The ReadableByteStreamController
interface of the Streams API represents a controller for a readable byte stream. It allows control of the state and internal queue of a ReadableStream
with an underlying byte source, and enables efficient zero-copy transfer of data from the underlying source to a consumer when the stream's internal queue is empty.
An instance of this controller type is created if an underlyingSource
object with the property type="bytes"
is passed as an argument to the ReadableStream()
constructor. The underlyingSource
object may also define start()
and pull()
callback functions. These are called with the controller as a parameter, in order to setup the underlying source, and request data when needed.
The underlying source uses the controller to supply data to the stream via its byobRequest
property or enqueue()
method. byobRequest
is a ReadableStreamBYOBRequest
object that represents a pending request from a consumer to make a zero-copy transfer of data direct to a consumer. byobRequest
must be used to copy data if it exists (do not use enqueue()
in this case)! If the underlying source needs to pass data to the stream and byobRequest
is null
then the source can call enqueue()
to add the data to the stream's internal queues.
Note that the byobRequest
is only created in "BYOB mode" when there is a request from a reader and the stream's internal queue is empty. "BYOB mode" is enabled when using a ReadableStreamBYOBReader
(typically constructed by calling ReadableStream.getReader()
with the argument { mode: 'byob' }
). It is also enabled when using a default reader and autoAllocateChunkSize
is specified in the ReadableController()
constructor.
An underlying byte source can also use the controller to close()
the stream when all the data has been sent and report errors from the underlying source using error()
. The controller's desiredSize
property is used to apply "backpressure", informing the underlying source of the size of the internal queue (small values indicate that the queue is filling up, hinting to the underlying source that it is be desirable to pause or throttle the inflow).
Note that even though the controller is primarily used by the underlying byte source, there is no reason it cannot be stored used by other parts of the system to signal the stream.