Skip to content

Instantly share code, notes, and snippets.

@jpoehls
Created March 29, 2012 01:48
Show Gist options
  • Star 79 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • Save jpoehls/2232358 to your computer and use it in GitHub Desktop.
Save jpoehls/2232358 to your computer and use it in GitHub Desktop.
Simple message passing between cluster master and workers in Node.js
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.');
});
}
@svkrclg
Copy link

svkrclg commented Feb 24, 2021

Just to NOTE: workers keep on sending some internal nodejs related data to the master, so keep a check on msg key

@oneEyedSunday
Copy link

Great stuff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment