【问题标题】:Why does output come out from STDERR and not STDOUT when using child_process.exec for Node.js?为什么在 Node.js 中使用 child_process.exec 时输出来自 STDERR 而不是 STDOUT?
【发布时间】:2014-08-03 16:25:15
【问题描述】:

我正在尝试将我的 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,我什至尝试切换 stdout 和 stderr 的 console.log 的位置,仍然得到相同的结果。

标签: javascript node.js phantomjs stdout child-process


【解决方案1】:

根据Dan Davis,您可以切换errorstderrstdout - 不是console.log 语句,而是函数中参数的顺序。以下是the 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 的位置,所以它是空的。

【讨论】:

  • 谢谢。这行得通。我不知道参数的顺序很重要,但现在我知道了。
猜你喜欢
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
相关资源
最近更新 更多