What is Piping in Streams?

1. Definition

Piping in Node.js streams is a method used to connect the output of one stream directly to the input of another stream. It allows data to flow automatically from one place to another.

2. Why We Use Piping

  • Efficient data transfer
  • Reduces memory usage
  • Handles large files easily
  • Automatic data flow between streams

3. How Piping Works

  • Readable stream provides data
  • Writable stream receives data
  • pipe() connects both streams

4. Example

const fs = require("fs");

const readStream = fs.createReadStream("input.txt");
const writeStream = fs.createWriteStream("output.txt");

// Pipe data from input to output
readStream.pipe(writeStream);

5. Data Flow

input.txt  --->  Readable Stream  --->  pipe()  --->  Writable Stream  --->  output.txt

6. Advantages

  • Efficient for large data handling
  • Reduces manual coding
  • Improves performance
  • Automatic flow control