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.
|
|
|
|
|
|
|
|
const textDecoder = new TextDecoder();
|
|
|
|
|
2023-12-04 06:12:52 +00:00
|
|
|
/**
|
|
|
|
* Converts a {@linkcode ReadableSteam} of strings or {@linkcode Uint8Array}s
|
|
|
|
* to a single string. Works the same as {@linkcode Response.text}.
|
|
|
|
*
|
2024-05-28 01:27:40 +00:00
|
|
|
* @param readableStream A `ReadableStream` to convert into a `string`.
|
|
|
|
* @returns A `Promise` that resolves to the `string`.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2023-12-04 06:12:52 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { toText } from "@std/streams/to-text";
|
2024-05-28 01:27:40 +00:00
|
|
|
* import { assertEquals } from "@std/assert/assert-equals";
|
2023-12-04 06:12:52 +00:00
|
|
|
*
|
|
|
|
* const stream = ReadableStream.from(["Hello, ", "world!"]);
|
2024-05-28 01:27:40 +00:00
|
|
|
* assertEquals(await toText(stream), "Hello, world!");
|
2023-12-04 06:12:52 +00:00
|
|
|
* ```
|
|
|
|
*/
|
2023-09-13 08:21:52 +00:00
|
|
|
export async function toText(
|
|
|
|
readableStream: ReadableStream,
|
|
|
|
): Promise<string> {
|
|
|
|
const reader = readableStream.getReader();
|
|
|
|
let result = "";
|
|
|
|
|
|
|
|
while (true) {
|
|
|
|
const { done, value } = await reader.read();
|
|
|
|
|
|
|
|
if (done) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
result += typeof value === "string" ? value : textDecoder.decode(value);
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|