← Back to Node.js, page 6

nodejs-0109 · Hard senior

How do you process a very large file efficiently: line counting, parallel byte ranges, and resuming after a crash?

Never read the file into memory. Stream it and keep only counters or small aggregates. For more speed, split the file into byte ranges that start and end on newline boundaries, and process the ranges with createReadStream({ start, end }) in parallel (in workers for CPU work). To resume after a crash, store the byte offset of the last fully processed line and restart from it.

Full answer

Memory is the first limit. readFile on a 5 GB file fails. Streams keep memory flat, but speed and recovery need more design.

Speed

  • Do the least work per byte. Scanning for newline bytes in raw Buffers is much faster than creating a string per line with readline. Use readline when you need the line text and the file is moderate.
  • Increase highWaterMark (for example 1 MB) for fewer reads on fast disks.
  • Parallelism: disks and CPUs allow it. Split the file into N ranges by size. A range boundary can fall inside a line, so move each boundary forward to the next newline. Each range then starts at a line start and ends at a line end. Process ranges in parallel with createReadStream({ start, end }), where end is inclusive.
  • For CPU heavy parsing use worker_threads, one range per worker. For simple counting, one thread is often limited by the disk.
  • Combine results from ranges (sums, maps), which should be associative.

Recovery

  • Track the byte offset after each batch of lines. Write it to a checkpoint file atomically (write a temp file, then rename).
  • On restart read the offset and open the stream with { start: offset }. Make the processing idempotent, because the last batch may run twice.

Other points: handle the last line without a newline, handle \r\n, do not trust file size to be stable for a growing log, and prefer a database bulk loader (COPY) when the goal is to load data.

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

// Build a deterministic 200,000-line "access log": status,bytes
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bigfile-'));
const file = path.join(dir, 'access.log');
const statuses = [200, 200, 200, 404, 500];
const lines = [];
for (let i = 0; i < 200000; i++) lines.push(`${statuses[i % 5]},${(i * 37) % 1000}`);
fs.writeFileSync(file, lines.join('\n')); // no newline at the end on purpose

// Process one byte range: count lines and sum bytes (field 2).
async function processRange(start, end, from = 0) {
  let count = 0, total = 0;
  const rl = readline.createInterface({ input: fs.createReadStream(file, { start: start + from, end, highWaterMark: 1 << 20 }), crlfDelay: Infinity });
  for await (const line of rl) { count++; total += Number(line.split(',')[1]); }
  return { count, total };
}

// Move a boundary forward to just after the next newline.
async function nextLineStart(handle, pos, size) {
  const buf = Buffer.alloc(4096);
  while (pos < size) {
    const { bytesRead } = await handle.read(buf, 0, buf.length, pos);
    if (bytesRead === 0) break;
    const i = buf.subarray(0, bytesRead).indexOf(10);
    if (i !== -1) return pos + i + 1;
    pos += bytesRead;
  }
  return size;
}

async function main() {
  const size = fs.statSync(file).size;
  const handle = await fs.promises.open(file, 'r');

  // Single pass for the expected answer.
  const whole = await processRange(0, size - 1);
  console.log('single pass :', whole);

  // Four aligned ranges, processed in parallel.
  const parts = 4;
  const starts = [0];
  for (let p = 1; p < parts; p++) starts.push(await nextLineStart(handle, Math.floor((size * p) / parts), size));
  await handle.close();
  const ranges = starts.map((s, i) => [s, (starts[i + 1] ?? size) - 1]);
  const results = await Promise.all(ranges.map(([s, e]) => processRange(s, e)));
  const sum = results.reduce((a, r) => ({ count: a.count + r.count, total: a.total + r.total }), { count: 0, total: 0 });
  console.log('parallel sum:', sum, '| same as single pass:', sum.count === whole.count && sum.total === whole.total);

  // Resume: pretend we crashed after the first range, with its offset saved.
  const checkpoint = ranges[0][1] + 1;
  const first = await processRange(0, checkpoint - 1);
  const rest = await processRange(checkpoint, size - 1);
  console.log('resume from byte', checkpoint, '-> total matches:', first.count + rest.count === whole.count && first.total + rest.total === whole.total);

  fs.rmSync(dir, { recursive: true });
}
main();

A 200,000 line file is created, then counted once, in four aligned parallel ranges, and in two parts split at a checkpoint. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): single pass : { count: 200000, total: 99900000 } parallel sum: { count: 200000, total: 99900000 } | same as single pass: true resume from byte 394500 -> total matches: true

Key points

  • Stream and keep aggregates only.
  • Raw byte scanning beats creating a string per line.
  • Align range boundaries to newlines and use inclusive end.
  • Combine per-range results with associative operations.
  • Checkpoint byte offsets for resume, and make work idempotent.

Common mistakes

  • Using readFile or readFileSync for large input.
  • Splitting ranges at fixed byte offsets and cutting lines in two.
  • Forgetting that the end option of createReadStream is inclusive.
  • Parallelising a disk-bound job and getting no speedup.
  • Writing the checkpoint non-atomically and reading a half-written file.

Follow-ups

  • How would you run each range in a worker thread?
  • How do you handle quoted CSV fields that contain newlines when you split by ranges?
  • How can you read the last 10 lines of a big log quickly?

Tips

  • Lead with 'never load the whole file'.
  • Explain the aligned boundary in one sentence.
  • Mention idempotent processing for resume.