Files and data
Reject invalid UTF-8 instead of replacing bytes
Use TextDecoder with fatal true when invalid UTF-8 should stop an import. The default replacement behavior can hide encoding problems by substituting replacement characters.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const decoder = new TextDecoder("utf-8", {fatal: true});
console.log(decoder.decode(new Uint8Array([0x63, 0x61, 0x66, 0xc3, 0xa9])));
try { decoder.decode(new Uint8Array([0xc3, 0x28])); }
catch (error) { console.log(error.name); }How it works
The first byte sequence encodes café correctly. The second contains an invalid sequence, so strict decoding throws instead of silently changing the text. This is useful when exact identifiers or audit data must not be altered during import.
Limits and mistakes
A successful UTF-8 decode does not prove the file’s intended encoding or schema. When reading a stream, preserve decoder state across chunks and flush it at the end. Do not independently decode arbitrary byte chunks as complete documents.
Check the result
Expect café and TypeError. Compare strict and default decoding on the invalid fixture so the application’s chosen failure policy is visible.
Sources
Reference documentation for the behavior used in this guide: