Skip to content

Instantly share code, notes, and snippets.

@hamidreza-s
Created June 21, 2013 11:58
Show Gist options
  • Save hamidreza-s/5830734 to your computer and use it in GitHub Desktop.
Save hamidreza-s/5830734 to your computer and use it in GitHub Desktop.
A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load.
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
// Fork event of workers
cluster.on('fork', function(worker) {
console.log(worker.process.pid + ':is forked');
});
// Online event of workers
cluster.on('online', function(worker) {
console.log(worker.process.pid + ':is online');
});
// Listening event of workers
cluster.on('listening', function(worker, address) {
console.log(worker.process.pid + ':is listening');
});
// Exiting event of workers
cluster.on('exit', function(worker, code, signal) {
console.log(worker.process.pid + ':is exited');
// Now fork a new worker
cluster.fork();
});
} else {
// Run server for each worker
http.createServer(function(req, res) {
res.writeHead(200);
res.end("Hello World\n");
}).listen(8000);
// Throw an error for test
var randNum = Math.random() * 10000;
setTimeout(function(){
throw new Error('Oh no! An error!');
}, randNum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment