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

11

假设我有一个包含名为parent的方法的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*/ }
};

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

与此同时,在 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
        });
    });
});

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

为什么asyncFn在发送到child后会变成undefined

这与JSON.stringify有关吗?

1个回答

11

JSON不支持序列化函数(至少不是开箱即用的)。您可以首先将函数转换为其字符串表示形式(通过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();
  });
}

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

1
哎呀,你比我快了 :P - loganfsmyth
new Function('return ' + funcString)(); 对于不受信任的代码来说安全吗? - M4GNV5
@M4GNV5 不行,你需要在子进程中使用 vm 模块,并采取适当的操作系统级别保护措施来确保与“不受信任的代码”安全。 - mscdex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接