Skip to content

Instantly share code, notes, and snippets.

@arch1t3ct
Last active December 19, 2015 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arch1t3ct/6011061 to your computer and use it in GitHub Desktop.
Save arch1t3ct/6011061 to your computer and use it in GitHub Desktop.
A demonstration on how to pass data from a killed worker to a new one when using Node.js cluster module. More information at http://a.ndri.us/blog/node-js-cluster-worker-persistent-data
var cluster = require('cluster');
if (true === cluster.isMaster) {
var map = {};
function forkWorker(data) {
var worker = cluster.fork({data: data});
map[worker.id] = data;
}
forkWorker('Alice');
forkWorker('Bob');
forkWorker('Ted');
cluster.on('exit', function (worker, code, signal) {
console.log(worker.process.env.data); // This will be undefined. Therefore we need a map.
var data = map[worker.id];
delete map[worker.id]; // We don't need old id mapping.
forkWorker(data);
});
} else {
console.log(process.env.data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment