Run parts of Cocos from Node.js

I’m building a game in Cocos Creator, and also a server. I would like to be able to do some server-side checks in Node.js by re-using a few of the JavaScript objects I wrote for the game. These are not Components, but plain vanilla JavaScript objects.

It works a little bit, until I try to use any cc functions. So I tried including the Cocos2D JavaScript library like this:

if(typeof cc === 'undefined')
    require("../../build/web-desktop/cocos2d-js-min");

This fails with the error:

ReferenceError: window is not defined

Which is understandable, as Node.js doesn’t have a window object. Is there a better way to do this, to include cc functions in a Node.js project?

It’s not officially supported in cocos but you can try.

First checkout the cocos engine repo: https://github.com/cocos-creator/engine

And in node.js:
Declare some dummy modules:

global.CC_EDITOR = true;
global.Editor = { isMainProcess: true, versions: {} };

Finally just require the engine repo by using node.js

var cc = require('engine');

It should work but only some basic module is available, cc.Node and cc.Component will not work in node environment.

Where do I put the cocos engine repo in relation to the cocos project?

Goto Preferences panel and click [Native Develop Tab]. And follow the guide to set the path to your customized JavaScript engine.

It’s sort of working, but I was really hoping to be able to use cc.eventManager, and it’s undefined. Do you know if there’s a way to include it?

Of less importance, cc.error, cc.warn, and cc.log all do not work either.

Node.js not contains DOM so many module will not work. But you can try to require the engine/cocos2d/core/event by yourself.
To enable cc.error, cc.warn and cc.log, just modify the CCDebugger.js and require it.

Is there a way to tell the Cocos Creator compiler not to compile one line or block? I want it to execute in Node.js, but I want the Cocos Creator compiler to skip it.

I know how to make Cocos skip the code at runtime, but that’s not good enough – I’m getting compile-time errors.

EDIT: I realized that I might be looking for a preprocessor command. When Cocos Creator says “Compiled successfully” in the console, what compiler is it using, and does it have preprocessor commands?

Creator use browserify and uglifyjs to compile your scripts, but no macro for node.js can be used… you can only use CC_EDITOR (or !CC_EDITOR)

I’m interested in hearing how this worked out for you. I’ve thought about making a physics based multiplayer game to run servers with multiple instances of CC with Box2d enabled.

I’ve done some semi successful tests by just running a Box2d library on the server and syncing it with CC but it’s extra work to have two separate coordinate systems and game objects since I’d have to code everything twice under slightly different environments.

Would it be possible to run the engine + physics not using requestAnimationFrame?