Cluster Example
suggest changeA single instance of Node.js runs JavaScript on one thread. To take advantage of multi-core systems, an application can be launched as a cluster of Node.js processes.
The cluster module creates child processes that can share server ports. cluster.isMaster still works; since Node.js 16 the preferred name is cluster.isPrimary.
The following example creates one worker per CPU in the main process. The workers share the load.
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);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents