我尝试用“延迟”来传输流。
问题是,一旦输入流接收到数据并完成管道传输,数据就会丢失,输出流上什么也没有收到。
const { PassThrough } = require("stream");
console.log("Started...");
const input = new PassThrough();
const output = new PassThrough();
output.on("data", (data) => {
console.log("Chunk on output input", data);
});
input.on("readable", () => {
console.log("input is readable, pipe to output");
// this does not work
//setTimeout(() => {
// input.pipe(output);
//}, 1000);
// this dosnt work either
// input.pipe(output);
});
// wait some time to simluate user input
setTimeout(() => {
console.log("Write to input");
input.write(`Hello World ${Date.now()}`);
}, 1000);
如何在不丢失数据的情况下延迟传输流?
我认为输入流是“缓冲”的,直到它从
.read
、管道或通过“数据”事件切换到流模式时被耗尽。
欢迎任何提示。
编辑:
似乎“可读”的事件监听器搞砸了。 以下示例有效,但不确定为什么它在可读事件中不起作用。如果事件被触发,文档中没有写明您必须使用任何数据。
const { PassThrough } = require("stream");
console.log("Started...");
const input = new PassThrough();
const output = new PassThrough();
output.on("data", (data) => {
console.log("Chunk on output input:", data);
});
// wait some time before pipe
setTimeout(() => {
console.log("Pipe input to output")
input.pipe(output);
}, 2000);
// wait some time to simluate user input
setTimeout(() => {
console.log("Write to input");
input.write(`Hello World ${Date.now()}`);
}, 1000);
我打开这个问题。
也许有人可以解释为什么第一个示例不适用于可读事件。