Node.js中Readable Stream定时输出功能实现求助
解决Readable Stream定时输出问题
你的代码里,_read方法会一次性把1到10的所有数据push出去,所以data事件会一次性触发,自然达不到每秒输出一个的效果。要实现需求,得每次只push一个数据,然后延迟1秒再处理下一个,直到完成所有数字后结束流。
修改后的代码如下:
const { Readable } = require('stream'); class MyReadable extends Readable { constructor() { super(); this.currentNumber = 1; // 记录当前要输出的数字 this.isPushing = false; // 防止重复触发定时器 } _read() { // 如果正在推送数据,直接返回避免重复操作 if (this.isPushing) return; this.isPushing = true; const pushNext = () => { if (this.currentNumber > 10) { this.push(null); // 推送null结束流 this.isPushing = false; return; } this.push(this.currentNumber.toString()); this.currentNumber++; // 间隔1秒后执行下一次推送 setTimeout(pushNext, 1000); }; pushNext(); } } const instanceReadableStream = new MyReadable(); instanceReadableStream.on('data', (chunk) => { console.log(chunk.toString()); }); instanceReadableStream.on('end', () => console.log('Fin de la lecture des données'));
关键修改说明:
- 在类的构造函数里新增两个属性:
currentNumber用来追踪当前要输出的数字,isPushing用来标记是否正在推送数据,避免_read被多次调用时启动多个定时器 - 定义
pushNext函数处理单次推送逻辑:判断数字是否超出范围,超出则结束流;否则推送当前数字并自增,然后通过setTimeout延迟1秒再次调用自身,实现间隔输出 - 这样每次只会推送一个数据,并且严格保持1秒的间隔,直到所有数字输出完毕触发
end事件
内容的提问来源于stack exchange,提问作者Cassius
相关产品推荐
相关产品推荐

