← Back to Node.js, page 1

nodejs-0010 · Easy fresher

How do you read a large file line by line in Node.js without loading it all into memory?

Create a read stream with fs.createReadStream and pass it to readline.createInterface. The interface emits one line at a time and supports for await...of, so memory use stays small whatever the file size.

Full answer

fs.readFile loads the entire file into one Buffer. For a 5 GB log this fails or slows the whole process. Reading in chunks with a stream avoids it, but chunks do not end on line breaks, so a line can be cut between two chunks.

The readline module solves that. It reads from any readable stream, keeps the partial line until the rest arrives, and gives you complete lines. The interface is async iterable, so the code is a normal loop with backpressure handled for you.

Details worth knowing:

  • Set crlfDelay: Infinity so that "\r\n" is treated as a single line break.
  • Lines do not include the line break.
  • Pass an encoding to createReadStream only if you need something other than UTF-8 handling by readline.
  • If you also need to stop early (find the first match), call rl.close() or break out of the loop, then destroy the stream.

For CSV with quoted fields that contain line breaks, a plain line split is not enough. Use a CSV parser stage in a pipeline.

javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const readline = require('node:readline');

async function main() {
  // Create a small sample file with Windows line endings.
  const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'marks-')), 'marks.txt');
  fs.writeFileSync(file, 'asha,78\r\nravi,91\r\nmeera,85\r\n');

  const rl = readline.createInterface({
    input: fs.createReadStream(file),
    crlfDelay: Infinity,
  });

  let total = 0;
  let count = 0;
  for await (const line of rl) {
    const [name, marks] = line.split(',');
    console.log('line', ++count + ':', name, marks);
    total += Number(marks);
  }
  console.log('average marks:', (total / count).toFixed(2));
}

main();

The sample file is created in a temporary folder, so the snippet runs anywhere. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): line 1: asha 78 line 2: ravi 91 line 3: meera 85 average marks: 84.67

Key points

  • Use readline with fs.createReadStream.
  • for await (const line of rl) gives complete lines and applies backpressure.
  • Set crlfDelay: Infinity for Windows line endings.
  • A plain split on newline breaks CSV fields that contain newlines.

Common mistakes

  • Using readFileSync(...).split('\n') on a huge file.
  • Not setting crlfDelay and getting empty lines on Windows files.
  • Forgetting that the loop variable is a string, so numbers need Number().
  • Reading a file with readline and then also reading the same stream elsewhere.

Follow-ups

  • How would you count lines in a 10 GB file quickly?
  • How do you read only the last 10 lines of a big file?
  • What changes if the file is gzip compressed?

Tips

  • Say that readline takes care of lines split across chunks.
  • Mention for await (modern) before the old 'line' event.
  • Point out the CSV exception to show you know the limits.