Basic Pipe Syntax
What you'll learn: How to use readableStream.pipe(writableStream) to automatically connect streams and manage data flow without manual event handling.
The Core Idea
You've learned how to read from readable streams and write to writable streams manually, handling events like 'data', 'end', and 'drain'. But there's a much simpler way: piping.
Piping connects a readable stream directly to a writable stream, automatically handling all the data transfer, backpressure, and cleanup for you. It's like connecting two garden hoses—once connected, water flows automatically from source to destination.
The Syntax
readableStream.pipe(writableStream);
That's it! This single line:
- Listens for data from the readable stream
- Writes each chunk to the writable stream
- Handles backpressure (pauses reading when writing can't keep up)
- Automatically ends the writable stream when reading finishes
- Manages error propagation
A Simple Example
const fs = require('fs');
const readable = fs.createReadStream('input.txt');
const writable = fs.createWriteStream('output.txt');
readable.pipe(writable);
This copies input.txt to output.txt efficiently, chunk by chunk, without loading the entire file into memory. No manual event listeners needed!
Why It Matters
Before pipes, you'd write dozens of lines handling 'data', 'end', 'drain', and 'error' events. Piping replaces all that boilerplate with one method call, making stream code cleaner and less error-prone.
Key Takeaway: readableStream.pipe(writableStream) automatically connects streams, handling data flow, backpressure, and cleanup—turning complex stream management into a single, elegant line of code.