将文件读取流传递到Node.js中的readline.createInterface时读取整个文件
我正在一个大文件上创建一个文件读取流,并将其传递给将文件读取流传递到Node.js中的readline.createInterface时读取整个文件,node.js,fs,readline,node-streams,Node.js,Fs,Readline,Node Streams,我正在一个大文件上创建一个文件读取流,并将其传递给readline.createInterface。目标是,在此之后,使用等待。。。从文件中获取行而不将其全部读取到内存 然而,即使我没有读任何东西,整个流似乎都在被处理。我知道发生这种情况是因为我试图监听事件(它们被发出),而且如果我使用一个非常大的文件,我的脚本需要一段时间才能完成 有没有办法避免这种行为?我希望该流能够按需使用 如果我不使用readline,而是从流中读取块并自己搜索行,我可以成功地实现此行为,但如果可能,我希望避免这种情况
readline.createInterface
。目标是,在此之后,使用等待。。。从文件中获取行而不将其全部读取到内存
然而,即使我没有读任何东西,整个流似乎都在被处理。我知道发生这种情况是因为我试图监听事件(它们被发出),而且如果我使用一个非常大的文件,我的脚本需要一段时间才能完成
有没有办法避免这种行为?我希望该流能够按需使用
如果我不使用readline
,而是从流中读取块并自己搜索行,我可以成功地实现此行为,但如果可能,我希望避免这种情况
MWE:
从readline
package的官方文件:
const fs = require('fs');
const readline = require('readline');
async function processLineByLine() {
const fileStream = fs.createReadStream('/tmp/input.txt');
// If you want to start consuming the stream after some point
// in time then try adding the open even to the readstream
// and explictly pause it
fileStream.on('open', () => {
fileStream.pause();
// Then resume the stream when you want to start the data flow
setInterval(() => {
fileStream.resume();
}, 1000)
});
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
console.log("reading finished");
}
processLineByLine();
尝试将接口存储在变量中,并在迭代中进一步使用它。这里发生的事情是readline开始并继续,直到没有任何东西要求它等待
进一步阅读:
const fs = require('fs');
const readline = require('readline');
async function processLineByLine() {
const fileStream = fs.createReadStream('/tmp/input.txt');
// If you want to start consuming the stream after some point
// in time then try adding the open even to the readstream
// and explictly pause it
fileStream.on('open', () => {
fileStream.pause();
// Then resume the stream when you want to start the data flow
setInterval(() => {
fileStream.resume();
}, 1000)
});
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
console.log("reading finished");
}
processLineByLine();