Decoding Stream Chunks
You'll learn how to convert raw binary stream chunks into readable text using TextDecoder.
When you read from a ReadableStream, each chunk arrives as a Uint8Array—a raw array of bytes. These bytes represent text, but they're not yet in a format JavaScript strings can work with directly. Think of it like receiving a letter written in code: you need a decoder to translate those numeric values back into readable characters.
This is especially important for streaming text responses like server-sent events, real-time logs, or progressive API responses where you need to process text as it arrives, chunk by chunk.
Creating a TextDecoder
The TextDecoder API converts byte arrays into strings:
const decoder = new TextDecoder();
By default, it decodes UTF-8 encoded text (the web standard). You typically create one decoder instance and reuse it for all chunks in a stream.
Decoding Chunks in Your Read Loop
Combine TextDecoder with your streaming read loop:
const response = await fetch('https://api.example.com/stream');
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
// value is a Uint8Array, decode it to a string
const textChunk = decoder.decode(value, { stream: true });
console.log(textChunk); // Now you have readable text!
}
Notice the { stream: true } option—this tells the decoder that more chunks might follow, so it can handle multi-byte characters that might be split across chunk boundaries.
Key Takeaway: Use TextDecoder to convert Uint8Array chunks from streams into readable JavaScript strings, enabling you to process streaming text data piece by piece with the { stream: true } option to handle characters split across chunks.