Node.js Child Process


Child Processes are the way to go when one wants to run processes independently with different initialization and concerns. Like forks in clusters, a child_process runs in its thread, but unlike forks, it has a way to communicate with its parent.

The communication goes both ways, so parent and child can listen for messages and send messages.

Parent (../parent.js)

var child_process = require('child_process');
console.log('[Parent]', 'initalize');

var child1 = child_process.fork(__dirname + '/child');
child1.on('message', function(msg) { 
    console.log('[Parent]', 'Answer from child: ', msg); 

// one can send as many messages as one want
child1.send('Hello'); // Hello to you too :)
child1.send('Hello'); // Hello to you too :)

// one can also have multiple children
var child2 = child_process.fork(__dirname + '/child');

Child (../child.js)

// here would one initialize this child
// this will be executed only once
console.log('[Child]', 'initalize');

// here one listens for new tasks from the parent
process.on('message', function(messageFromParent) {
    //do some intense work here
    console.log('[Child]', 'Child doing some intense work');

    if(messageFromParent == 'Hello') process.send('Hello to you too :)');
    else process.send('what?');

Next to message one can listen to many events like 'error', 'connected' or 'disconnect'.

Starting a child process has a certain cost associated with it. One would want to spawn as few of them as possible.