2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-09-13 08:21:52 +00:00
|
|
|
// This module is browser compatible.
|
|
|
|
|
2024-04-29 02:57:30 +00:00
|
|
|
import { concat } from "@std/bytes/concat";
|
2023-09-13 08:21:52 +00:00
|
|
|
|
2023-12-04 06:12:52 +00:00
|
|
|
/**
|
|
|
|
* Converts a {@linkcode ReadableStream} of {@linkcode Uint8Array}s to an
|
2024-05-28 01:27:40 +00:00
|
|
|
* {@linkcode ArrayBuffer}. Works the same as {@linkcode Response.arrayBuffer}.
|
2023-12-04 06:12:52 +00:00
|
|
|
*
|
2024-05-28 01:27:40 +00:00
|
|
|
* @param readableStream A `ReadableStream` of `Uint8Array`s to convert into an `ArrayBuffer`.
|
|
|
|
* @returns A promise that resolves with the `ArrayBuffer` containing all the data from the stream.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2023-12-04 06:12:52 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { toArrayBuffer } from "@std/streams/to-array-buffer";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2023-12-04 06:12:52 +00:00
|
|
|
*
|
|
|
|
* const stream = ReadableStream.from([
|
|
|
|
* new Uint8Array([1, 2]),
|
2024-05-28 01:27:40 +00:00
|
|
|
* new Uint8Array([3, 4, 5]),
|
2023-12-04 06:12:52 +00:00
|
|
|
* ]);
|
2024-05-28 01:27:40 +00:00
|
|
|
* const buf = await toArrayBuffer(stream);
|
|
|
|
* assertEquals(buf.byteLength, 5);
|
2023-12-04 06:12:52 +00:00
|
|
|
* ```
|
|
|
|
*/
|
2023-09-13 08:21:52 +00:00
|
|
|
export async function toArrayBuffer(
|
|
|
|
readableStream: ReadableStream<Uint8Array>,
|
|
|
|
): Promise<ArrayBuffer> {
|
|
|
|
const reader = readableStream.getReader();
|
|
|
|
const chunks: Uint8Array[] = [];
|
|
|
|
|
|
|
|
while (true) {
|
|
|
|
const { done, value } = await reader.read();
|
|
|
|
|
|
|
|
if (done) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
chunks.push(value);
|
|
|
|
}
|
|
|
|
|
2023-11-13 05:34:32 +00:00
|
|
|
return concat(chunks).buffer;
|
2023-09-13 08:21:52 +00:00
|
|
|
}
|