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