Course contentsShow
← JavaScript
Lesson 1571 of 2,72334. Streams and BuffersFree lesson

Built-in Transform Examples

Using Node's zlib, crypto, and stream.Transform for real-world transformations.

Built-in Transform Examples

You'll learn: How to use Node.js's ready-made transform streams for compression, encryption, and data processing without building your own from scratch.

Why Use Built-in Transforms?

Node.js provides powerful transform streams in modules like zlib (compression), crypto (encryption), and the base stream.Transform class. Instead of implementing _transform() yourself for common tasks, these built-in transforms handle complex operations efficiently and reliably.

Think of them as pre-built kitchen appliances: you could knead dough by hand (custom transform), but a stand mixer (built-in transform) does the job faster and more consistently.

zlib for Compression

The zlib module creates transform streams that compress or decompress data on-the-fly:

import { createReadStream, createWriteStream } from 'fs';
import { createGzip } from 'zlib';

// Compress a file as it's read
createReadStream('largefile.txt')
  .pipe(createGzip())
  .pipe(createWriteStream('largefile.txt.gz'));

This reads the file, compresses chunks as they flow through, and writes the compressed result—all with controlled memory usage.

crypto for Encryption

The crypto module provides transforms for hashing and encryption:

import { createReadStream } from 'fs';
import { createHash } from 'crypto';

const hash = createHash('sha256');
createReadStream('document.pdf')
  .pipe(hash)
  .on('finish', () => {
    console.log('Hash:', hash.digest('hex'));
  });

Data flows through the hash transform, computing the checksum incrementally.

Combining Built-in Transforms

You can chain them together using pipe():

import { createGzip } from 'zlib';
import { createCipheriv } from 'crypto';

// Compress THEN encrypt
sourceStream
  .pipe(createGzip())
  .pipe(createCipheriv('aes-256-cbc', key, iv))
  .pipe(destinationStream);

Key Takeaway: Node's built-in transform streams in zlib, crypto, and other modules provide production-ready data transformations that handle backpressure and memory efficiently, letting you pipe complex operations together without custom implementation.