假设我有一个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中是否不允许将函数传递给子进程。
为什么将其发送到后会asyncFn
变成?undefined
child
有关系JSON.stringify
吗?
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
});
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句