agyanadda@gmail.com

Node.js Streams and Buffers

Node.js Core Modules 1 min read Updated Dec 3, 2026 Topic 10 of 30

Buffers

A Buffer holds raw binary data (bytes) — images, files, network data.

  • Buffer.from('Hello') — text to bytes
  • buf.toString('utf8'), buf.toString('base64')
  • buf.length — size in bytes

Streams

A stream processes data piece by piece (chunks) instead of loading everything into memory. A 2 GB video can be sent with a few KB of memory.

Type Example
Readable fs.createReadStream, an HTTP request
Writable fs.createWriteStream, an HTTP response
Duplex a network socket
Transform gzip compression

Connecting streams

Use pipeline() from node:stream/promises to connect streams. It handles errors and closes everything properly. (readable.pipe(writable) also works but does not handle errors well.)

Stream events

data, end, error, finish. You can also read a stream with for await (const chunk of stream).

Example

Example — Compress a large log file JavaScript
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';

console.time('gzip');

await pipeline(
  createReadStream('server.log'),      // read in chunks
  createGzip(),                        // transform: compress
  createWriteStream('server.log.gz'),  // write in chunks
);

console.timeEnd('gzip');
console.log('Done: server.log.gz created');

// Buffers
const buf = Buffer.from('Namaste');
console.log(buf);                     // <Buffer 4e 61 6d 61 73 74 65>
console.log(buf.toString('base64'));  // TmFtYXN0ZQ==

The log file is compressed using little memory however large it is. The Buffer lines show the raw bytes of "Namaste" and its base64 form.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Why use streams for big files?

Exercise 2 True / False

pipeline() handles errors and closes all connected streams.

Exercise 3 Fill in the Blank

A stream that changes data as it passes through is a ___ stream.

Frequently Asked Questions

Use them for large file downloads and uploads, video or audio, CSV exports and reading big log files. For small JSON responses, normal code is simpler.