ReadableStreamDefaultReader
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
* Some parts of this feature may have varying levels of support.
Note: This feature is available inWeb Workers.
TheReadableStreamDefaultReader
interface of theStreams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request).
AReadableStreamDefaultReader
can be used to read from aReadableStream
that has an underlying source of any type (unlike aReadableStreamBYOBReader
, which can only be used with readable streams that have anunderlying byte source).
Note however that zero-copy transfer from an underlying source is only supported for underlying byte sources that autoallocate buffers.In other words, the stream must have beenconstructed specifying bothtype="bytes"
andautoAllocateChunkSize
.For any other underlying source, the stream will always satisfy read requests with data from internal queues.
In this article
Constructor
ReadableStreamDefaultReader()
Creates and returns a
ReadableStreamDefaultReader
object instance.
Instance properties
ReadableStreamDefaultReader.closed
Read onlyReturns a
Promise
that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process.
Instance methods
ReadableStreamDefaultReader.cancel()
Returns a
Promise
that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The suppliedreason
argument will be given to the underlying source, which may or may not use it.ReadableStreamDefaultReader.read()
Returns a promise providing access to the next chunk in the stream's internal queue.
ReadableStreamDefaultReader.releaseLock()
Releases the reader's lock on the stream.
Examples
In the following example, an artificialResponse
is created to stream HTML fragments fetched from another resource to the browser.
It demonstrates the usage of aReadableStream
in combination with aUint8Array
.
fetch("https://www.example.org/").then((response) => { const reader = response.body.getReader(); const stream = new ReadableStream({ start(controller) { // The following function handles each data chunk function push() { // "done" is a Boolean and value a "Uint8Array" return reader.read().then(({ done, value }) => { // Is there no more data to read? if (done) { // Tell the browser that we have finished sending data controller.close(); return; } // Get the data and send it to the browser via the controller controller.enqueue(value); push(); }); } push(); }, }); return new Response(stream, { headers: { "Content-Type": "text/html" } });});
Specifications
Specification |
---|
Streams> # default-reader-class> |
Browser compatibility
Loading…