Callback exception [TypeError: listener must be a function]

Callback exception [TypeError: listener must be a function]

我编写了一个简单的 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);
});

现在它不再抛出错误,但请注意,使用异步数据并不能保证执行顺序,因此您可能会得到意想不到的结果。

问题是您不能在另一个函数中传递带有参数的函数。您必须创建一个匿名函数并在其中发送参数。