Answer the question
In order to leave comments, you need to log in
Do I understand correctly how cluster works in NodeJS?
var http = require('http');
var cluster = require('cluster');
var server = http.createServer();
server.on('request', ...);
server.on('error', ...);
var rand = Math.random();
if (cluster.isMaster){
var i = 4;
while(i--) cluster.fork();
}
else {
console.log(rand);
server.listen(8888);
}
var http = require('http');
var cluster = require('cluster');
var server = http.createServer();
server.on('request', ...);
server.on('error', ...);
var rand = Math.random();
console.log(rand);
server.listen(8888);
if (cluster.isWorker) { ... }
?
Answer the question
In order to leave comments, you need to log in
cluster.isWorker is equal to the !cluster.isMaster node
, this is directly stated in the docs (it is the negation of cluster.isMaster) so wrapping is not necessary once there is already if(cluster.isMaster){}else
child processes understand that they are not masters by variable process.env.NODE_UNIQUE_ID if defined then I am a worker.
All this can be viewed directly in the cluster code here https://github.com/joyent/node/blob/master/lib/clu...
see function createWorkerProcess(id, env)
You can create a cluster in nodejs only for the isMaster process and after the if check, spawn a child process on each server core and the number of child processes must match the number of cores. And it’s better to create a cluster in index.js which will be the entry point (npm start should run node index.js), and separately create server.js with the server creation code.
Entry point code example:
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Leader ${process.pid} is running`);
// 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 {
require('./server.js');
console.log(`Worker ${process.pid} started`);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question