# Streams & Buffers

> What are streams and buffers in Node.js? Why are streams important for handling large files, and what is backpressure?

Canonical: https://www.internhack.in/learn/interview/nodejs-interview/node-streams-buffers
Last updated: 2026-11-28

Difficulty: Advanced

## Question

What are streams and buffers in Node.js? Why are streams important for handling large files, and what is backpressure?

## Answer

A stream is an object that delivers data in small chunks over time instead of all at once, and a Buffer is Node's fixed-size container for raw bytes (a subclass of `Uint8Array`). Streams let you process a 10 GB log file or a video upload with a small, constant amount of memory, because only a few chunks are in memory at any moment.

### The four stream types

| Type | What it does | Examples |
| --- | --- | --- |
| Readable | Produces data | `fs.createReadStream`, `http.IncomingMessage` (`req`) |
| Writable | Consumes data | `fs.createWriteStream`, `http.ServerResponse` (`res`) |
| Duplex | Both, independent sides | TCP `net.Socket` |
| Transform | Duplex where output is derived from input | `zlib.createGzip()`, a CSV parser |

All of them are `EventEmitter`s. Readables emit `data` and `end`; writables expose `write()` and `end()` and emit `drain` and `finish`. Since Node 10 readables are also async iterables, so `for await (const chunk of stream)` works and is often the clearest way to consume one.

### Backpressure and highWaterMark

Backpressure is what happens when the consumer is slower than the producer, for example reading from a fast SSD and uploading to a slow S3 connection. Without control, chunks pile up in memory until the process crashes.

Each stream has an internal buffer limited by `highWaterMark`. File streams default to 64 KiB, and since Node 22 the default for byte streams in general is 64 KiB (it was 16 KiB before); object-mode streams default to 16 objects. When `writable.write(chunk)` returns `false`, the buffer is full and the producer should pause until `drain` fires. `pipe()` and `pipeline()` do this pausing for you.

### pipe() vs pipeline()

`readable.pipe(writable)` handles backpressure, but it does **not** forward errors or destroy the other streams when one fails, which leaks file descriptors. In production code, use `pipeline` from `node:stream/promises`: it wires up backpressure, propagates the first error, cleans up every stream, and returns a Promise you can `await`. It also accepts async generator functions as transform steps, which removes most of the need for custom `Transform` classes.

### Buffers in practice

- Create with `Buffer.from('hello')`, `Buffer.alloc(n)` (zero-filled, safe) or `Buffer.allocUnsafe(n)` (faster but may contain old memory, so overwrite it fully).
- Convert with `buf.toString('utf8' | 'base64' | 'hex')`.
- A chunk boundary can split a multi-byte UTF-8 character (common with Hindi or emoji text). Use `setEncoding('utf8')` or `StringDecoder` instead of calling `toString()` on each chunk.
- `new Buffer()` is deprecated; never use it.

### Where streams show up in real systems

Serving video or large downloads (`pipeline(fs.createReadStream(path), res)`), gzip compression, parsing large CSV exports line by line (for example a settlement report from a payment gateway), proxying uploads straight to S3 without touching disk, and streaming LLM or database results to the client as they arrive.

**A stream pipeline with backpressure. If the writable side slows down, pipeline pauses the readable side so memory stays flat.**

1. **Readable: file on disk**: Emits 64 KiB chunks as they are read.
2. **Transform: gzip**: Compresses each chunk as it passes through.
3. **Writable: HTTP response**: Sends bytes to the client over the network.
4. **Backpressure signal**: write() returns false, upstream pauses until drain.

## Code examples

### Reading Large Files: Buffer vs Stream

```
const fs = require('fs');

// BAD: loads entire file into memory
// For a 2GB file, this uses 2GB+ RAM
fs.readFile('huge.csv', 'utf8', (err, data) => {
  const lines = data.split('\n');
  console.log(`Lines: ${lines.length}`);
});

// GOOD: stream processes line by line
// Uses only a few KB of memory
const readline = require('readline');
const rl = readline.createInterface({
  input: fs.createReadStream('huge.csv'),
});

let count = 0;
rl.on('line', (line) => {
  count++;
});
rl.on('close', () => {
  console.log(`Lines: ${count}`);
});
```

fs.readFile pulls the whole file into memory, so a 2 GB CSV needs over 2 GB of RAM. readline over a read stream holds only the current chunk and line, so memory stays roughly constant.

### Compress and serve files with stream.pipeline

```
const fs = require('node:fs');
const zlib = require('node:zlib');
const http = require('node:http');
const { pipeline } = require('node:stream/promises');

// 1. Gzip a large file with constant memory
async function compress(src) {
  await pipeline(
    fs.createReadStream(src),
    zlib.createGzip(),
    fs.createWriteStream(src + '.gz'),
  );
  console.log('Compressed', src);
}

// 2. Stream a file to the client, uppercasing it on the way
http.createServer(async (req, res) => {
  res.setHeader('Content-Type', 'text/plain');
  try {
    await pipeline(
      fs.createReadStream('./report.txt', { encoding: 'utf8' }),
      async function* (source) {
        for await (const chunk of source) yield chunk.toUpperCase();
      },
      res,
    );
  } catch (err) {
    // client disconnected or file missing: all streams already cleaned up
    console.error('stream failed:', err.code);
  }
}).listen(3000);

compress('./access.log').catch(console.error);
```

pipeline handles backpressure like pipe() but also propagates errors and destroys every stream on failure. The second example uses an async generator as an inline transform.

### Custom Transform stream and Buffer basics

```
const { Transform } = require('node:stream');

// Counts bytes passing through without changing them
class ByteCounter extends Transform {
  constructor() { super(); this.bytes = 0; }
  _transform(chunk, encoding, callback) {
    this.bytes += chunk.length; // chunk is a Buffer
    callback(null, chunk);      // pass it downstream
  }
  _flush(callback) {
    console.error(`total: ${this.bytes} bytes`);
    callback();
  }
}

process.stdin.pipe(new ByteCounter()).pipe(process.stdout);

// Buffer basics
const a = Buffer.from('UPI ₹500', 'utf8');
console.log(a.length);              // bytes, not characters
console.log(a.toString('base64'));
const safe = Buffer.alloc(4);       // <Buffer 00 00 00 00>
console.log(safe);
```

A Transform receives chunks, calls the callback with transformed data, and the stream machinery handles buffering and backpressure. Buffer.alloc is zero-filled while allocUnsafe skips that step for speed.

## Key points

- Streams process data chunk by chunk, so memory stays flat regardless of input size.
- Four types: Readable, Writable, Duplex, Transform; req and res in Node HTTP are streams.
- Backpressure: write() returning false means pause until 'drain'; pipe and pipeline do it automatically.
- Prefer pipeline from node:stream/promises over pipe(), because pipe() does not forward errors or clean up.
- Buffer is a Uint8Array subclass; use Buffer.alloc or Buffer.from, never new Buffer().

## Common follow-up questions

- What is the difference between flowing mode and paused mode in a Readable stream?
- How would you write a CSV parser as a Transform stream that handles lines split across chunks?
- How would you upload a 5 GB file to S3 from Node without loading it into memory?
- What happens if you ignore the return value of writable.write()?

## Interview tips

- Lead with the memory argument and a concrete case, such as parsing a multi-GB log file.
- Explaining backpressure correctly is what separates strong answers; mention write() returning false and the drain event.
- Saying you use pipeline instead of pipe because of error handling signals production experience.

## Concepts covered

Readable Stream, Transform Stream, stream.pipeline, Backpressure, Buffer, highWaterMark

Previous: [Node.js Event Loop & Architecture](https://www.internhack.in/learn/interview/nodejs-interview/node-event-loop) · Next: [REST API Design & Middleware](https://www.internhack.in/learn/interview/nodejs-interview/node-rest-api-design) · [All of Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)

## More Node.js Interview questions

- [Node.js Basics & Runtime](https://www.internhack.in/learn/interview/nodejs-interview/node-basics-runtime)
- [Module System (CJS vs ESM)](https://www.internhack.in/learn/interview/nodejs-interview/node-module-system)
- [File System Operations](https://www.internhack.in/learn/interview/nodejs-interview/node-fs-operations)
- [Path & OS Modules](https://www.internhack.in/learn/interview/nodejs-interview/node-path-os)
- [HTTP Module & Server Creation](https://www.internhack.in/learn/interview/nodejs-interview/node-http-server)
- [Express.js Fundamentals](https://www.internhack.in/learn/interview/nodejs-interview/node-express-fundamentals)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)
