-
Notifications
You must be signed in to change notification settings - Fork 644
/
Copy pathread_all.ts
76 lines (73 loc) · 1.98 KB
/
read_all.ts
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.
import { concat } from "@std/bytes/concat";
import { DEFAULT_CHUNK_SIZE } from "./_constants.ts";
import type { Reader, ReaderSync } from "./types.ts";
/**
* Read {@linkcode Reader} `r` until EOF (`null`) and resolve to the content as
* {@linkcode Uint8Array}.
*
* @example Usage
* ```ts ignore
* import { readAll } from "@std/io/read-all";
*
* // Example from stdin
* const stdinContent = await readAll(Deno.stdin);
*
* // Example from file
* using file = await Deno.open("my_file.txt", {read: true});
* const myFileContent = await readAll(file);
* ```
*
* @param reader The reader to read from
* @returns The content as Uint8Array
*/
export async function readAll(reader: Reader): Promise<Uint8Array> {
const chunks: Uint8Array[] = [];
while (true) {
let chunk = new Uint8Array(DEFAULT_CHUNK_SIZE);
const n = await reader.read(chunk);
if (n === null) {
break;
}
if (n < DEFAULT_CHUNK_SIZE) {
chunk = chunk.subarray(0, n);
}
chunks.push(chunk);
}
return concat(chunks);
}
/**
* Synchronously reads {@linkcode ReaderSync} `r` until EOF (`null`) and returns
* the content as {@linkcode Uint8Array}.
*
* @example Usage
* ```ts ignore
* import { readAllSync } from "@std/io/read-all";
*
* // Example from stdin
* const stdinContent = readAllSync(Deno.stdin);
*
* // Example from file
* using file = Deno.openSync("my_file.txt", {read: true});
* const myFileContent = readAllSync(file);
* ```
*
* @param reader The reader to read from
* @returns The content as Uint8Array
*/
export function readAllSync(reader: ReaderSync): Uint8Array {
const chunks: Uint8Array[] = [];
while (true) {
let chunk = new Uint8Array(DEFAULT_CHUNK_SIZE);
const n = reader.readSync(chunk);
if (n === null) {
break;
}
if (n < DEFAULT_CHUNK_SIZE) {
chunk = chunk.subarray(0, n);
}
chunks.push(chunk);
}
return concat(chunks);
}