forked from denoland/std
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread_lines.ts
54 lines (52 loc) · 1.46 KB
/
read_lines.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
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import type { Reader } from "./types.ts";
import { BufReader } from "./buf_reader.ts";
import { concat } from "@std/bytes/concat";
/**
* Read strings line-by-line from a {@linkcode Reader}.
*
* @example Usage
* ```ts
* import { readLines } from "@std/io/read-lines";
* import { assert } from "@std/assert/assert"
*
* let fileReader = await Deno.open("README.md");
*
* for await (let line of readLines(fileReader)) {
* assert(typeof line === "string");
* }
* ```
*
* @param reader The reader to read from
* @param decoderOpts The options
* @returns The async iterator of strings
*
* @deprecated This will be removed in 1.0.0. Use the {@link https://developer.mozilla.org/en-US/docs/Web/API/Streams_API | Web Streams API} instead.
*/
export async function* readLines(
reader: Reader,
decoderOpts?: {
encoding?: string;
fatal?: boolean;
ignoreBOM?: boolean;
},
): AsyncIterableIterator<string> {
const bufReader = new BufReader(reader);
let chunks: Uint8Array[] = [];
const decoder = new TextDecoder(decoderOpts?.encoding, decoderOpts);
while (true) {
const res = await bufReader.readLine();
if (!res) {
if (chunks.length > 0) {
yield decoder.decode(concat(chunks));
}
break;
}
chunks.push(res.line);
if (!res.more) {
yield decoder.decode(concat(chunks));
chunks = [];
}
}
}