-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrackStream.js
87 lines (75 loc) · 1.65 KB
/
trackStream.js
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
77
78
79
80
81
82
83
84
85
86
87
export const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (!chunkSize || len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
}
export const readBytes = async function* (iterable, chunkSize) {
for await (const chunk of readStream(iterable)) {
yield* streamChunk(chunk, chunkSize);
}
}
const readStream = async function* (stream) {
if (stream[Symbol.asyncIterator]) {
yield* stream;
return;
}
const reader = stream.getReader();
try {
for (;;) {
const {done, value} = await reader.read();
if (done) {
break;
}
yield value;
}
} finally {
await reader.cancel();
}
}
export const trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator = readBytes(stream, chunkSize);
let bytes = 0;
let done;
let _onFinish = (e) => {
if (!done) {
done = true;
onFinish && onFinish(e);
}
}
return new ReadableStream({
async pull(controller) {
try {
const {done, value} = await iterator.next();
if (done) {
_onFinish();
controller.close();
return;
}
let len = value.byteLength;
if (onProgress) {
let loadedBytes = bytes += len;
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
} catch (err) {
_onFinish(err);
throw err;
}
},
cancel(reason) {
_onFinish(reason);
return iterator.return();
}
}, {
highWaterMark: 2
})
}