Is there a way to send a message from a worker to other workers in node.js?

3k Views Asked by At

I can use process.send to send a message from a worker to a master. I can use the following code to send a message from the master to each worker.

for (var id in cluster.workers) {
  cluster.workers[id].send({command: 'doSomething'});
}

To send a message from a worker to other workers I have to send a message to the master and then have it forward the message. This results in the original sender also receiving the message and is something that I'd like to avoid but I can live with it!

I also tried sending the message directly from the worker like it's done in the master but cluster.workers is undefined in workers.

Is there any other way to do this?

2

There are 2 best solutions below

0
On BEST ANSWER

You can compare pid's of the sender and the recipients:

worker.on('message', function(msg) {

  for (var id in cluster.workers) {

    if (cluster.workers[id].process.pid !== this.process.pid) {

      cluster.workers[id].send({
        command: 'doSomething',
        from: this.process.pid
      });

    }

  }

}
0
On

I have created a simple package called ipc-messenger that helps to do this. It provides an abstraction where details are hidden from the user.

The function messageSiblings can be used to send messages only to other workers and messageWorkers to send messages to all workers.

Example:

var ipcm = require('ipc-messenger')
ipcm.messageSiblings('hello')