Skip to the page

Events, buffers, streams and files · mid

Streams and pipeline

Streams process data piece by piece instead of loading it all into memory; Node has Readable, Writable, Duplex and Transform streams, and you connect them with stream.pipeline, which also handles errors and cleanup.

The notes

What you must know

  • Four types: Readable (fs.createReadStream, the HTTP request on a server, process.stdin), Writable (fs.createWriteStream, the HTTP response, process.stdout), Duplex (a TCP socket), Transform (zlib.createGzip, crypto ciphers).
  • Why: you can serve a 2 GB file while holding only about 64 KiB at a time, and the first bytes reach the user sooner.
  • Consume a Readable with for await...of (simplest), with pipeline, or with 'data'/'end' events. Pick one style per stream; the docs warn that mixing them gives surprising results.
  • pipeline(source, ...transforms, destination) from node:stream/promises connects streams, respects backpressure, destroys every stream if one fails, and gives one promise to await. Old .pipe() does not forward errors or clean up.
  • Readable.from(iterable) turns an array or async generator into a stream; an async generator function can be a transform step inside pipeline.
  • objectMode streams carry JS objects instead of bytes (e.g. rows from a database cursor).
  • Default highWaterMark: 64 KiB for byte streams (raised from 16 KiB in Node 22), 16 objects in objectMode.
  • Web Streams (ReadableStream) exist in Node too (fetch bodies use them); Readable.fromWeb and Readable.toWeb convert between the two.

The red pen

Common traps: mistake → fix

  • Mistake: readFile is fine for any file

    Fix: it loads the whole file into memory; stream big or unknown-size files.

  • Mistake: a.pipe(b) handles errors

    Fix: errors are not forwarded and streams can leak; use pipeline.

  • Mistake: Streams are only for files

    Fix: HTTP requests and responses, sockets, compression and DB cursors are all streams.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are streams and why use them?
  2. Name the four stream types with an example of each.
  3. How would you serve a 2 GB CSV export without running out of memory?
  4. pipe vs pipeline: what is the difference?
  5. How would you process a huge file line by line?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview