This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The body
read-only property of the Body
mixin is a simple getter used to expose a ReadableStream
of the body contents.
var stream = responseInstance.body;
In our simple stream pump example we fetch an image, expose the response's stream using response.body
, create a reader using ReadableStream.getReader()
, then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image.
const image = document.getElementById('target'); // Fetch the original image fetch('./tortoise.png') // Retrieve its body as ReadableStream .then(response => response.body) .then(body => { const reader = body.getReader(); return new ReadableStream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // When no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // Enqueue the next data chunk into our target stream controller.enqueue(value); return pump(); }); } } }) }) .then(stream => new Response(stream)) .then(response => response.blob()) .then(blob => URL.createObjectURL(blob)) .then(url => console.log(image.src = url)) .catch(err => console.error(err));
Specification | Status | Comment |
---|---|---|
Fetch The definition of 'body' in that specification. | Living Standard |
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | 52.0 | No support[1] | No support | 39 | ? |
Feature | Android Webview | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | 52 | 52 | No support[1] | No support | 39 | ? |
[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/Body/body