var cluster = require('cluster');

cluster.isMaster

cluster.isWorker

var cluster = require('cluster');

var http = require('http');

var numCPUs = require('os').cpus().length;





if(cluster.isMaster) {

for(var i=0;i<numCPUs;i++) {

cluster.fork();

}

cluster.on('exit', function(worker, code, signal) {

console.log('worker ' + worker.process.pid + ' died');

});

} else {

http.createServer(function(req, res) {

res.writeHead(200);

res.end("Hello World

");

}).listen(8080);

}

if(cluster.isMaster)

for(var i=0;i<numCPUs;i++) {

cluster.fork();

}

cluster.on('exit', function(worker, code, signal))

fork

online

listening

disconnect

exit

In this post we will show you whats the use of cluster module in Nodejs. Node provides you with a module called cluster that allows you to delegate work to child processes. This module allows you to write Node programs that itself start many other Node programs and assign work to them for load balancing.One thing to know that Node program which you have created will manage all the other Node programs but will not take part on each and every transaction. That means if a child Node program is interacting with a database they do it directly but not through the master Node program.// This is how you can call the cluster module in NodejsYou can check if the current process is master or worker using the below commands..// returns true if the process is master// returns true if the process is not master i.e. process that is created by masterLets take an example to see how cluster works. The example taken from nodejs.org The process can be either a master or a worker. So at first we are checking that process is master or not using. cluster.fork() is used to create child process that is identical to master. So in the above example we are creating child processes for all CPUs available, to distribute the work across all of the CPUs.The above code is nothing but creating child process using cluster.fork().When any of the worker process die, the cluster module will emit the 'exit' event. So using the above command we are checking that if any worker process is dead or not, if dead do something.There are many events attached with the child processes like...1.// when a new worker is forked the cluster module will emit a 'fork' event2.// when master process receives an online message (emitted by woker process after it is forked), it will emit this event3.// after calling listen() from a worker, 'listening' event is emitted on cluster4.// this is emitted after the worker process is disconnected from the master5.// when any of the worker process die, the cluster module will emit the 'exit' event.For more Information about cluster you can check the documentation in nodejs.orgPlease Like and Share the Blog, if you find it interesting and helpful.