如何在数据实际准备好流式传输时获得通知?

问题描述

我有两个流:

  • 从 Internet 下载音频文件的源流
  • 消费者流,将文件流式传输到流媒体服务器

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

这意味着,我应该

  • 首先等待源数据准备好流式传输
  • 然后才开始流式传输。

问题在于,当源流中的数据准备就绪时,似乎没有办法获得通知

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

那么如何做这样的事情:

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

提前致谢。

解决方法

回答我自己。

这是一个对我有用的解决方案。

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

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);