Consuming Streams with pipeTo
You'll learn how to efficiently transfer data from a ReadableStream directly to a WritableStream using pipeTo(), eliminating manual read loops.
The Direct Pipeline
Until now, you've manually read chunks from a ReadableStream using read() loops. But when your goal is to transfer stream data to a destination (like a file or another network endpoint), there's a more elegant approach: pipe it directly.
The pipeTo() method connects a ReadableStream to a WritableStream, automatically handling all the reading, writing, backpressure, and error propagation for you. Think of it like connecting two garden hoses end-to-end—water flows automatically without you manually bucketing it across.
How It Works
Call pipeTo() on a ReadableStream, passing a WritableStream as the argument:
async function streamToDestination(response) {
// Get the readable stream from fetch
const readableStream = response.body;
// Create a writable stream (hypothetical destination)
const writableStream = getWritableDestination();
// Pipe directly - no manual loops!
await readableStream.pipeTo(writableStream);
console.log('Stream fully transferred');
}
The pipeTo() method returns a promise that resolves when the stream completes or rejects if an error occurs. JavaScript handles all the reading and writing internally, respecting backpressure signals to prevent overwhelming the destination.
Why Use pipeTo
Instead of writing manual read() loops to transfer data chunk-by-chunk, pipeTo() does it all for you with better efficiency and automatic error handling. It's the preferred method when you need to move data from one stream endpoint to another.
Key Takeaway: Use pipeTo() to connect a ReadableStream directly to a WritableStream for automatic, efficient data transfer without manual chunk processing loops.