【问题标题】:Find out if the stream chunk is the last找出流块是否是最后一个
【发布时间】:2018-03-11 16:58:36
【问题描述】:

在转换函数中编写 NodeJS 转换流时,我如何知道该块是最后一个块还是没有任何新块到来。

_transform(chunk: any, encoding: string, callback: Function): void {
    // accumulating chunks here to buffer
    // so that I need to do some processing on the whole buffer
    // and I need to understand when to do that
}

所以我需要知道进入 Stream 的块何时结束,对由所有块组成的缓冲区进行一些处理,然后从流中推送处理后的数据。

【问题讨论】:

标签: javascript node.js typescript


【解决方案1】:

使用through2

fs.createReadStream('/tmp/important.dat')
  .pipe(through2(
    (chunk, enc, cb) => cb(null, chunk), // transform is a noop
    function (cb) { // FLUSH FUNCTION
      this.push('tacking on an extra buffer to the end');
      cb();
    }
  ))
  .pipe(fs.createWriteStream('/tmp/wut.txt'));   

【讨论】:

  • 这对我有帮助,不需要再保留计数器了 :-)
【解决方案2】:

例子,

const COUNTER_NULL_SYMBOL = Symbol('COUNTER_NULL_SYMBOL');

const Counter = () => {
  let data = COUNTER_NULL_SYMBOL;
  let counter = 1;
  let first = true;

  const counterStream = new Transform({

    objectMode: true,
    decodeStrings: false,
    highWaterMark: 1,

    transform(chunk, encoding, callback) {
      if (data === COUNTER_NULL_SYMBOL) {
        data = chunk;
        return callback();
      } else {
        this.push({data, counter, last: false, first});
        first = false;

        counter++;
        data = chunk;

        return callback();
      }
    },
  });

  counterStream._flush = function (callback) {
    if (data === COUNTER_NULL_SYMBOL) {
      return callback();
    } else {
      this.push({data, counter, last: true, first});
      return callback();
    }
  };

  return counterStream;
};

【讨论】:

    【解决方案3】:

    _transform你无法确定是否会有更多数据。

    根据您的用例,您可以收听end 事件,也可以使用_flush

    Stream: transform._flush(callback):

    自定义转换实现可以实现transform._flush() 方法。这将在没有更多写入数据被使用时调用,但在发出 'end' 事件之前,表示可读流结束。

    transform._flush() 实现中,readable.push() 方法可能会被调用零次或多次,视情况而定。刷新操作完成后必须调用回调函数。

    【讨论】:

    • 好的,但是如果我在_flush 中进行后期处理,则流永远不会发出end 事件。正常吗?那我需要手动发出end 事件吗?例如,如果我正在进行后期处理,然后将流的结果通过管道传输到http.ServerResponse,则加载永远不会结束,但如果我手动发出end 事件,一切正常。它应该这样工作吗,或者我可能有另一个问题?
    猜你喜欢
    • 2012-05-28
    • 2019-05-07
    • 1970-01-01
    • 2021-09-13
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多