IntermediateLesson 6 of 125 min read

Streams: Processing Big Files Without Loading Them

Process a 200,000-line file piece by piece with Node streams: write it respecting backpressure, read it in chunks, transform it line by line, hash it while streaming, and verify the chunk count, the totals and the hash with Python.

In this lesson you will

  • Explain why streams exist
  • Read and write files as streams
  • Use pipeline and transform streams
  • Verify results independently

About 28 minutes

The orders file that grew

A year of Mara’s orders is a file of 200,000 lines. Reading it with readFile works, until the file becomes a gigabyte, when it fills the memory and the program dies. A stream treats data as a flow of chunks. A readable stream produces chunks, 64 kilobytes at a time for files by default, a writable stream consumes them, and a transform stream sits in the middle and changes them. Only a few chunks are in memory at a time, so a program can process a file much larger than its memory, and it can start working on the first chunk before the last one has been read. The same idea covers network connections, compression and the standard input and output of programs.

Two mechanisms make the flow safe. Backpressure: if a writable stream cannot keep up, write returns false, and the producer must pause until the stream emits drain, so a fast reader cannot flood a slow writer. The pipeline function from the stream module connects streams, forwards errors, and cleans up all of them if one fails, which is why it should be preferred to calling pipe by hand. A transform stream receives chunks that may split a line in two, so line-oriented code must keep the unfinished part of a line until the next chunk arrives. The readline module does this for you.

Type Role Example
Readable Produces chunks fs.createReadStream
Writable Consumes chunks fs.createWriteStream
Transform Changes chunks zlib.createGzip, hashes
pipeline Connects and cleans up stream.pipeline(a, b, c)
const fs = require('fs'), path = require('path'), crypto = require('crypto'), readline = require('readline');
const { once } = require('events'), { pipeline } = require('stream/promises');
(async () => {
  const file = path.join(process.argv[2], 'big.csv');
  const out = fs.createWriteStream(file);
  let s = 777, drains = 0;
  const rnd = n => { s = (s * 16807) % 2147483647; return s % n; };
  const items = [['poster', 1200], ['flyer', 35], ['card', 18], ['banner', 4500]];
  for (let id = 1; id <= 200000; id++) {
    const it = items[rnd(4)];
    if (!out.write(id + ',' + it[0] + ',' + (1 + rnd(20)) + ',' + it[1] + '\n')) { drains++; await once(out, 'drain'); }
  }
  out.end(); await once(out, 'finish');
  const size = fs.statSync(file).size;
  const rs = fs.createReadStream(file);
  let chunks = 0, bytes = 0;
  const hash = crypto.createHash('sha256');
  rs.on('data', c => { chunks++; bytes += c.length; hash.update(c); });
  await once(rs, 'close');
  let lines = 0, total = 0, perItem = {};
  const rl = readline.createInterface({ input: fs.createReadStream(file), crlfDelay: Infinity });
  for await (const line of rl) { const [id, item, qty, cents] = line.split(','); lines++; const v = qty * cents; total += v; perItem[item] = (perItem[item] || 0) + v; }
  console.log('file size:', size, 'bytes | read as', chunks, 'chunks of up to 65536 bytes | bytes seen:', bytes);
  console.log('writer paused for backpressure at least once:', drains > 0);
  console.log('lines:', lines, '| revenue:', (total / 100).toFixed(2));
  console.log('sha256:', hash.digest('hex'));
  console.log('DATA ' + JSON.stringify({ size, chunks, bytes, lines, total, perItem, drains }));
})();
file size: 3850747 bytes | read as 59 chunks of up to 65536 bytes | bytes seen: 3850747
writer paused for backpressure at least once: true
lines: 200000 | revenue: 30243171.71
sha256: 5ce8888614ab3fe8e0686668464a9b1527dad02d1b2d78587fd1c5b6ad9eacfc

The script wrote 200,000 lines, 3,850,747 bytes, with a writable stream. Whenever write returned false, the loop waited for the drain event: that happened 58 times, which is backpressure at work, and the program never held more than a small buffer of the file in memory. It then read the file as a stream of 59 chunks, at most 65,536 bytes each, and the bytes seen add up to exactly the size of the file. While the chunks flowed past, they were also fed into a SHA-256 hash, so the program computed a fingerprint of the whole file without ever holding it.

A second pass used readline on a new read stream to process the file line by line, which handles lines that were split across chunk boundaries. It counted 200,000 lines and a revenue of 30,243,171.71, with the totals per item: banner 23,597,280.00, card 94,003.56, flyer 183,284.15, poster 6,368,604.00. The same approach works if the file has 200 million lines: the memory used stays about the same, and only the time grows.

Independent check: Python read the finished file with a different method, as one block of bytes, and computed the SHA-256 hash, 5ce8888614ab3fe8…, the number of lines, the revenue and the revenue per item, using its own code. All of them agree with the stream results. The chunk count agrees with ceil(3,850,747 / 65,536) = 59, a prediction made from the size of the file and the default buffer. A matching hash is strong evidence that the stream delivered every byte exactly once and in order.

Check by hand: the number of chunks is the file size divided by 65,536, rounded up, because the last chunk is smaller. A hash is a fingerprint: changing one byte of the file would change it completely, so equal hashes from two independent programs mean equal content.

Do not ignore backpressure

If you write in a loop without checking the return value of write, memory fills with unwritten data, which is how a streaming program becomes a memory hog. Use pipeline or await drain.

Prefer pipeline

stream.pipeline connects streams and destroys all of them on an error. Chaining pipe calls by hand leaks resources when something fails.

About this course

Every program in this lesson was run while the course was written, with Node.js 22 and only its built-in modules (plus the packages named in the lesson), and cross-checked with the shell, curl, Python or the specification. Node.js releases change, so check nodejs.org for the current long-term support version and its documentation. Default buffer sizes can differ by stream type and version. The 64 kilobyte figure is for file read streams in current Node.js versions.

Practice

Add a gzip transform with zlib.createGzip between reading and writing, and compare the file sizes. Write a transform stream that upper-cases the item name. Use pipeline to copy the file and compare the hash of the copy.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Why use streams for big files?

  1. They are always faster
  2. They compress
  3. Only a few chunks are in memory at a time
  4. They avoid errors

Memory stays small.

What is backpressure?

  1. A network error
  2. A slow consumer making the producer wait
  3. A hash
  4. A compression level

write returns false, then drain.

Why use pipeline instead of pipe?

  1. It is shorter only
  2. It forwards errors and cleans up
  3. It is needed for HTTP
  4. It is older

No leaked streams.

Why does readline help with lines?

  1. It handles lines split across chunks
  2. It sorts lines
  3. It compresses lines
  4. It hashes lines

Chunks do not align with lines.

What does a matching SHA-256 hash show?

  1. The content is identical
  2. The file is small
  3. The file is sorted
  4. Nothing

It is a strong fingerprint.

Summary

  • Streams process data in chunks, so memory stays small.
  • Backpressure prevents a fast producer from flooding a slow consumer.
  • Use pipeline and readline.
  • Verify with hashes and counts from an independent program.

Next lesson

Lesson 7 covers building an HTTP server.

Questions

Are streams faster than readFile?

For small files readFile is simpler and just as fast. Streams win on memory for big files, and on latency, since processing starts before the whole file is read.

What chunk size should I use?

The default is usually fine. You can change it with highWaterMark if measurements show a benefit.

Can I use async iteration on streams?

Yes: for await (const chunk of stream) reads a stream chunk by chunk, and readline supports it for lines.

Progress is saved in this browser.