WritableStream
The WritableStream interface of Azion Runtime: its constructor, the locked property, and the methods that abort, close, and lock a stream to a writer.
The WritableStream interface is part of the Streams API of Azion Runtime. It writes a stream of data to a destination, called a sink, one chunk at a time. It queues the chunks and applies backpressure, so the sink receives data at the rate it can take it. For more information, refer to WritableStream on MDN Web Docs.
In a function, a WritableStream produces output chunk by chunk, so a large or generated response body never sits whole in memory. It is the writable side of a TransformStream, which rewrites or filters a payload as it passes through the function. It is also the destination of pipeTo() on a ReadableStream: backpressure slows the readable stream to the rate the sink consumes.
Constructor
The WritableStream() constructor creates and returns a writable stream object from a sink and an optional queuing strategy:
The sink object takes a write(chunk) method, called for each chunk written to the stream, and a close() method, called when the stream closes. Its abort(reason) method receives the reason passed to stream.abort(). The strategy object sets the size of the queue, such as new CountQueuingStrategy({ highWaterMark: 2 }), which counts chunks. The Example section shows a stream built this way.
Properties
| Property | Type | Description |
|---|---|---|
locked | Boolean | true while a writer holds the stream. It is true after getWriter() and false after the writer calls releaseLock(). |
Methods
| Method | Description |
|---|---|
stream.abort(reason) | Aborts the stream. The producer can no longer write to it, the stream moves to an error state at once, and any queued writes are discarded. The abort() method of the sink receives reason. Call it when an error occurs, so partial or invalid output is discarded. |
stream.close() | Closes the stream and runs the close() method of the sink. Returns a promise. |
stream.getWriter() | Returns a WritableStreamDefaultWriter and locks the stream to it. While the stream is locked, you cannot acquire another writer until the first one is released. |
Example
This handler constructs a stream whose sink collects each chunk, writes two chunks through a writer, and closes the writer. It returns the locked value, the class name and desiredSize of the writer, and the chunks the sink received:
The function returns these values. The stream is locked because the writer holds it, and desiredSize starts at the highWaterMark of the queuing strategy: