Streams & Buffers

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

TypeWhat it doesExamples
ReadableProduces datafs.createReadStream, http.IncomingMessage (req)
WritableConsumes datafs.createWriteStream, http.ServerResponse (res)
DuplexBoth, independent sidesTCP net.Socket
TransformDuplex where output is derived from inputzlib.createGzip(), a CSV parser

All of them are EventEmitters. 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

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

Common follow-up questions

Interview tips

Concepts covered

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

More Node.js Interview questions