The cluster
module allows you to create child processes (workers) that can share server ports, enabling load balancing across multiple CPU cores. This improves the performance of Node.js applications. Here’s an example of clustering:
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello, World!');
}).listen(8000);
}