Streaming involves breaking a resource that you want to receive over a network down into small chunks, then processing it bit by bit. This is something browsers do anyway when receiving assets to be shown on webpages — videos buffer and more is gradually available to play, and sometimes you'll see images display gradually as more is loaded.
There are more advantages too — you can detect when streams start or end, chain streams together, handle errors and cancel streams as required, and react to the speed the stream is being read at.
The basic usage of Streams hinges around making responses available as streams. For example, the response
Body returned by a successful fetch request can be exposed as a
ReadableStream, and you can then read it using a reader created with
ReadableStream.getReader(), cancel it with
You can also write data to streams using
ReadableStream's state and internal queue. Default controllers are for streams that are not byte streams.
WritableStream's state. When constructing a
WritableStream, the underlying sink is given a corresponding
WritableStreamDefaultControllerinstance to manipulate.
Requestobject is constructed, you can pass it a
bodyproperty of its
Requestcould then be passed to a
WindowOrWorkerGlobalScope.fetch()to commence fetching the stream.
Bodyreturned by a successful fetch request is exposed by default as a
ReadableStream, and can have a reader attached to it, etc.
Important: these are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. This may change over time.
ReadableStream's state and internal queue. Byte stream controllers are for byte streams.
We have created a directory of examples to go along with the Streams API documentation — see mdn/dom-examples/streams. The examples are as follows:
pipeThrough()can be used to transform a ReadableStream into a stream of other data types by transforming a data of a PNG file into a stream of PNG chunks.
Examples from other developers:
|Streams||Living Standard||Initial definition.|
|Android webview||Chrome for Android||Edge Mobile||Firefox for Android||Opera for Android||iOS Safari||Samsung Internet|
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.