[英]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.