ReadableStream: ReadableStream() constructor
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.
TheReadableStream() constructor creates and returns a readable stream object from the given handlers.
Note that while all parameters are technically optional, omitting theunderlyingSource 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).
In this article
Syntax
new ReadableStream()new ReadableStream(underlyingSource)new ReadableStream(underlyingSource, queuingStrategy)Parameters
underlyingSourceOptionalAn object containing methods and properties that define how the constructed stream instance will behave.
underlyingSourcecan contain the following:start(controller)OptionalThis is a method, called immediately when the object is constructed. Thecontents of this method are defined by the developer, and should aim to get accessto the stream source, and do anything else required to set up the streamfunctionality. If this process is to be done asynchronously, it can return apromise to signal success or failure. The
controllerparameter passedto this method is aReadableStreamDefaultControlleror aReadableByteStreamController, depending on the value of thetypeproperty. This can be used by the developer to control thestream during set up.pull(controller)OptionalThis method, also defined by the developer, will be called repeatedly when thestream's internal queue of chunks is not full, up until it reaches its high watermark. If
pull()returns a promise, then it won't be called againuntil that promise fulfills; if the promise rejects, the stream will becomeerrored. Thecontrollerparameter passed to this method is aReadableStreamDefaultControlleror aReadableByteStreamController, depending on the value of thetypeproperty. This can be used by the developer to control thestream as more chunks are fetched. This function will not be called untilstart()successfully completes. Additionally, it will only be called repeatedly if itenqueues at least one chunk or fulfills a BYOB request; a no-oppull()implementation will not be continually called.cancel(reason)OptionalThis method, also defined by the developer, will be called if the app signalsthat the stream is to be cancelled (e.g., if
ReadableStream.cancel()is called). The contents should do whatever is necessary to release access to thestream source. If this process is asynchronous, it can return a promise to signalsuccess or failure. Thereasonparameter contains astring describing why the stream was cancelled.typeOptionalThis property controls what type of readable stream is being dealt with. If itis included with a value set to
"bytes", the passed controller objectwill be aReadableByteStreamControllercapable of handling a BYOB(bring your own buffer)/byte stream. If it is not included, the passed controllerwill be aReadableStreamDefaultController.autoAllocateChunkSizeOptionalFor byte streams, the developer can set the
autoAllocateChunkSizewith a positive integer value to turn on the stream's auto-allocation feature.With this is set, the stream implementation will automatically allocate a view buffer of the specified size inReadableByteStreamController.byobRequestwhen required.This must be set to enable zero-copy transfers to be used with a default
ReadableStreamDefaultReader.If not set, a default reader will still stream data, butReadableByteStreamController.byobRequestwill always benulland transfers to the consumer must be via the stream's internal queues.
queuingStrategyOptionalAn object that optionally defines a queuing strategy for the stream. This takes twoparameters:
highWaterMarkA non-negative integer — this defines the total size of all chunks that can becontained in the internal queue before backpressure is applied.
size(chunk)A method containing a parameter
chunk— this indicates the size touse for each chunk, in bytes.
Note:You could define your own custom
queuingStrategy, or use an instance ofByteLengthQueuingStrategyorCountQueuingStrategyfor this object value. If noqueuingStrategyis supplied, the defaultused is the same as aCountQueuingStrategywith a high water mark of1.
Return value
An instance of theReadableStream object.
Exceptions
RangeErrorThrown if the supplied type value is neither
"bytes"norundefined.
Examples
In the following simple example, a customReadableStream is created usinga constructor (see ourSimple random stream example for the full code). Thestart() function generates arandom 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.
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> # ref-for-rs-constructor⑤> |