1

我正在尝试在下一个代码中运行子进程:

run = function (cmd, callback) {
    var spawn = require('child_process').spawn;
    var command = spawn(cmd);

    var result = '';

    command.stdout.on('data', function (data) {
        result += data.toString();
    });

    command.on('exit', function () {
        callback(result);
    });
}

execQuery = function (cmd) {
    var result = {
        errnum: 0,
        error: 'No errors.',
        body: ''
    };

    run(cmd, function (message) {
        result.body = message;

        console.log(message);
    });

    return result;
}

执行后 execQuery('ls') result.body始终为空,但console.log包含值。

4

1 回答 1

1

I ran a quick test and the command's exit event is firing before all of stdouts data is drained. I at least got the output captured and printed if I changed your exit handler to look for command.stdout's end event.

command.stdout.on('end', function () {
    callback(result);
});

That should help a bit. Note there are existing libraries you might want to use for this and a truly correct implementation would be significantly more involved than what you have, but my change should address your current roadblock problem.

Random tip: it is the node convention to always reserve the first argument of callback functions for an error and your snippet is inconsistent with that convention. You probably should adjust to match the convention.

Oh sorry, let me address your question about result.body. The run function is ASYNCHRONOUS! That means that your return result; line of code executes BEFORE the run callback body where result.body = message; is. You can't use return values like that anywhere in node when you have I/O involved. You have to use a callback.

于 2013-05-29T04:45:23.993 回答