Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

WritableStream sink: start, write, close, and abort

Four optional sink callbacks define how a writable stream initializes its destination, writes chunks, finalizes successful output, or cleans up after an abort.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

new WritableStream()
new WritableStream(underlyingSink)
new WritableStream(underlyingSink, queuingStrategy)

// Optional methods on underlyingSink:
const underlyingSink = {
  start(controller) { /* initialize the destination */ },
  write(chunk, controller) { /* write one chunk */ },
  close() { /* finalize successful output */ },
  abort(reason) { /* clean up after an abort request */ },
};

WritableStream belongs to the Web Streams API, not ECMAScript 2024; availability depends on the runtime. The phrase “WritableStream underlying sink start/write/close/abort” refers to four optional callbacks on underlyingSink, the constructor’s first optional argument. The second optional argument, queuingStrategy, defines how queue size is measured for backpressure.

start(controller) runs once during construction. A synchronous throw makes construction fail; a rejected promise errors the constructed stream. The stream waits for successful initialization before delivering chunks to the sink. write(chunk, controller) handles one chunk at a time, in submission order. Return a promise for the actual asynchronous write so the stream can wait for it and propagate failures.

close() takes no arguments. After a close request, it runs only once all accepted writes have succeeded. Use it to flush sink buffers and release resources. abort(reason) handles cleanup after an abort request; the reason can be any JavaScript value. Writes that have not started are rejected, but an in-flight operation is not automatically stopped, and completed writes are not rolled back. Both callbacks can return promises; do not assume abort runs on every error or after closure.

start and write receive the same WritableStreamDefaultController. controller.signal lets in-flight work respond to an abort request if the operation supports cancellation. controller.error(error) reports a stream failure; it is not an abort request and does not replace cleanup.

Producer code calls getWriter(), which locks the stream to one writer. Handle the promises from writer.write(), writer.close(), and writer.abort(); direct stream.close() and stream.abort() calls reject while the stream is locked. writer.releaseLock() unlocks the stream without ending it.

Examples

(async () => {
  const log = [];
  const reason = new Error("stop");

  async function run(label, shouldAbort) {
    const stream = new WritableStream({
      start() {
        log.push(`${label}: start`);
      },
      async write(chunk) {
        await Promise.resolve();
        log.push(`${label}: write ${chunk}`);
      },
      close() {
        log.push(`${label}: close`);
      },
      abort(received) {
        log.push(`${label}: abort (${received === reason})`);
      },
    });

    const writer = stream.getWriter();
    try {
      await writer.write("A");
      if (shouldAbort) {
        await writer.abort(reason);
      } else {
        await writer.close();
      }
    } finally {
      writer.releaseLock();
    }
  }

  await run("normal", false);
  await run("interrupted", true);
  console.log(log.join("\n"));
})().catch(console.error);

Result

normal: start
normal: write A
normal: close
interrupted: start
interrupted: write A
interrupted: abort (true)

The example uses two separate streams. Both finish writing `A`; the first closes and the second aborts. `true` shows that the sink received the exact same `Error` object.

Related lessons

  • JavaScript · Lesson 4 · Advanced · Version: 4

Sources