Skip to the content

Lesson 191 of 296

Streams and buffers

What you will learn

  • What a Buffer is
  • What streams are and why they save memory
  • The four kinds of streams
  • Piping, pipeline and backpressure
  • Streaming a big file over HTTP
  • Transform streams and async iteration
On this page

Buffer

A Buffer is a fixed-size piece of raw binary data (bytes). Node.js uses Buffers for file contents, network packets and images.

TypeScript
const buf = Buffer.from("Héllo", "utf8");
console.log(buf.length);
console.log(buf.toString("hex"));
console.log(buf.toString("base64"));
console.log(Buffer.from("SMOpbGxv", "base64").toString("utf8"));

Prints 6 (the "é" takes 2 bytes in UTF-8, so bytes are not the same as characters, Lesson 33), the hex string, SMOpbGxv, and Héllo. Buffers are a kind of Uint8Array.

What is a stream?

A stream handles data piece by piece (in chunks) instead of all at once.

Reading a 2 GB log file with readFile loads all 2 GB into memory, which can crash the server. A stream reads, say, 64 KB at a time, processes it, and lets it go. Memory stays small and work starts immediately.

Stream typeMeaningExamples
ReadableA source you read fromfs.createReadStream, an incoming HTTP request (req)
WritableA destination you write tofs.createWriteStream, an HTTP response (res)
DuplexBoth readable and writableA TCP socket
TransformA duplex that changes data as it passes throughgzip compression, encryption, CSV parsing

Pipe and pipeline

Piping connects a readable to a writable: data flows automatically.

Use pipeline (from node:stream/promises), which pipes and handles errors and clean-up for every stream:

TypeScript
import { createReadStream, createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { createGzip } from "node:zlib";

export async function gzipFile(source: string, destination: string): Promise<void> {
  await pipeline(createReadStream(source), createGzip(), createWriteStream(destination));
}

With the older source.pipe(destination), an error in one stream does not close the others, which can leak file handles. Prefer pipeline.

Backpressure

What if the source is faster than the destination (reading a fast disk, sending to a slow mobile connection)? Data would pile up in memory. Backpressure is the mechanism that slows the source down: writable.write() returns false when its internal buffer is full, and the source pauses until the drain event. pipe and pipeline handle this for you. This is a common interview question.

Streaming a file over HTTP

TypeScript
import { createServer } from "node:http";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { pipeline } from "node:stream/promises";

export function createDownloadServer(filePath: string) {
  return createServer(async (req, res) => {
    try {
      const info = await stat(filePath);
      res.writeHead(200, {
        "Content-Type": "text/csv; charset=utf-8",
        "Content-Length": info.size,
        "Content-Disposition": 'attachment; filename="report.csv"'
      });
      await pipeline(createReadStream(filePath), res);
    } catch {
      if (!res.headersSent) res.writeHead(500).end("Could not send file");
      else res.destroy();
    }
  });
}

Memory use stays small no matter how big the file is. If the client disconnects, pipeline destroys the file stream.

Transform streams and async iteration

A transform that turns text to upper case:

TypeScript
import { Transform } from "node:stream";

export function upperCase() {
  return new Transform({
    transform(chunk: Buffer, _encoding, callback) {
      callback(null, chunk.toString("utf8").toUpperCase());
    }
  });
}

Readable streams can also be read with for await (Lesson 80), which is often the simplest way to process lines or chunks:

TypeScript
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";

export async function countErrorLines(logPath: string): Promise<number> {
  const lines = createInterface({ input: createReadStream(logPath), crlfDelay: Infinity });
  let count = 0;
  for await (const line of lines) {
    if (line.includes("ERROR")) count++;
  }
  return count;
}

This handles a log file of any size with tiny memory use.

Where streams appear

  • Uploading and downloading files (to S3, Lesson 254).
  • Exporting large CSV reports from a database cursor.
  • Proxying responses.
  • Compression.
  • Streaming AI responses token by token (Lesson 274) and Server-Sent Events.
  • The web standard Web Streams (ReadableStream), used by fetch and Next.js, also exist in Node.js.

How to say it in an interview

"A Buffer holds raw bytes. Streams process data in chunks, so memory stays small and work starts early: readable, writable, duplex and transform streams. I connect them with stream.pipeline, which propagates errors and cleans up, unlike plain pipe. Backpressure stops a fast source from overwhelming a slow destination: write returns false and the source pauses until drain, which pipeline handles automatically. I use streams for file downloads and uploads, large exports, compression and reading big files line by line with for await."

Key words

WordMeaning
BufferA fixed-size block of raw bytes
StreamData processed piece by piece
ChunkOne piece of streamed data
Readable / Writable / Duplex / TransformThe four kinds of streams
pipelineConnects streams and handles errors and clean-up
BackpressureSlowing a fast source to match a slow destination

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.