【发布时间】:2020-03-12 19:24:26
【问题描述】:
我正在一个大文件上创建一个文件读取流并将其传递给readline.createInterface。目标是在此之后使用for await ... of 从文件中获取行而不将其全部读入内存。
但是,即使我什么都没读,整个流似乎都被处理了。我知道发生这种情况是因为我尝试监听事件(并且它们已被发出),而且如果我使用非常大的文件,我的脚本需要一段时间才能完成。
有没有办法避免这种行为?我希望按需使用流。
如果我不使用readline,而是从流中读取块并自己搜索行,我可以成功实现此行为,但如果可能的话,我想避免这种情况。
MWE:
var readline = require('readline');
var fs = require('fs');
var file = 'really_big_file.txt'; // 2GB is what I used
readline.createInterface({input: fs.createReadStream(file)});
// this takes a while to finish because the file is being read,
// even if I'm not doing anything with the stream
【问题讨论】:
标签: node.js fs readline node-streams