A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load.
The cluster module allows easy creation of child processes that all share server ports.
A cluster is a pool of similar workers running under a parent Node process. Workers are spawned using the fork() method of the child_processes module. This means workers can share server handles and use IPC (Inter-process communication) to communicate with the parent Node process.
Syntax
- const cluster = require("cluster")
- cluster.fork()
- cluster.isMaster
- cluster.isWorker
- cluster.schedulingPolicy
- cluster.setupMaster(settings)
- cluster.settings
- cluster.worker // in worker
- cluster.workers // in master
Remarks
Note that cluster.fork() spawns a child process that begins executing the current script from the beginning, in contrast to the fork() system call in C which clones the current process and continues from the instruction after the system call in both parent and child process.
Examples:const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
require('./server.js')();
}
This is your main server.js:
const http = require('http');
function startServer() {
const server = http.createServer((req, res) => {
res.writeHead(200); res.end('Hello Http');
});
server.listen(3000);
}
if(!module.parent) {
// Start server if file is run directly startServer();
} else {
// Export server, if file is referenced via cluster module.exports = startServer;
}
In this example,
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length; //number of CPUS
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork(); //creating child process
}
//on exit of cluster
cluster.on('exit', (worker, code, signal) => {
if (signal) {
console.log(`worker was killed by signal: ${signal}`);
} else if (code !== 0) {
console.log(`worker exited with error code: ${code}`);
} else {
console.log('worker success!');
}
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200); res.end('hello world\n');
}).listen(3000);
}

