Skip to content

Instantly share code, notes, and snippets.

@jmervine jmervine/server.js
Created Jun 27, 2013

Embed
What would you like to do?
Clustering in Node.js
/**
* Libraries
**/
var cluster = require('cluster');
var datefmt = require('dateformat');
/**
* Setup
**/
var workers = parseInt(process.env.CLUSTER_WORKERS, 8);
cluster.setupMaster({
exec : "app.js",
});
/**
* Utilities
**/
function say(message) {
console.log("[SERVER] " + message);
};
/**
* Startup Messaging
**/
say("Master starting:");
say("time => " + datefmt(new Date(), "ddd, dd mmm yyyy hh:MM:ss Z"));
say("pid => " + process.pid);
say("environment => " + process.env.NODE_ENV);
/**
* Fork Workers
**/
say("Workers starting:");
for (var i = 0; i < workers; i++) {
cluster.fork();
}
/**
* Worker Event Handlers
**/
cluster.on('exit', function(worker, code, signal) {
say('worker => with pid: ' + worker.process.pid + ', died. Restarting...');
cluster.fork();
});
cluster.on('online', function(worker) {
say('worker => start with pid: ' + worker.process.pid + '.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.