Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Simple message passing between cluster master and workers in Node.js

View node-cluster-messaging.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
var cluster = require('cluster');
 
if (cluster.isWorker) {
 
console.log('Worker ' + process.pid + ' has started.');
 
// Send message to master process.
process.send({msgFromWorker: 'This is from worker ' + process.pid + '.'})
 
// Receive messages from the master process.
process.on('message', function(msg) {
console.log('Worker ' + process.pid + ' received message from master.', msg);
});
 
}
 
 
if (cluster.isMaster) {
 
console.log('Master ' + process.pid + ' has started.');
 
// Fork workers.
for (var i = 0; i < 2; i++) {
var worker = cluster.fork();
 
// Receive messages from this worker and handle them in the master process.
worker.on('message', function(msg) {
console.log('Master ' + process.pid + ' received message from worker ' + this.pid + '.', msg);
});
 
// Send a message from the master process to the worker.
worker.send({msgFromMaster: 'This is from master ' + process.pid + ' to worker ' + worker.pid + '.'});
}
 
// Be notified when worker processes die.
cluster.on('death', function(worker) {
console.log('Worker ' + worker.pid + ' died.');
});
 
}

thanks! great ref.

This won't work. var inside for?

worker will hold the last worker forked, not each one (specially inside the event callback).

should work fine, as the variable is only being used inside that particular block. if it was leaking outside the block, then yes, it would be a problem (and should be in a closure, or have some kind of binding). nice example, thanks!

how do u pass message between workers.....pass message to master makes master a bottleneck..............

Good example.
Need to replace this.pid for this.process.pid on newer Node versions.
Same for worker.pid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.