考慮下面的代碼...我想讀第5行後暫停流:暫停的readline
var fs = require('fs');
var readline = require('readline');
var stream = require('stream');
var numlines = 0;
var instream = fs.createReadStream("myfile.json");
var outstream = new stream;
var readStream = readline.createInterface(instream, outstream);
readStream.on('line', function(line){
numlines++;
console.log("Read " + numlines + " lines");
if (numlines >= 5) {
console.log("Pausing stream");
readStream.pause();
}
});
輸出(下一個複製)表明,它使閱讀後線暫停。也許readline已經在緩衝區中排隊了幾行,並將它們反饋給我......如果它繼續在後臺異步讀取,這將是有意義的,但基於文檔,我不知道適當的行爲應該是。有關如何達到預期效果的任何建議?
Read 1 lines
Read 2 lines
Read 3 lines
Read 4 lines
Read 5 lines
Pausing stream
Read 6 lines
Pausing stream
Read 7 lines
感謝您的回答。出於興趣,這種要求有多普遍?我正在解析需要流式傳輸到服務器的80GB CSV。還有什麼其他用例? –
@ZachSmith我發現在回調不能或不應該同步完成時(比如說,將行插入到數據庫中),可以暫停和恢復。如果您正在讀取的行比處理它們的速度快,則可能會排隊過多請求並耗盡內存。 –