The ReadableStream
interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream
through the body
property of a Response
object.
ReadableStream
is a transferable object.
ReadableStream
implements the async iterable protocol. This enables asynchronous iteration over the chunks in a stream using the for await...of
syntax:
const stream = new ReadableStream(getSomeSource());
for await (const chunk of stream) {
}
The async iterator consumes the stream until it runs out of data or otherwise terminates. The loop can also exit early due to a break
, throw
, or return
statement.
While iterating, the stream is locked to prevent other consumers from acquiring a reader (attempting to iterate over a stream that is already locked will throw a TypeError
). This lock is released when the loop exits.
By default, exiting the loop will also cancel the stream, so that it can no longer be used. To continue to use a stream after exiting the loop, pass { preventCancel: true }
to the stream's values()
method:
for await (const chunk of stream.values({ preventCancel: true })) {
break;
}
In the following example, an artificial Response
is created to stream HTML fragments fetched from another resource to the browser.
It demonstrates the usage of a ReadableStream
in combination with a Uint8Array
.
fetch("https://www.example.org")
.then((response) => response.body)
.then((rb) => {
const reader = rb.getReader();
return new ReadableStream({
start(controller) {
function push() {
reader.read().then(({ done, value }) => {
if (done) {
console.log("done", done);
controller.close();
return;
}
controller.enqueue(value);
console.log(done, value);
push();
});
}
push();
},
});
})
.then((stream) =>
new Response(stream, { headers: { "Content-Type": "text/html" } }).text(),
)
.then((result) => {
console.log(result);
});
The from()
static method can convert an iterator, such as an Array
or Map
, or an (async) iterator to a readable stream:
const myReadableStream = ReadableStream.from(iteratorOrAsyncIterator);
On browsers that don't support the from()
method you can instead create your own custom readable stream to achieve the same result:
function iteratorToStream(iterator) {
return new ReadableStream({
async pull(controller) {
const { value, done } = await iterator.next();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
},
});
}
This example shows how you can process the fetch()
response using a for await...of
loop to iterate through the arriving chunks.
const response = await fetch("https://www.example.org");
let total = 0;
for await (const chunk of response.body) {
total += chunk.length;
}
console.log(total);