如何将函数/回调传递给Node.js中的子进程? [英] How to pass function/callback to child process in Node.js?
问题描述
假设我有一个 parent.js
,其中包含名为 parent
Let's say I have a parent.js
containing a method named 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中是否允许将函数传递给子进程。
I was wondering if passing functions to child process is not allowed in Node.js.
为什么 asyncFn
在发送到<$后变为 undefined
c $ c>孩子?
Why would asyncFn
become undefined
after it is sent to the child
?
是否与 JSON.stringify
有关?
推荐答案
JSON不支持序列化功能(至少开箱即用)。您可以先将函数转换为其字符串表示形式(通过 asyncFn.toString()
),然后在子进程中再次重新创建该函数。问题是你在这个过程中失去了范围和上下文,所以你的函数必须是独立的。
JSON doesn't support serializing functions (at least out of the box). You could convert the function to its string representation first (via asyncFn.toString()
) and then re-create the function again in the child process. The problem though is you lose scope and context with this process, so your function really has to be standalone.
完整的例子:
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
});
});
});
这篇关于如何将函数/回调传递给Node.js中的子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!