UNPKG

1.55 kBJavaScriptView Raw
1import { fromBase64 } from "@aws-sdk/util-base64";
2export const streamCollector = (stream) => {
3 if (typeof Blob === "function" && stream instanceof Blob) {
4 return collectBlob(stream);
5 }
6 return collectStream(stream);
7};
8async function collectBlob(blob) {
9 const base64 = await readToBase64(blob);
10 const arrayBuffer = fromBase64(base64);
11 return new Uint8Array(arrayBuffer);
12}
13async function collectStream(stream) {
14 let res = new Uint8Array(0);
15 const reader = stream.getReader();
16 let isDone = false;
17 while (!isDone) {
18 const { done, value } = await reader.read();
19 if (value) {
20 const prior = res;
21 res = new Uint8Array(prior.length + value.length);
22 res.set(prior);
23 res.set(value, prior.length);
24 }
25 isDone = done;
26 }
27 return res;
28}
29function readToBase64(blob) {
30 return new Promise((resolve, reject) => {
31 const reader = new FileReader();
32 reader.onloadend = () => {
33 if (reader.readyState !== 2) {
34 return reject(new Error("Reader aborted too early"));
35 }
36 const result = (reader.result ?? "");
37 const commaIndex = result.indexOf(",");
38 const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
39 resolve(result.substring(dataOffset));
40 };
41 reader.onabort = () => reject(new Error("Read aborted"));
42 reader.onerror = () => reject(reader.error);
43 reader.readAsDataURL(blob);
44 });
45}