Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Cluster in nodeJS

Introduction
  1. A single instance of Node.js runs in a single thread
  2. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load
  3. The cluster module allows easy creation of child processes that all share server ports
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    console.log(`Master is running`, process.pid);
    // Fork workers.
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }
    cluster.on('exit', (worker, code, signal) => {
        console.log(`worker died`, worker.process.pid);
    });
} else {
    http.createServer((req, res) => {
        res.writeHead(200);
        res.end('hello world\n');
    }).listen(8000);
    console.log(`Worker started`, process.pid);
}

// Master 67188 is running
// Worker 67191 started
// Worker 67190 started
// Worker 67189 started
// Worker 67192 started