Alex Mills Alex Mills - 3 months ago 30
Node.js Question

Getting id of worker from inside worker process

Using the node.js Cluster module, it is straightforward to get the id of a worker process.

https://nodejs.org/api/cluster.html

that would be:

cluster.on('fork', function (worker) {
console.log('A worker', worker.id, 'was forked.');
});


but how can I get the
id
of the worker from inside the worker itself? How come the cluster module doesn't give the worker an id when the cluster forks the worker?

Do I really have to send the worker it's cluster id from the master process?

I am looking for something akin to:

process.id
(as opposed to process.pid)

or

process.worker.id


in any case, I am having trouble figuring out what the id of the worker is from inside the worker itself.

Answer
var cluster = require('cluster');

if (cluster.isMaster) {
  console.log('I am master');
  cluster.fork();
  cluster.fork();
} else if (cluster.isWorker) {
  console.log('I am worker #' + cluster.worker.id);
}

as in here