Canceling a Stream Early
What you'll learn: How to stop reading from a response stream before it completes and properly release resources.
When you're reading a ReadableStream (like from a fetch response), you might discover you don't need the rest of the data—maybe you found what you were looking for in the first few chunks, or the user navigated away. Continuing to read wastes bandwidth and memory.
This is where reader.cancel() comes in.
Why Cancel a Stream?
Think of a stream like a water hose actively filling a bucket. If you only needed a little water and walk away, the hose keeps running, wasting water and potentially overflowing. Canceling the stream is like turning off the hose—you stop the flow immediately and signal that you're done.
How to Cancel
After you've called getReader() on a stream and started reading chunks with read(), you can call cancel() on the reader at any time:
const response = await fetch('https://example.com/large-file');
const reader = response.body.getReader();
try {
const { value, done } = await reader.read();
// Maybe we only needed the first chunk
if (foundWhatWeNeed(value)) {
await reader.cancel(); // Stop here!
console.log('Stream canceled, no more data will be read');
}
} finally {
reader.releaseLock();
}
What Happens When You Cancel
- The stream stops fetching data immediately
- The connection may close (depending on the server)
- The reader's lock is not automatically released—you still need to call
releaseLock()if you need to access the stream again - Future
read()calls will resolve with{ done: true }
Key Takeaway: Use reader.cancel() to stop reading a stream early, freeing up resources when you don't need the remaining data—but remember to still release the lock afterward.