# WritableStream

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](https://developer.mozilla.org/en-US/docs/Web/API/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](/en/documentation/devtools/runtime/api-reference/transform-stream/), which rewrites or filters a payload as it passes through the function. It is also the destination of `pipeTo()` on a [ReadableStream](/en/documentation/devtools/runtime/api-reference/readable-stream/): backpressure slows the readable stream to the rate the sink consumes.

---

## Constructor

The [`WritableStream()`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream/WritableStream) constructor creates and returns a writable stream object from a sink and an optional queuing strategy:

```javascript
new WritableStream(sink, 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](#example) section shows a stream built this way.

---

## Properties

| Property                                                                           | Type    | Description                                                                                                                  |
| ---------------------------------------------------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
| [`locked`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream/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)`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream/abort)   | 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()`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream/close)         | Closes the stream and runs the `close()` method of the sink. Returns a promise.                                                                                                                                                                                          |
| [`stream.getWriter()`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream/getWriter) | Returns a [WritableStreamDefaultWriter](/en/documentation/devtools/runtime/api-reference/stream-default-writer/) 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:

```javascript
export default {
  async fetch(request, env, ctx) {
    const got = [];
    const stream = new WritableStream(
      {
        write(chunk) {
          got.push(chunk);
        },
      },
      new CountQueuingStrategy({ highWaterMark: 2 }),
    );
    const writer = stream.getWriter();
    const info = {
      locked: stream.locked,
      ctor: writer.constructor.name,
      desiredSize: writer.desiredSize,
    };
    await writer.ready;
    await writer.write('one');
    await writer.write('two');
    await writer.close();
    await writer.closed;
    return Response.json({ ...info, got });
  },
};
```

The function returns these values. The stream is locked because the writer holds it, and `desiredSize` starts at the `highWaterMark` of the queuing strategy:

```json
{
 "locked": true,
 "ctor": "WritableStreamDefaultWriter",
 "desiredSize": 2,
 "got": [
  "one",
  "two"
 ]
}
```

---

## Related resources

- [WritableStreamDefaultWriter](/en/documentation/devtools/runtime/api-reference/stream-default-writer.md): The writer that `getWriter()` locks to a stream, and its methods.
- [ReadableStream](/en/documentation/devtools/runtime/api-reference/readable-stream.md): How to pipe a readable stream into a `WritableStream` with `pipeTo()`.
- [TransformStream](/en/documentation/devtools/runtime/api-reference/transform-stream.md): The stream pair whose writable side is a `WritableStream`.
- [Web APIs](/en/documentation/devtools/runtime/api-reference/javascript.md): The other Web APIs that Azion Runtime supports.
