Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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 Oleg

Large 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: 2

Common 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

Thanks for reading!

Donate to the site — we work hard for you.