2024-02-19 05:34:51 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
|
|
// This module is browser compatible.
|
|
|
|
|
|
|
|
import { Buffer } from "./buffer.ts";
|
|
|
|
import { writeAll } from "./write_all.ts";
|
|
|
|
import type { Reader } from "./types.ts";
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a {@linkcode Reader} from a {@linkcode ReadableStreamDefaultReader}.
|
|
|
|
*
|
2024-08-08 14:20:43 +00:00
|
|
|
* @example Usage
|
2024-09-19 23:29:31 +00:00
|
|
|
* ```ts ignore
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { copy } from "@std/io/copy";
|
|
|
|
* import { readerFromStreamReader } from "@std/io/reader-from-stream-reader";
|
2024-02-19 05:34:51 +00:00
|
|
|
*
|
|
|
|
* const res = await fetch("https://deno.land");
|
|
|
|
*
|
|
|
|
* const reader = readerFromStreamReader(res.body!.getReader());
|
2024-08-08 14:20:43 +00:00
|
|
|
* await copy(reader, Deno.stdout);
|
2024-02-19 05:34:51 +00:00
|
|
|
* ```
|
2024-08-08 14:20:43 +00:00
|
|
|
*
|
|
|
|
* @param streamReader The stream reader to read from
|
|
|
|
* @returns The reader
|
2024-02-19 05:34:51 +00:00
|
|
|
*/
|
|
|
|
export function readerFromStreamReader(
|
|
|
|
streamReader: ReadableStreamDefaultReader<Uint8Array>,
|
|
|
|
): Reader {
|
|
|
|
const buffer = new Buffer();
|
|
|
|
|
|
|
|
return {
|
|
|
|
async read(p: Uint8Array): Promise<number | null> {
|
|
|
|
if (buffer.empty()) {
|
|
|
|
const res = await streamReader.read();
|
|
|
|
if (res.done) {
|
|
|
|
return null; // EOF
|
|
|
|
}
|
|
|
|
|
|
|
|
await writeAll(buffer, res.value);
|
|
|
|
}
|
|
|
|
|
|
|
|
return buffer.read(p);
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|