readline Streams A File Line By Line
Iterate a file with readline.createInterface over a read stream, counting lines incrementally instead of loading the whole file into memory.
Code
import { createReadStream, writeFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
// seed a small log file for the demo
writeFileSync('events.log', ['boot ok', 'cache cold', 'boot ok'].join('\n'), 'utf8');
// readline over a read stream hands out one line per iteration,
// so the file never has to fit in memory at once
const rl = createInterface({ input: createReadStream('events.log') });
const counts = new Map();
for await (const line of rl) {
counts.set(line, (counts.get(line) ?? 0) + 1);
}
console.log('lines counted:', [...counts.values()].reduce((a, b) => a + b, 0));
for (const [line, count] of counts) {
console.log(`${count}x ${line}`);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
lines counted: 1
1x boot okcache coldboot okHow it works
The nesting pairs for await (const line of rl) with for (const [line, count] of counts) — the inner runs once per outer step. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The import names the platform contact area: createReadStream, writeFileSync, createInterface, all from node:fs, node:readline.
All the work happens on the top-level bindings: rl, counts.
What to watch for
- The dependency surface is just
node:fs, and that one is built into Node.js.
Putting it to use
The demo output is labeled (lines counted:), so the output doubles as a step-by-step trace of what the file did.
Core lines
counts.set(line, (counts.get(line) ?? 0) + 1);
const counts = new Map();
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No — `node:fs` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.