NodeJs — Clustering in Node.js
Node.js runs on a single thread by default, which can limit performance on multi-core systems. The 'cluster' module allows you to spawn multiple worker processes that share the same server port, improving scalability and performance.
const cluster = require('cluster');
const http = require('http');
const os = require('os');
if (cluster.isMaster) {
const cpuCount = os.cpus().length;
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
cluster.on('exit', () => {
console.log('Worker exited, creating a new one...');
cluster.fork();
});
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello from Clustered Server');
}).listen(3000);
}