The ReadableStream()
constructor creates and returns a readable stream object from the given handlers.
Note that while all parameters are technically optional, omitting the underlyingSource
will result in a stream that has no source, and that can't be read from (readers return a promise that will never be resolved).
new ReadableStream()
new ReadableStream(underlyingSource)
new ReadableStream(underlyingSource, queuingStrategy)
An instance of the ReadableStream
object.
In the following simple example, a custom ReadableStream
is created using a constructor (see our Simple random stream example for the full code). The start()
function generates a random string of text every second and enqueues it into the stream. A cancel()
function is also provided to stop the generation if ReadableStream.cancel()
is called for any reason.
When a button is pressed, the generation is stopped, the stream is closed using ReadableStreamDefaultController.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();
controller.enqueue(string);
let listItem = document.createElement("li");
listItem.textContent = string;
list1.appendChild(listItem);
}, 1000);
button.addEventListener("click", () => {
clearInterval(interval);
fetchStream();
controller.close();
});
},
pull(controller) {
},
cancel() {
clearInterval(interval);
},
});