Javascript 如何将函数/回调传递给Node.js中的子进程?
假设我有一个Javascript 如何将函数/回调传递给Node.js中的子进程?,javascript,node.js,child-process,Javascript,Node.js,Child Process,假设我有一个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 =
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
在发送到子项后会变成未定义的
它是否与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();
});
}
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
});
});
});
child.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();
});
}
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
});
});
});
啊,比我快:Pisnewfunction('return'+funcString)()
safe for untrusted code?@M4GNV5否,您需要在子进程中使用vm
模块,并提供适当的操作系统级别保护,以确保“untrusted code”的安全