为什么使用child_process时输出来自STDERR而不是STDOUT ?执行为Node.js

Why does output come out from STDERR and not STDOUT when using child_process.exec for Node.js?

本文关键字:STDOUT 执行 js Node STDERR child process 输出 为什么      更新时间:2023-09-26

我正试图缓冲从我的phantomjs脚本到nodejs的结果,但由于某种原因,缓冲结果不断从STDERR出来,但不是STDOUT,即使似乎没有错误。

NodeJS代码:

var exec = require('child_process').exec;
exec('phantomjs console.js', function(stdout, stderr, error){
        if (error !== null) {
            console.log('exec error: ' + error);
        }
        console.log("Standard Output: " + stdout + " ");
        console.log("Error Output: " + stderr + " ");
    });

PhantomJS代码(console.js):

console.log("Hello world!");
phantom.exit();

我得到的结果:

exec error: 
Standard Output: null 
Error Output: Hello world!

根据Dan Davis,您切换了error, stderrstdout -不是console.log语句,而是函数中参数的顺序。以下是按照docs

的正确顺序
var exec = require('child_process').exec;
exec('phantomjs console.js', function(error, stdout, stderr){
    if (error !== null) {
        console.log('exec error: ' + error);
    }
    console.log("Standard Output: " + stdout + " ");
    console.log("Error Output: " + stderr + " ");
});

输出的原因是您的stdout在实际error应该在的地方,所以它是空的。你的stderr在实际的stdout的位置,所以它接收输出。您的error在实际stderr的位置,所以它是空的。