我编写了一个简单的 NodeJS 程序来执行 shell 脚本。我叉出一个 child 并尝试执行脚本。我已经在退出时向 child 提供了回调,如下所示。但是当我尝试运行该程序时它抛出异常。我哪里错了?
var exec = require('child_process').exec;
function callXmlAgent(callback) {
try {
var child = exec('./a.sh');
var response = { stdout: '', stderr: '', errCode: -1 };
child.stdout.on('data', function (data) {
response.stdout += data;
});
child.stderr.on('data', function (data) {
response.stderr += data;
});
child.on('close', function (errCode) {
if (errCode) {
response.errCode = errCode;
}
});
child.on('exit', callback(response));
process.on('exit', function () {
// If by chance the parent exits, the child is killed instantly
child.kill();
});
} catch(exception) {
console.log(exception);
}
}
function foo(response) {
console.log(response)
};
callXmlAgent(foo);
我得到的输出是:
{ stdout: '', stderr: '', errCode: -1 }
[TypeError: listener must be a function]
最佳答案
使用以下代码修改子退出事件:
child.on('exit', function() {
callback(response);
});
现在它不再抛出错误,但请注意,使用异步数据并不能保证执行顺序,因此您可能会得到意想不到的结果。
问题是您不能在另一个函数中传递带参数的函数。您必须创建一个匿名函数并在其中发送参数。
关于javascript - 回调异常[TypeError : listener must be a function],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30346958/