【问题标题】:Getting chunks by newline in Node.js data stream在 Node.js 数据流中通过换行符获取块
【发布时间】:2020-05-07 17:59:40
【问题描述】:

在某一时刻,我认为您可以告诉 Node.js 子进程通过换行符来分块数据。如下所示,来自子进程的 stderr 数据事件正在触发字符和单词,而不是行。理想情况下,我可以传递一个标志来告诉流仅在一行数据准备好时触发数据事件。没有办法吗?

我有这个:

const sh = spawn('sh', [ b ], {
  cwd: cwd,
});

sh.stdout.pipe(fs.createWriteStream('/dev/null'));

var stderr = '';
var line = '';

sh.stderr.setEncoding('utf8');

sh.stderr.on('data', function (d) {

  //trying to split by newlines, but this is hairy logic
  const lines = String(d).split('\n');

  line += lines.shift();

  if(lines.length > 0){

    if (!String(d).match(/npm/ig) && !String(d).match(/npm/ig)) {
      stderr += d;
      process.stderr.write.apply(process.stderr, arguments);
    }

  }

});

并且在这个处理程序中返回的数据不是整行

sh.stderr.on('data', function (d) {
   // d is chunks of data but not whole lines
});

有没有办法告诉 stderr 在触发 'data' 事件之前等待换行符?

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您可以为此使用Transform stream

    实现并不是那么简单,所以我建议使用像 split2 这样的库。

    基本思路如下:

    const Transform = require('stream').Transform;
    const StringDecoder = require('string_decoder').StringDecoder;
    
    const decoder = new StringDecoder('utf8');
    
    const myTransform = new Transform({
       transform(chunk, encoding, cb) {
          if ( this._last === undefined ) { this._last = "" }
          this._last += decoder.write(chunk);
          var list = this._last.split(/\n/);          
          this._last = list.pop();
          for (var i = 0; i < list.length; i++) {
            this.push( list[i] );
          }
          cb();
      },
    
      flush(cb) {
          this._last += decoder.end()
          if (this._last) { this.push(this._last) }
          cb()
      }
    });
    
    sh.stderr.pipe( myTransform )
             .on('data', function (line) {
                  console.log("[" + line + "]");
             });    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      相关资源
      最近更新 更多