|
| 1 | +// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. |
| 2 | +// This module is browser compatible. |
| 3 | + |
| 4 | +import { DEFAULT_CHUNK_SIZE } from "./_constants.ts"; |
| 5 | +import { isCloser } from "./_common.ts"; |
| 6 | +import type { Closer, Reader } from "./types.ts"; |
| 7 | + |
| 8 | +/** Options for {@linkcode toReadableStream}. */ |
| 9 | +export interface ToReadableStreamOptions { |
| 10 | + /** If the `reader` is also a `Closer`, automatically close the `reader` |
| 11 | + * when `EOF` is encountered, or a read error occurs. |
| 12 | + * |
| 13 | + * @default {true} |
| 14 | + */ |
| 15 | + autoClose?: boolean; |
| 16 | + |
| 17 | + /** The size of chunks to allocate to read, the default is ~16KiB, which is |
| 18 | + * the maximum size that Deno operations can currently support. */ |
| 19 | + chunkSize?: number; |
| 20 | + |
| 21 | + /** The queuing strategy to create the `ReadableStream` with. */ |
| 22 | + strategy?: QueuingStrategy<Uint8Array>; |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Create a {@linkcode ReadableStream} of {@linkcode Uint8Array}s from a |
| 27 | + * {@linkcode Reader}. |
| 28 | + * |
| 29 | + * When the pull algorithm is called on the stream, a chunk from the reader |
| 30 | + * will be read. When `null` is returned from the reader, the stream will be |
| 31 | + * closed along with the reader (if it is also a `Closer`). |
| 32 | + * |
| 33 | + * @example |
| 34 | + * ```ts |
| 35 | + * import { toReadableStream } from "https://deno.land/std@$STD_VERSION/io/to_readable_stream.ts"; |
| 36 | + * |
| 37 | + * const file = await Deno.open("./file.txt", { read: true }); |
| 38 | + * const fileStream = toReadableStream(file); |
| 39 | + * ``` |
| 40 | + */ |
| 41 | +export function toReadableStream( |
| 42 | + reader: Reader | (Reader & Closer), |
| 43 | + { |
| 44 | + autoClose = true, |
| 45 | + chunkSize = DEFAULT_CHUNK_SIZE, |
| 46 | + strategy, |
| 47 | + }: ToReadableStreamOptions = {}, |
| 48 | +): ReadableStream<Uint8Array> { |
| 49 | + return new ReadableStream({ |
| 50 | + async pull(controller) { |
| 51 | + const chunk = new Uint8Array(chunkSize); |
| 52 | + try { |
| 53 | + const read = await reader.read(chunk); |
| 54 | + if (read === null) { |
| 55 | + if (isCloser(reader) && autoClose) { |
| 56 | + reader.close(); |
| 57 | + } |
| 58 | + controller.close(); |
| 59 | + return; |
| 60 | + } |
| 61 | + controller.enqueue(chunk.subarray(0, read)); |
| 62 | + } catch (e) { |
| 63 | + controller.error(e); |
| 64 | + if (isCloser(reader)) { |
| 65 | + reader.close(); |
| 66 | + } |
| 67 | + } |
| 68 | + }, |
| 69 | + cancel() { |
| 70 | + if (isCloser(reader) && autoClose) { |
| 71 | + reader.close(); |
| 72 | + } |
| 73 | + }, |
| 74 | + }, strategy); |
| 75 | +} |
0 commit comments