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

Chaining Multiple Pipes

Connecting multiple transform streams in sequence using pipe chaining for data processing pipelines.

Chaining Multiple Pipes

You'll learn how to connect multiple transform streams in sequence to build powerful data processing pipelines.

The Assembly Line Analogy

Think of chaining pipes like an assembly line in a factory. Raw material enters at one end, passes through multiple stations (each performing a specific transformation), and emerges as a finished product at the other end. Each station receives input from the previous one and sends output to the next.

How Pipe Chaining Works

You've already learned basic piping with .pipe(). The magic is that .pipe() returns the destination stream, allowing you to immediately call .pipe() again on that result. This creates a chain:

const fs = require('fs');
const { Transform } = require('stream');

// Transform 1: Convert to uppercase
const upperCase = new Transform({
  transform(chunk, encoding, callback) {
    callback(null, chunk.toString().toUpperCase());
  }
});

// Transform 2: Replace spaces with hyphens
const replaceSpaces = new Transform({
  transform(chunk, encoding, callback) {
    callback(null, chunk.toString().replace(/ /g, '-'));
  }
});

// Chain them together
fs.createReadStream('input.txt')
  .pipe(upperCase)           // First transformation
  .pipe(replaceSpaces)       // Second transformation
  .pipe(fs.createWriteStream('output.txt')); // Final destination

In this pipeline, data flows through three stages: reading → uppercasing → replacing spaces → writing. Each transform processes chunks as they arrive, maintaining Node.js's efficient streaming model.

Why Chain?

Chaining keeps each transform focused on one task (single responsibility), makes your code modular and testable, and allows you to reuse transforms in different combinations.

Key Takeaway: Pipe chaining connects multiple transform streams in sequence by calling .pipe() repeatedly, creating modular data processing pipelines where each stream performs one specific transformation.