【发布时间】:2021-03-12 04:17:40
【问题描述】:
我正在尝试实现具有缓冲功能的双工流。
它应该积累大量数据,直到它们足够多,然后才将它们进一步发送。
例如,在播放流式音频/视频数据时可以使用它:不能简单地及时获取帧,对吧?
下面是我创建这种缓冲双工流的愚蠢尝试。有一个源流,它将x\n 字符发送到缓冲流,而缓冲流又应该将数据进一步发送到process.stdout。
唉,这行不通。具体来说,read() 函数似乎没有任何方法可以暂停或停止,例如:
“嘿,我现在没有任何数据给你,稍后再回来”。
不,一旦我返回 undefined 或 null,故事就结束了,标准输出中什么也没有出现。
var {Readable, Duplex} = require('stream');
// Source stream, seeds: x\n, x\n, x\n, ...
let c = 10;
var rs = new Readable({
read () {
if (c > 0) {
c--;
console.log('rs reading:', 'x');
this.push('x\n');
}
else {
this.push(null)
}
},
});
// Buffering duplex stream
// I want it to cache 3 items and only then to proceed
const queue = [];
const limit = 3;
var ds = new Duplex({
writableHighWaterMark: 0,
write (chunk, encoding, callback) {
console.log('ds writing:', chunk, 'paused: ', ds.isPaused());
queue.push(chunk);
callback();
},
readableHighWaterMark: 0,
read () {
// We don't want to output anything
// until there's enough elements in the `queue`.
if (queue.length >= limit) {
const chunk = queue.shift();
console.log('ds reading:', chunk);
this.push(chunk);
}
else {
// So how to wait here?
this.push(undefined)
}
},
});
// PROBLEM: nothing is coming out of the "ds" and printed on the stdout
rs.pipe(ds).pipe(process.stdout);
这是我的回复:https://repl.it/@OnkelTem/BufferingStream1-1#index.js
我检查了双工的状态,它甚至没有处于暂停状态。所以它没有暂停,它在流动,然而——什么也不返回。
我还花了几个小时重新阅读有关 Node 流的文档,但实际上并不觉得它是为了理解而创建的。
【问题讨论】:
标签: node.js audio-streaming node-streams