Fork a child process and inject dependency

user1082754 picture user1082754 · Mar 12, 2013 · Viewed 23.1k times · Source

I currently have an operation in a module that is blocking, so I'm looking at making this into a child process that I fork instead.

If I want to do that, then I of course need to modify the architecture of my module. The module requires that a dependency is injected by calling the module as a function, passing in the dependency, like so:

var dependency = { name: "Bob" }
require('worker')(dependency)

Then in my worker module:

module.exports = function (dependency) {
  // Outputs { name: "Bob" }
  console.log(dependency)
}

How can I turn this example into a child process being forked?

Answer

UpTheCreek picture UpTheCreek · Mar 12, 2013

When using .fork() you are spinning up a completely separate process, so you are not able to pass around references between the parent and child processes (and are limited to messaging after the process has been created).

An approach not requiring messaging is to pass arguments (in an array) when you fork the process. Although I believe you'll have to stick with simple string/number values (but it looks like this might be enough for you from the code). Eg.:

At top level:

var name = 'bob'
var args = [name];
var childProcess = require('child_process').fork(__dirname + '/worker', args);

In the worker process:

var name = process.argv[2]; //AFIAK elements 0 and 1 are already populated with env info

Update

If you really want to go the messaging route (which I'd hesitate to recommend if you already need to send messages), then you could differentiate between the types of messages something like this (there may be more elegant ways):

At top level:

var childProcess = require('child_process').fork(__dirname + '/worker');
childProcess.send({msgtype:'dependencies', content:dependencies});

//Then to send 'normal' message:
childProcess.send({msgtype:'myothermessagetype', content:'some content'}

In worker process:

process.on('message', function(msg){
    if(msg.mtype == 'dependencies') {
       var dependencies = msg.content;
       //Do something with dependencies
    } else if(msg.mtype == 'myothermessagetype') {
       var normalmessage = msg.content;
       //Do something in response to normal message.
    }
});