Search code examples
javascriptnode.jscluster-computing

Node.js - cluster.fork() - how to check number of worker within the worker?


When using cluster.fork, is there a way to check which number the worker created is within the worker itself?

if(cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);    
    // Fork workers
    for (let i = 0; i < cores.length; i++) {
        cluster.fork();
    }
    cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} died`);
    });
}
else{   
    var number = CLUSTER_NUM; //Get the spawned number of the worker
}

Solution

  • The cluster.worker.id should be an incremental number.

    if (cluster.isWorker) {
      console.log(cluster.worker.id); // 0, 1, 2 etc.
    }