TextDecoder: invalid bytes and chunk boundaries
Quick answer
TextDecoder converts encoded bytes into text. Its options determine whether invalid sequences are replaced or rejected and whether decoding continues across chunks.
How it works
Use new TextDecoder("utf-8",{fatal:true}) for strict UTF-8 validation; without fatal, malformed sequences become replacement characters. When a character spans chunks, use the same decoder with {stream:true} on intermediate calls and a final decode() to flush. Decoding does not validate the resulting JSON or business data.
Local examples
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const b=new Uint8Array([255]);const d=new TextDecoder();let err;try{new TextDecoder("utf-8",{fatal:true}).decode(b);}catch(e){err=e.name;}console.log(d.decode(b).codePointAt(0),err);})()Expected console output:
65533 TypeErrorDefault replacement is U+FFFD; strict decoding rejects.
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const d=new TextDecoder();const a=d.decode(new Uint8Array([195]),{stream:true});const b=d.decode(new Uint8Array([169]),{stream:true});console.log(JSON.stringify(a),b+d.decode());})()Expected console output:
"" éThe first chunk is incomplete and the second completes the character.
Common mistakes
Do not create a new decoder for each arbitrary network chunk; a character may span chunks.
Practice
Split a UTF-8 sequence for é between two chunks and compare streaming decoding with independent calls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TextDecoder: invalid bytes and chunk boundaries — Knowledge Check
Apply the concept and reason about local example output.
Which TextDecoder option rejects malformed UTF-8?
Why use the same decoder across chunks?
What should finish a streaming decode sequence?
What is the expected console output of TextDecoder: invalid bytes and chunk boundaries example 1?
(async () => {const b=new Uint8Array([255]);const d=new TextDecoder();let err;try{new TextDecoder("utf-8",{fatal:true}).decode(b);}catch(e){err=e.name;}console.log(d.decode(b).codePointAt(0),err);})()What is the expected console output of TextDecoder: invalid bytes and chunk boundaries example 2?
(async () => {const d=new TextDecoder();const a=d.decode(new Uint8Array([195]),{stream:true});const b=d.decode(new Uint8Array([169]),{stream:true});console.log(JSON.stringify(a),b+d.decode());})()