Created
February 15, 2013 23:15
-
-
Save ithinkihaveacat/4964390 to your computer and use it in GitHub Desktop.
Creates event-listener-style communication between parent and child.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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