[英]NodeJS: Detect last new line byte from Readable Stream when reading by Range to parse large CSV file
[英]NodeJs Readable Error When Reading From Stream
我想每1秒打印一次输出,但是出现以下错误。 我以为read方法被同步调用,但事实并非如此。 有人可以解释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);
我得到这个错误:
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)
当您按下null
您正在关闭流,但是没有清除超时,因此您尝试在关闭的流上进行写操作。 像这样尝试:
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);
有关流的更多信息: https : //nodejs.org/api/stream.html#stream_visible_streams
对于以后来阅读此书的任何人:
如果您使用节点的更新的版本,则不会重现此行为。 对此的详细讨论可以在这里找到:
github.com/nodejs/node/issues/3203#issuecomment-355137794
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.