Skip to content Skip to sidebar Skip to footer

How To Pass Function/callback To Child Process In Node.js?

Let's say I have a parent.js containing a method named parent var childProcess = require('child_process'); var options = { someData: {a:1, b:2, c:3}, asyncFn: function (da

Solution 1:

JSON doesn't support serializing functions (at least out of the box). You could convert the function to its string representation first (via asyncFn.toString()) and then re-create the function again in the child process. The problem though is you lose scope and context with this process, so your function really has to be standalone.

Complete example:

parent.js:

var childProcess = require('child_process');

var options = {
  someData: {a:1, b:2, c:3},
  asyncFn: function (data, callback) { /*do other async stuff here*/ }
};
options.asyncFn = options.asyncFn.toString();

functionParent(options, callback) {
  var child = childProcess.fork('./child');
  child.send({
    method: method,
    options: options
  });
  child.on('message', function(data){
    callback(data,err, data,result);
    child.kill();
  });
}

child.js:

process.on('message', function(data){
  var method = data.method;
  var options = data.options;
  var someData = options.someData;
  var asyncFn = newFunction('return ' + options.asyncFn)();
  asyncFn(someData, function(err, result){
    process.send({
      err: err,
      result: result
    });
  });
});

Post a Comment for "How To Pass Function/callback To Child Process In Node.js?"