如何将函数/callback传递给Node.js中的subprocess?

比方说,我有一个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(); }); } 

同时在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中传递函数给subprocess。

为什么asyncFn在发送给child之后会变得undefined

它与JSON.stringify有关吗?

JSON不支持序列化function(至less开箱即用)。 您可以先将函数转换为string表示forms(通过asyncFn.toString() ),然后在subprocess中再次重新创build该函数。 但问题是你失去了这个过程的范围和上下文,所以你的function必须是独立的。

完整的例子:

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