【问题标题】:NodeJS spawn stdout string formatNodeJS 生成标准输出字符串格式
【发布时间】:2013-12-14 18:39:30
【问题描述】:

我正在节点中生成一个进程并像这样跟踪命令的输出:

proc.stdout.on("data", function (data) {
    console.log(data.toString());
});

效果很好,但是输出似乎分行:

npm http
 304 https://registry.npmjs.org/underscore

以上只是npm install 的回复中的一行。通常这一切都在一行中,它还在响应之前和之后添加换行符。有没有办法让数据输出看起来像标准运行,即逐行?

【问题讨论】:

    标签: node.js stdout spawn


    【解决方案1】:

    流被缓冲并在需要时(可以这么说)发出 data 事件,而不是像文本行这样的严格边界。

    但是您可以使用readline 模块为您将缓冲区解析为行:

    var child_process = require('child_process');
    var readline      = require('readline');
    var proc          = child_process.spawn(...);
    
    readline.createInterface({
      input     : proc.stdout,
      terminal  : false
    }).on('line', function(line) {
      console.log(line);
    });
    

    【讨论】:

      【解决方案2】:

      我想到了 3 个解决方案:

      // solution #1
      process.stdout.write(data);
      
      // solution #2
      console.log(data.toString().replace(/[\n\r]/g, ""));
      
      // solution #3
      var child_process = require('child_process');
      var readline = require('readline');
      var proc = child_process.spawn(...);
      readline.createInterface({
        input: proc.stdout,
        terminal: false
      }).on('line', function(line) {
        console.log(line);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-31
        • 1970-01-01
        • 2015-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-10
        • 2012-04-02
        相关资源
        最近更新 更多