All files / io / to_writable_stream.ts

66.67% Branches 2/3
79.31% Lines 23/29
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
 
 
 
x2
 
x2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x2
x2
 
x7
 
x7
x7
x19
x19
 
 
 
 
 
 
x7
x7
x9
x10
x10
x7
x7
x8
x8
x8
x8
x7
x7










































I

















// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

import { writeAll } from "./write_all.ts";
import type { Writer } from "./types.ts";
import { isCloser } from "./_common.ts";

/** Options for {@linkcode toWritableStream}. */
// deno-lint-ignore deno-style-guide/naming-convention
export interface toWritableStreamOptions {
  /**
   * If the `writer` is also a `Closer`, automatically close the `writer`
   * when the stream is closed, aborted, or a write error occurs.
   *
   * @default {true}
   */
  autoClose?: boolean;
}

/**
 * Create a {@linkcode WritableStream} from a {@linkcode Writer}.
 *
 * @example Usage
 * ```ts no-assert
 * import { toWritableStream } from "@std/io/to-writable-stream";
 *
 * const a = toWritableStream(Deno.stdout); // Same as `Deno.stdout.writable`
 * ```
 *
 * @param writer The writer to write to
 * @param options The options
 * @returns The writable stream
 */
export function toWritableStream(
  writer: Writer,
  options?: toWritableStreamOptions,
): WritableStream<Uint8Array> {
  const { autoClose = true } = options ?? {};

  return new WritableStream({
    async write(chunk, controller) {
      try {
        await writeAll(writer, chunk);
      } catch (e) {
        controller.error(e);
        if (isCloser(writer) && autoClose) {
          writer.close();
        }
      }
    },
    close() {
      if (isCloser(writer) && autoClose) {
        writer.close();
      }
    },
    abort() {
      if (isCloser(writer) && autoClose) {
        writer.close();
      }
    },
  });
}