This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
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()ReadableStream.locked Read only
locked getter returns whether or not the readable stream is locked to a reader.ReadableStream.cancel()ReadableStream.getReader()ReadableStream.pipeThrough()ReadableStream.pipeTo()WritableStream and returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.ReadableStream.tee()tee method tees this readable stream, returning a two-element array containing the two resulting branches as new ReadableStream instances.In the following example, an artifical 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) => {
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);
}).then(push);
};
push();
}
});
return new Response(stream, { headers: { "Content-Type": "text/html" } });
});
| Specification | Status | Comment |
|---|---|---|
| Streams The definition of 'ReadableStream' in that specification. | Living Standard | Initial definition |
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | 43.0 | No support[1] | ? | 39 | ? |
pipeThrough and pipeTo methods | 59.0 | No support[1] | ? | 46 | ? |
| Feature | Android Webview | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | 43 | 43 | No support[1] | ? | 39 | ? |
pipeThrough and pipeTo methods | 59 | 59 | No support[1] | ? | 46 | ? |
[1] Readable streams are currently enabled in Firefox, but hidden behind the dom.streams.enabled and javascript.options.streams prefs.
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream