-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.ts
74 lines (68 loc) · 1.85 KB
/
index.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
/**
* @packageDocumentation
*
* Allows treating a browser readable stream as an async iterator.
*
* @example
*
* ```javascript
* import toIt from 'browser-readablestream-to-it'
* import all from 'it-all'
*
* const content = [0, 1, 2, 3, 4]
*
* const stream = new ReadableStream({
* start(controller) {
* for (let i = 0; i < content.length; i++) {
* controller.enqueue(content[i])
* }
*
* controller.close()
* }
* })
*
* const arr = await all(toIt(stream))
*
* console.info(arr) // 0, 1, 2, 3, 4
* ```
*
* ## preventCancel
*
* By default a readable stream will have [.cancel](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/cancel) called on it once it has ended or
* reading has stopped prematurely.
*
* To prevent this behaviour, pass `preventCancel: true` as an option:
*
* ```javascript
* const arr = await all(toIt(stream, { preventCancel: true }))
*
* console.info(arr) // 0, 1, 2, 3, 4
* ```
*/
export interface BrowserReadableStreamToItOptions {
preventCancel?: boolean
}
/**
* Turns a browser readable stream into an async iterable. Async iteration over
* returned iterable will lock give stream, preventing any other consumer from
* acquiring a reader. The lock will be released if iteration loop is broken. To
* prevent stream cancelling optional `{ preventCancel: true }` could be passed
* as a second argument.
*/
export default async function * browserReadableStreamToIt <T> (stream: ReadableStream<T>, options: BrowserReadableStreamToItOptions = {}): AsyncGenerator<T, void, undefined> {
const reader = stream.getReader()
try {
while (true) {
const result = await reader.read()
if (result.done) {
return
}
yield result.value
}
} finally {
if (options.preventCancel !== true) {
await reader.cancel()
}
reader.releaseLock()
}
}