Stream to Text (ReadableStream -> string)

intermediate
By FrontendAtlas Editorial · Updated Oct 15, 2026
Implement streamToText(stream, options) that reads a ReadableStream<Uint8Array> and returns the full string. Use TextDecoder with stream=true to handle multi-byte characters across chunk boundaries. Optionally support AbortSignal to cancel reading. Concepts: Streams API, TextDecoder, async iteration.

Arguments

  • stream: ReadableStream<Uint8Array> — A stream of byte chunks (e.g., from fetch(...).body).
  • options: { encoding?: string, signal?: AbortSignal } — Optional text encoding and AbortSignal for cancellation.

Returns

Promise<string> — Resolves to the decoded text, or rejects on abort.

Solution idea

Get a reader, then put signal setup—including the already-aborted path—and the read loop inside one try/finally. Decode chunks with TextDecoder using { stream: true } so multi-byte characters are not split, flush at the end, and cancel on abort. The finally block always removes the abort listener and releases the reader lock on success, failure, or cancellation.

Examples
const res = await fetch('/api/logs');
const text = await streamToText(res.body);

const ac = new AbortController();
const p = streamToText(stream, { signal: ac.signal });
ac.abort();

Public interview reports

These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.

Reported in a public Intuit interview account. Intuit frontend interview questions