Skip to content

Instantly share code, notes, and snippets.

@ithinkihaveacat
Created February 15, 2013 23:15
Show Gist options
  • Save ithinkihaveacat/4964390 to your computer and use it in GitHub Desktop.
Save ithinkihaveacat/4964390 to your computer and use it in GitHub Desktop.
Creates event-listener-style communication between parent and child.
function onChild(child, event, callback) {
child.on('message', (function (args) {
if (args[0] === event) {
callback.apply(null, Array.prototype.slice.call(args, 1));
}
}));
}
function emitChild(/* child, event, [arg1], [arg2], [...] */) {
var args = Array.prototype.slice.call(arguments);
var child = args.shift();
child.send.call(child, args);
}
function onParent(event, callback) {
process.on('message', function (args) {
if (args[0] === event) {
callback.apply(null, Array.prototype.slice.call(args, 1));
}
});
}
function emitParent(/* event, [arg1], [arg2], [...] */) {
process.send.call(process, Array.prototype.slice.call(arguments));
}
// EXAMPLE
// Server
var child = require('child_process').fork(__dirname + '/static.js');
onChild(child, 'request', function (server) {
// ...
});
emitChild(child, 'listen', port);
// Child
onParent('listen', function (port) {
// ...
})
emitParent('request', request);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment