如何将函数/回调传递给Node.js中的子进程?

kit*_*kit 8 javascript child-process node.js

假设我有一个parent.js名为的方法parent

var childProcess = require('child_process');

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

function Parent(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();
    });
}
Run Code Online (Sandbox Code Playgroud)

同时在 child.js

process.on('message', function(data){
    var method = data.method;
    var options = data.options;
    var someData = options.someData;
    var asyncFn = options.asyncFn; // asyncFn is undefined at here
    asyncFn(someData, function(err, result){
        process.send({
            err: err,
            result: result
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

我想知道Node.js中是否允许将函数传递给子进程.

为什么会asyncFn成为undefined它被送到后child

它与JSON.stringify?有关吗?

msc*_*dex 8

JSON不支持序列化功能(至少开箱即用).您可以先将函数转换为其字符串表示形式(via asyncFn.toString()),然后在子进程中再次重新创建该函数.但问题是你在这个过程中失去了范围和上下文,所以你的功能必须是独立的.

完整的例子:

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();

function Parent(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();
  });
}
Run Code Online (Sandbox Code Playgroud)

child.js:

process.on('message', function(data){
  var method = data.method;
  var options = data.options;
  var someData = options.someData;
  var asyncFn = new Function('return ' + options.asyncFn)();
  asyncFn(someData, function(err, result){
    process.send({
      err: err,
      result: result
    });
  });
});
Run Code Online (Sandbox Code Playgroud)