【问题标题】:Order of process.stdout.on( 'data', ... ) and process.stderr.on( 'data', ... )process.stdout.on( 'data', ... ) 和 process.stderr.on( 'data', ... ) 的顺序
【发布时间】:2016-12-03 06:04:14
【问题描述】:

我正在编写一个电子应用程序,这个应用程序处理从电子内部执行的终端命令。

我在执行npm ls 命令时遇到了麻烦。从 cli 运行它时,依赖关系树会打印到 stdout,最后可能会出现一些来自 stderr 的警告。

请看下面的截图。

correct output

我稍微挖掘了npm 源代码,它首先记录结果,然后打印错误。所以它就像我在终端中看到的一样。

但是,当我对 child_process spawn (或 exec 没关系)执行相同操作时,顺序不同。

puzzled output

看起来由于stdout 数据的大块,stderr 打印在所有stdout 的中间。

下面我写的代码:

// this is mapped to require( 'child_process' ).spawn
this.$set( 'process', this.spawn(
  'npm',
  [ 'ls' ],
  {
    cwd   : options.cwd,

    // following are only my tryouts - nothing helped :(

    // some npm ls command destroy kill the scripts
    // with too big buffers in stdout
    // maxBuffer : 1024 * 5000
    // shell : true
  }
) );

// this.handleData is only printing out for nwo
this.process.stdout.on( 'data', this.handleData );
this.process.stderr.on( 'data', this.handleData );

当大数据来自 stdout 和来自 stderr 的小数据时,stderr 会在中间被调用。

这是预期的行为吗?我可以以某种方式解决此问题以检索与终端中相同的行为吗?

谢谢。 :)

【问题讨论】:

    标签: node.js electron


    【解决方案1】:

    process.stdoutprocess.stderr 不能保证以任何特定的相对于彼此的顺序发出数据,因此正如您所注意到的,只要任一管道中有任何数量的数据,您的回调就可能会被调用。

    如果您想确保仅在所有 stdout 完成后才处理 stderr,您可能希望收听 stdout.on('end', cb) 并仅在该回调 cb 中调用 stderr.on('data', this.handleData)


    也就是说,如果您只想要npm ls 的结果,也许您可​​以考虑尝试use the npm module programmatically?文档并不令人惊奇,但它是一个更高级别的 API。

    【讨论】:

    • 我也想过这个问题。用例是更新任何stdoutstderr。当我等待所有stdout 完成直到我抓住stderr 时,这可能会导致其他命令出现不同的问题,中间需要stderr。 :( npm 命令只是我发现它的情况。可能有完全不同的命令。
    猜你喜欢
    • 2019-10-12
    • 2018-07-03
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多