Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

TextEncoderStream — streaming UTF-8 encoding

TextEncoderStream transforms text chunks into UTF-8 bytes while preserving surrogate pairs split across chunks.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

new TextEncoderStream()
encoder.encoding
encoder.writable
encoder.readable
textReadable.pipeThrough(new TextEncoderStream())

TextEncoderStream is a WHATWG Encoding Web API, not an ECMAScript feature. Its constructor takes no encoding options; encoding always returns "utf-8".

writable accepts text; readable provides Uint8Array chunks. Connect a source using pipeThrough(). Unlike separate TextEncoder.encode() calls, the stream preserves a surrogate pair split across chunks. Unpaired surrogates become U+FFFD; a final leading surrogate waits until input closes.

The example collects bytes without assuming matching chunk boundaries. Check API availability in the target browser; Node 24 in the repository does not establish browser support.

Examples

(async () => {
  if (typeof TextEncoderStream === "undefined") {
    throw new Error("TextEncoderStream unavailable");
  }

  const source = new ReadableStream({
    start(controller) {
      controller.enqueue("A\uD83D");
      controller.enqueue("\uDE00");
      controller.close();
    }
  });

  const encoder = new TextEncoderStream();
  const reader = source.pipeThrough(encoder).getReader();
  const bytes = [];
  try {
    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      bytes.push(...value);
    }
  } finally {
    reader.releaseLock();
  }

  console.log(encoder.encoding);
  console.log(bytes.join(","));
})().catch(console.error);

Result

utf-8
65,240,159,152,128

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources