A common use case for readline
is to consume an input file one line at a time. readline
的一个常见用例是一次使用一行输入文件。The easiest way to do so is leveraging the 最简单的方法是利用fs.ReadStream
API as well as a for await...of
loop:fs.ReadStream
API和for await...of
循环:
const fs = require('node:fs');
const readline = require('node:readline');
async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');
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}`);
}
}
processLineByLine();
Alternatively, one could use the 或者,可以使用'line'
event:'line'
事件:
const fs = require('node:fs');
const readline = require('node:readline');
const rl = readline.createInterface({
input: fs.createReadStream('sample.txt'),
crlfDelay: Infinity
});
rl.on('line', (line) => {
console.log(`Line from file: ${line}`);
});
Currently, 目前,for await...of
loop can be a bit slower. for await...of
循环的速度可能会慢一点。If 如果async
/ await
flow and speed are both essential, a mixed approach can be applied:async
/await
流和速度都很重要,那么可以应用混合方法:
const { once } = require('node:events');
const { createReadStream } = require('node:fs');
const { createInterface } = require('node:readline');
(async function processLineByLine() {
try {
const rl = createInterface({
input: createReadStream('big-file.txt'),
crlfDelay: Infinity
});
rl.on('line', (line) => {
// Process the line.
});
await once(rl, 'close');
console.log('File processed.');
} catch (err) {
console.error(err);
}
})();