Clustering in Node.js

25 / Feb / 2013 by Shreyance Jain 1 comments

Node.js is single threaded so it runs one process on a single CPU, as the power of Node.js is its performance and speed it doesn’t seem good to use only one CPU in a multi-core system. For utilizing all the CPUs, Node.js allows us to create a network of processes that all shares the same port.

Create a file named clusterExample.js

var cluster = require('cluster'); //use the cluster module
var http = require('http')
var noOfCPUs = require('os').cpus().length(); //count the no of CPUs available

if (cluster.isMaster) { //Check if the cluster is master or worker process
  for (var i = 0; i < noOfCPUs; i++) {
    cluster.fork() //creates a worker process
  }

  //give message on console when worker process starts listening
  cluster.on('listening', function (worker, address) {
    console.log("A new worker process with #" + worker.id + " is now listening to " + ":" + address.port);
  });

  //give message on console and create a new worker porcess when a worker process dies
  cluster.on('exit', function (worker, code, signal) {
    console.log("worker process with #" + worker.process.pid + "died");
    cluster.fork(); //create the new worker process
  });
} else {
  http.createServer(function (req, res) {
    res.writeHead(200);
    res.end("Cluster Example\n");
  }).listen(9090);
}

Now run the clusterExample.js

node clusterExample.js

Output:

A new worker process with #1 is now listening to :9090
A new worker process with #2 is now listening to :9090
A new worker process with #3 is now listening to :9090
A new worker process with #4 is now listening to :9090

Shreyance Jain
shreyance@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (1 “Clustering in Node.js”)

  1. WimeFeeledo

    There is noticeably a bundle to know about this. I assume you created certain nice points in functions also.

    [URL=http://www.topsmichaelkorsbags.com/michael-kors-shoulder-bags-c-41.html]michael kors men[/URL]

    Reply

Leave a comment -