Example: Read file stream line-by-Line示例:逐行读取文件流#

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.ReadStreamAPI和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);
}
})();