How to read a file line by line in Node.js
Short answer
For small files, read the content and split it into lines:
import { readFile, writeFile } from 'node:fs/promises';
await writeFile('names.txt', 'Anna\nOleg\nMaria\n');
const lines = (await readFile('names.txt', 'utf8')).split(/\r?\n/).filter(Boolean);
console.log(lines.length, lines[1]);Output:
3 OlegLarge files
A large file should not be loaded into memory all at once. readline reads it with a stream, one line at a time:
import { createReadStream } from 'node:fs';
import { writeFile } from 'node:fs/promises';
import { createInterface } from 'node:readline';
await writeFile('access.log', 'GET /\nPOST /login\nGET /about\n');
const lines = createInterface({ input: createReadStream('access.log'), crlfDelay: Infinity });
let count = 0;
for await (const line of lines) {
if (line.startsWith('GET')) count++;
}
console.log('GET requests:', count);Output:
GET requests: 2Common mistake
Without crlfDelay: Infinity, a Windows line ending \r\n may be split into two line breaks. And forEach() is not available on the stream: use for await.
// count-lines.js
const lines = createInterface({ input: createReadStream('access.log'), crlfDelay: Infinity });
for await (const line of lines) {
console.log(line);
}Functions used in this recipe
- for await...of — Loops over asynchronous data sources, waiting for each item.
- String.prototype.split — Splits a string into an array by a separator.