-
Notifications
You must be signed in to change notification settings - Fork 576
/
read_all.ts
61 lines (58 loc) · 1.85 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
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import { Buffer } from "../io/buffer.ts";
import type { Reader, ReaderSync } from "../types.d.ts";
/** Read Reader `r` until EOF (`null`) and resolve to the content as
* Uint8Array`.
*
* ```ts
* import { Buffer } from "https://deno.land/std@$STD_VERSION/io/buffer.ts";
* import { readAll } from "https://deno.land/std@$STD_VERSION/streams/read_all.ts";
*
* // Example from stdin
* const stdinContent = await readAll(Deno.stdin);
*
* // Example from file
* const file = await Deno.open("my_file.txt", {read: true});
* const myFileContent = await readAll(file);
* file.close();
*
* // Example from buffer
* const myData = new Uint8Array(100);
* // ... fill myData array with data
* const reader = new Buffer(myData.buffer);
* const bufferContent = await readAll(reader);
* ```
*/
export async function readAll(r: Reader): Promise<Uint8Array> {
const buf = new Buffer();
await buf.readFrom(r);
return buf.bytes();
}
/** Synchronously reads Reader `r` until EOF (`null`) and returns the content
* as `Uint8Array`.
*
* ```ts
* import { Buffer } from "https://deno.land/std@$STD_VERSION/io/buffer.ts";
* import { readAllSync } from "https://deno.land/std@$STD_VERSION/streams/read_all.ts";
*
* // Example from stdin
* const stdinContent = readAllSync(Deno.stdin);
*
* // Example from file
* const file = Deno.openSync("my_file.txt", {read: true});
* const myFileContent = readAllSync(file);
* file.close();
*
* // Example from buffer
* const myData = new Uint8Array(100);
* // ... fill myData array with data
* const reader = new Buffer(myData.buffer);
* const bufferContent = readAllSync(reader);
* ```
*/
export function readAllSync(r: ReaderSync): Uint8Array {
const buf = new Buffer();
buf.readFromSync(r);
return buf.bytes();
}