mirror of
https://github.com/denoland/deno
synced 2024-10-30 02:21:11 +00:00
Improve bufferFromStream (#5826)
This commit is contained in:
parent
fbbb9f1c36
commit
c9f0e34e29
1 changed files with 21 additions and 28 deletions
|
@ -59,36 +59,29 @@ function concatenate(...arrays: Uint8Array[]): ArrayBuffer {
|
||||||
return result.buffer as ArrayBuffer;
|
return result.buffer as ArrayBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
function bufferFromStream(stream: ReadableStreamReader): Promise<ArrayBuffer> {
|
async function bufferFromStream(
|
||||||
return new Promise((resolve, reject): void => {
|
stream: ReadableStreamReader
|
||||||
const parts: Uint8Array[] = [];
|
): Promise<ArrayBuffer> {
|
||||||
const encoder = new TextEncoder();
|
const parts: Uint8Array[] = [];
|
||||||
// recurse
|
const encoder = new TextEncoder();
|
||||||
(function pump(): void {
|
|
||||||
stream
|
|
||||||
.read()
|
|
||||||
.then(({ done, value }): void => {
|
|
||||||
if (done) {
|
|
||||||
return resolve(concatenate(...parts));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof value === "string") {
|
while (true) {
|
||||||
parts.push(encoder.encode(value));
|
const { done, value } = await stream.read();
|
||||||
} else if (value instanceof ArrayBuffer) {
|
|
||||||
parts.push(new Uint8Array(value));
|
|
||||||
} else if (!value) {
|
|
||||||
// noop for undefined
|
|
||||||
} else {
|
|
||||||
reject("unhandled type on stream read");
|
|
||||||
}
|
|
||||||
|
|
||||||
return pump();
|
if (done) break;
|
||||||
})
|
|
||||||
.catch((err): void => {
|
if (typeof value === "string") {
|
||||||
reject(err);
|
parts.push(encoder.encode(value));
|
||||||
});
|
} else if (value instanceof ArrayBuffer) {
|
||||||
})();
|
parts.push(new Uint8Array(value));
|
||||||
});
|
} else if (!value) {
|
||||||
|
// noop for undefined
|
||||||
|
} else {
|
||||||
|
throw new Error("unhandled type on stream read");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return concatenate(...parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const BodyUsedError =
|
export const BodyUsedError =
|
||||||
|
|
Loading…
Reference in a new issue