node.js - 当数据实际准备好进行流式传输时,如何获得通知?
问题描述
我有两个流:
- 源流,它从 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);
推荐阅读
- magento2 - 在面板管理员中解锁编辑配置
- angularjs - 自定义多条形图?
- scala - 在 Apache Spark 中,如何将慢速 RDD/数据集转换为流?
- mysql - docker run 命令如何转换为 docker compose 文件?
- android - 如何重建 whats 应用程序主菜单(带有 fab 的 viewpager)
- python - 跨平台构建在 gitlab-ci
- javascript - 如何在 flex 容器中的每个项目上覆盖文本 + 图像?
- javascript - 在滚动上修复 div 和剪辑 div
- c# - 使用 C# 对象列表在 html 中创建表
- ruby - 用另一个哈希填充哈希值