forked from JakeChampion/fetch
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathutils.js
54 lines (44 loc) · 1.27 KB
/
utils.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
function createBlobReader(blob) {
const reader = new FileReader();
const fileReaderReady = new Promise((resolve, reject) => {
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = function () {
reject(reader.error);
};
});
return {
readAsArrayBuffer: async () => {
reader.readAsArrayBuffer(blob);
return fileReaderReady;
},
readAsText: async () => {
reader.readAsText(blob);
return fileReaderReady;
},
};
}
async function drainStream(stream) {
const chunks = [];
const reader = stream.getReader();
function readNextChunk() {
return reader.read().then(({ done, value }) => {
if (done) {
return chunks.reduce(
(bytes, chunk) => [...bytes, ...chunk],
[]
);
}
chunks.push(value);
return readNextChunk();
});
}
const bytes = await readNextChunk();
return new Uint8Array(bytes);
}
function readArrayBufferAsText(array) {
const decoder = new TextDecoder();
return decoder.decode(array);
}
export { createBlobReader, drainStream, readArrayBufferAsText };