ReadableStreamDefaultController
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.
Note: This feature is available inWeb Workers.
TheReadableStreamDefaultController
interface of theStreams API represents a controller allowing control of aReadableStream
's state and internal queue. Default controllers are for streams that are not byte streams.
In this article
Constructor
None.ReadableStreamDefaultController
instances are created automatically duringReadableStream
construction.
Instance properties
ReadableStreamDefaultController.desiredSize
Read onlyReturns the desired size required to fill the stream's internal queue.
Instance methods
ReadableStreamDefaultController.close()
Closes the associated stream.
ReadableStreamDefaultController.enqueue()
Enqueues a given chunk in the associated stream.
ReadableStreamDefaultController.error()
Causes any future interactions with the associated stream to error.
Examples
In the following simple example, a customReadableStream
is created using a constructor (see ourSimple random stream example for the full code). Thestart()
function generates a random string of text every second and enqueues it into the stream. Acancel()
function is also provided to stop the generation ifReadableStream.cancel()
is called for any reason.
Note that aReadableStreamDefaultController
object is provided as the parameter of thestart()
andpull()
functions.
When a button is pressed, the generation is stopped, the stream is closed usingReadableStreamDefaultController.close()
, and another function is run, which reads the data back out of the stream.
let interval;const stream = new ReadableStream({ start(controller) { interval = setInterval(() => { let string = randomChars(); // Add the string to the stream controller.enqueue(string); // show it on the screen let listItem = document.createElement("li"); listItem.textContent = string; list1.appendChild(listItem); }, 1000); button.addEventListener("click", () => { clearInterval(interval); fetchStream(); controller.close(); }); }, pull(controller) { // We don't really need a pull in this example }, cancel() { // This is called if the reader cancels, // so we should stop generating strings clearInterval(interval); },});
Specifications
Specification |
---|
Streams> # rs-default-controller-class> |
Browser compatibility
Loading…