Clustering in Node.js refers to the technique of spawning multiple processes (workers) to take advantage of multi-core systems.
This allows Node.js applications to handle more requests by distributing the workload across multiple CPU cores.
The built-in cluster
module in Node.js provides an easy way to implement clustering.
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers equal to the number of CPU cores
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, an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello from worker
');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
© www.thecoderjob.com. All Rights Reserved. Designed by HTML Codex