ReadableStream
The ReadableStream interface of Azion Runtime: its constructor, the locked property, and the methods that read, cancel, pipe, and split a stream.
The ReadableStream interface is part of the Streams API of Azion Runtime. It reads a stream of data one chunk at a time, such as the byte data of a response body. The Fetch API provides a specific instance of ReadableStream: the body property of a Response object. For more information, refer to ReadableStream on MDN Web Docs.
Constructor
The ReadableStream() constructor creates and returns a readable stream object from the handlers you pass to it:
The handlers object takes a start(controller) method and a cancel(reason) method. In start(), controller.enqueue() adds a chunk to the stream and controller.close() ends it. The cancel() method receives the reason passed to stream.cancel(). Chunks are not limited to bytes: a stream you construct can carry strings or numbers. To create a byte stream, add type: 'bytes' to the handlers object. The Example section shows a stream built this way.
Properties
| Property | Type | Description |
|---|---|---|
locked | Boolean | true while a reader holds the stream. It is false before getReader() and after the reader calls releaseLock(). |
Methods
| Method | Description |
|---|---|
stream.cancel(reason) | Returns a promise that resolves when the stream is canceled. A call signals that the consumer has lost interest in the stream. The cancel() handler of the stream receives reason and can use it or ignore it. |
stream.getReader() | Creates a reader and locks the stream to it. While the stream is locked, you cannot acquire another reader until the first one is released. For the methods of the reader, refer to ReadableStreamDefaultReader. |
stream.pipeThrough(transform) | Pipes the stream through a transform stream, or through any other pair of a writable and a readable stream, and returns the readable side. The call is chainable. |
stream.pipeTo(destination) | Pipes the stream to a WritableStream. Returns a promise that fulfills when the piping completes, or rejects when an error occurs. |
stream.tee() | Splits the stream into two branches and returns them as an array of two ReadableStream instances. Each branch receives the same chunks. |
ReadableStream also implements the async iterable protocol, so a for await…of loop reads the chunks of a stream in order.
Example
This handler constructs a stream of two chunks, reads it with a reader, releases the reader, and returns the locked value at each stage with the three results of read():
The function returns these values. The third read() reports done as true after the stream closes, and "[undefined]" marks its value, which is undefined: