[英]NodeJs Readable Error When Reading From Stream
I want to print the output every 1 second but i get the below error. 我想每1秒打印一次输出,但是出现以下错误。 I thought that read method is called synchronously but it seems that is not the case.
我以为read方法被同步调用,但事实并非如此。 Can someone explain how the read method executes and why i get this error?
有人可以解释read方法的执行方式以及为什么会出现此错误吗?
const {Readable} = require('stream');
var out = new Readable({
read(size){
console.log('read');
setTimeout(()=>{
console.log(this.k);
console.log('before push');
this.push(String.fromCharCode(this.k++)+'\n');
console.log('after push\n');
if(this.k>65){
this.push(null);
console.log('null\n');
}
},1000);
}
});
out.k = 65;
out.pipe(process.stdout);
And i get this error: 我得到这个错误:
events.js:183
throw er; // Unhandled 'error' event
^
Error: stream.push() after EOF
at readableAddChunk (_stream_readable.js:240:30)
at Readable.push (_stream_readable.js:208:10)
at Timeout.setTimeout [as _onTimeout] (C:\Users\x90540\Node\index.js:106:14)
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
at Timer.listOnTimeout (timers.js:270:5)
When you are pushing null
you are closing the stream, but you are not clearing the timeout, so then you are trying to write on a closed stream. 当您按下
null
您正在关闭流,但是没有清除超时,因此您尝试在关闭的流上进行写操作。 Try it like this: 像这样尝试:
const { Readable } = require('stream');
var prevTimeout;
var out = new Readable({
read(size) {
prevTimeout = setTimeout(()=> {
console.log(this.k);
this.push(String.fromCharCode(this.k++)+'\n');
if (this.k > 67) {
this.push(null);
clearTimeout(prevTimeout);
}
},
500);
}
});
out.k = 65;
out.pipe(process.stdout);
More info about streams: https://nodejs.org/api/stream.html#stream_readable_streams 有关流的更多信息: https : //nodejs.org/api/stream.html#stream_visible_streams
For anyone who comes to read this later on: 对于以后来阅读此书的任何人:
This behavior would not reproduce if you use the updated version of Node. 如果您使用节点的更新的版本,则不会重现此行为。 A detailed discussion of this can be found here:
对此的详细讨论可以在这里找到:
github.com/nodejs/node/issues/3203#issuecomment-355137794 github.com/nodejs/node/issues/3203#issuecomment-355137794
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.