Streams and Buffers
Streams let Node.js process data piece by piece instead of loading it all into memory. Buffers hold raw binary data. Interviewers ask about them to see if you can handle large files, uploads and responses without running out of memory.
What you will learn
- Name the four stream types
- Explain backpressure and how pipeline handles it
- Use streams for file downloads and CSV processing
- Know what a Buffer is and how encoding works
Key concepts
Readable, Writable, Duplex, Transform
Readable produces data (file read, HTTP request). Writable consumes it (file write, HTTP response). Duplex does both independently (TCP socket). Transform changes data as it passes (gzip, CSV parser).
Backpressure
When the writer is slower than the reader, write() returns false. A correct pipe pauses the reader until the writer emits drain, so memory stays flat.
pipeline()
stream.pipeline (or its promise version) connects streams, handles backpressure, and destroys every stream and reports the error if any of them fails. Prefer it over .pipe().
Buffer
A fixed-size chunk of raw bytes outside the V8 heap. Convert with buf.toString("utf8") and Buffer.from(str, "base64").
Step by step
Why not readFile?
Reading a 2 GB log with readFile needs 2 GB of RAM and blocks until done. A stream reads in 64 KB chunks, so memory stays around a few MB and the first bytes reach the client right away.
Examples
Stream a gzipped file to the client
import { createReadStream } from 'node:fs'
import { createGzip } from 'node:zlib'
import { pipeline } from 'node:stream/promises'
app.get('/export', async (req, res, next) => {
res.set({ 'Content-Type': 'text/csv', 'Content-Encoding': 'gzip' })
try {
await pipeline(createReadStream('./export.csv'), createGzip(), res)
} catch (err) {
next(err)
}
})Process a big file line by line
import { createReadStream } from 'node:fs'
import readline from 'node:readline'
const rl = readline.createInterface({ input: createReadStream('access.log') })
let errors = 0
for await (const line of rl) if (line.includes(' 500 ')) errors++
console.log({ errors })Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Write a Transform stream that upper-cases text.
- Stream a database cursor to a CSV download without loading all rows.
- Explain what happens to memory if you ignore the return value of write().
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
What is backpressure?
The mechanism that stops a fast producer from flooding a slow consumer. When the writable buffer passes its highWaterMark, write() returns false and the readable should pause until drain. pipeline() does this for you.
Why is pipeline better than pipe?
.pipe() does not forward errors or destroy the other streams, so a failed write can leave a file descriptor open and leak memory. pipeline() cleans up all streams and gives you one place to catch the error.
Summary
Streams move data in chunks with backpressure so memory stays flat; use pipeline to connect them safely. Buffers hold raw bytes and convert between encodings.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus