Cluster ?

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.

The cluster module allows you to easily create child processes that all share server ports,this gives your Node app access to the full power of your server.

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

if (cluster.isMaster) {
  console.log('I am the master,launching Workers!');
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {

  Object.keys(cluster.workers).forEach(function(id) {
    console.log("I am running with ID : "+cluster.workers[id];

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + + ' died');
} else {
   console.log('I am a worker');
  // Workers can share any TCP connection
  // In this case its a HTTP server
  http.createServer(function(req, res) {
    res.end("hello world\n");

If you observe the code, we are loading Cluster module in first line. Then we are counting how many cores do we have in our machine. Then in “if” condition , we are checking that if its Master process then create the copy of same process by number of core time.

If it is not the Master machine then basically run our normal Node program. So there would be one process which is master which in turn create processes number of core time.

In my case, i have Intel i3 consist of 4 core processor. If i run this code, i will get this output in terminal.


My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Node.Js Tagged with: