cluster
Created: 2016-05-03 08:48:20 -0700 Modified: 2016-05-03 08:54:51 -0700
NodeJS provides a ‘cluster’ module by default. This allows you to start the same program in many different processes and communicate between them.
You should likely perform logging by sending all log messages over a cluster transport if cluster.isWorker is true. To accomplish this:
- Master
- worker.on(‘message’, handlerFunction)
- Worker
- process.send({type: ‘log’, text: ‘blah’});
The basic template looks something like what’s coded below. Basically, the master needs to specify a custom port for “—debug” for all workers so that they aren’t all listening on the same port.
const env = {
anyEnvVars: ‘go here’
};
// If ‘—debug’ was specified as a flag to the master, then we’ll pass that off
// to the workers with their own specific debugger ports.
//
// Note: despite having ‘—debug’ specified, you may still need to hit the Pause
// button in Chrome or put a ‘debugger’ at the beginning of the game server
// worker.
//
// Note #2: you do not need —debug running on the master in order to debug
// workers.
const debug = process.execArgv.indexOf(‘—debug’) !== -1;
cluster.setupMaster({
execArgv: process.execArgv.filter((arg) => arg !== ‘—debug’)
});
if (debug) {
cluster.settings.execArgv.push(‘—debug=’ + (5859 + workerId));
}
cluster.fork(env);
if (debug) {
cluster.settings.execArgv.pop();
}