Using readable streams
As a JavaScript developer, programmatically reading and manipulating streams of data received over the network, chunk by chunk, is very useful! But how do you use the Streams API's readable stream functionality? This article explains the basics.
Note: This article assumes that you understand the use cases of readable streams, and are aware of the high-level concepts. If not, we suggest that you first read the Streams concepts and usage overview and dedicated Streams API concepts article, then come back.
Note: If you are looking for information on writable streams try Using writable streams instead.
Finding some examples
We will look at various examples in this article, taken from our dom-examples/streams repo. You can find the full source code there, as well as links to the examples.
Consuming a fetch as a stream
The Fetch API allows you to fetch resources across the network, providing a modern alternative to XHR. It has a number of advantages, and what is really nice about it is that browsers have recently added the ability to consume a fetch response as a readable stream.
The Request.body
and Response.body
properties are available, which are getters exposing the body contents as a readable stream.
As our Simple stream pump example shows (see it live also), exposing it is a matter of just accessing the body
property of the response:
// Fetch the original image
fetch("./tortoise.png")
// Retrieve its body as ReadableStream
.then((response) => response.body);
This provides us with a