Full answer
The goal is that memory depends on the number of stages and their buffers, never on the file size. A good design has four parts.
- A byte source such as fs.createReadStream. Chunks are 64 KB by default (16 KB before Node 22) and cut the file at random points, even in the middle of a line or a multi-byte character.
- A line splitter. It joins the leftover text of the previous chunk with the new chunk, splits on newlines, yields all complete lines, and keeps the last piece for the next round. When using strings, decode with the stream's encoding or a StringDecoder so a character is not cut in half.
- A parser that turns a line into an object. This stage can run in object mode, where highWaterMark counts objects (16 by default) instead of bytes.
- A sink that does the real work, such as batching 1,000 rows per database insert. If the sink is slow, backpressure travels back through the stages up to the file read.
Async generator functions make this short, because pipeline accepts them as stages and handles backpressure between them. Tune highWaterMark only after measuring. A larger value means fewer wake-ups but more memory per stage. Also batch rows before slow I/O, because one insert per row is usually the real bottleneck.
Error handling matters at this size. Use pipeline so a failing stage destroys the file handle, and decide what to do with a bad row (skip and count, or fail fast).
const { pipeline } = require('node:stream/promises');
const { Readable } = require('node:stream');
// Source: a generator that makes 200,000 rows lazily, like reading a big file.
function* rows(n) {
for (let i = 1; i <= n; i++) yield `${i},${i % 100}\n`;
}
// Stage 1: cut the text into 1000-character chunks (lines get split on purpose).
async function* chunks(source) {
let buffer = '';
for await (const part of source) {
buffer += part;
while (buffer.length >= 1000) {
yield buffer.slice(0, 1000);
buffer = buffer.slice(1000);
}
}
if (buffer) yield buffer;
}
// Stage 2: rebuild whole lines and yield one parsed marks value per row.
async function* parse(source) {
let tail = '';
for await (const chunk of source) {
const lines = (tail + chunk).split('\n');
tail = lines.pop(); // the last piece may be an unfinished line
for (const line of lines) yield Number(line.split(',')[1]);
}
if (tail) yield Number(tail.split(',')[1]);
}
async function main() {
let count = 0;
let sum = 0;
// Stage 3: the sink consumes the values one by one.
await pipeline(Readable.from(rows(200000)), chunks, parse, async function (source) {
for await (const marks of source) {
count++;
sum += marks;
}
});
console.log('rows:', count, '| sum of marks:', sum);
}
main();The expected sum is 2,000 full cycles of 0 to 99, which is 9,900,000, so a lost partial line would show up as a wrong number. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): rows: 200000 | sum of marks: 9900000
Key points
- Memory is the sum of stage buffers, not the file size.
- A line splitter must keep the partial last line between chunks.
- Object mode counts highWaterMark in objects, not bytes.
- Backpressure from a slow sink slows the file read.
- Batch writes to the database, and use pipeline for cleanup.
Common mistakes
- Splitting each chunk on newline without keeping the partial last line.
- Collecting all rows in an array before processing.
- Inserting one database row per await instead of batching.
- Decoding bytes to strings chunk by chunk and breaking multi-byte characters.
Follow-ups
- How would you add retry and a dead-letter file for bad rows?
- How can you process the file in parallel on several CPU cores?
- What would you change to resume after a crash at row 50 million?
Tips
- Draw the stages and say where each buffer lives.
- Mention the multi-byte character trap.
- Add batching and checkpointing to show production experience in general terms.