首页 > 解决方案 > 当数据实际准备好进行流式传输时,如何获得通知?

问题描述

我有两个流:

在流式传输到服务器之前,应该有一个返回句柄的握手。然后我有几秒钟的时间来真正开始流式传输或服务器关闭连接。

这意味着,我应该

问题是当源流中的数据准备好时,似乎没有办法得到通知。

想到的第一个事件是“数据”事件。但它也会消耗不可接受的数据,并且根本不允许使用管道。

那么如何做这样的事情:

  await pEvent(sourceStream, 'dataIsReady');
  // Negotiate with the server about the transmission
  sourceStream.pipe(consumerStream);

提前致谢。

标签: node.jsstreamnode-streams

解决方案


回答我自己。

这是一个适合我的解决方案。

它需要一个带有自定义事件的辅助直通流:

class DataWaitPassThroughStream extends Transform {
  dataIsReady: boolean = false;

  constructor(opts: TransformOptions) {
    super(opts);
  }

  _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback) {
    if (!this.dataIsReady) {
      this.dataIsReady = true;
      this.emit('dataIsReady');
    }
    callback(null, chunk);
  }
}

用法

import pEvent from 'p-event';

const dataReadyStream = sourceStream.pipe(new DataWaitPassThroughStream());
await pEvent(dataReadyStream, 'dataIsReady');

// Negotiate with the server about the transmission...

dataReadyStream.pipe(consumerStream);

推荐阅读