StringDecoder Reassembles Split UTF-8 Byte Chunks
Decode multi-byte UTF-8 payloads split mid-character across Node chunks with StringDecoder.write and flush incomplete tails via StringDecoder.end.
Code
import { Buffer } from 'node:buffer';
import { StringDecoder } from 'node:string_decoder';
const payload = Buffer.from('price: €12 🚀', 'utf8');
// Split right in the middle of the 3-byte € sign and 4-byte 🚀 emoji
const chunks = [payload.subarray(0, 8), payload.subarray(8, 13), payload.subarray(13)];
const naive = chunks.map((c) => c.toString('utf8')).join('');
console.log('naive join :', naive);
const decoder = new StringDecoder('utf8');
let assembled = '';
for (const chunk of chunks) {
assembled += decoder.write(chunk);
}
assembled += decoder.end();
console.log('decoder join :', assembled);
// A trailing incomplete multi-byte sequence is flushed as U+FFFD on .end()
const partial = new StringDecoder('utf8');
const head = partial.write(Buffer.from([0xe2, 0x82]));
const tail = partial.end();
console.log('flushed tail :', JSON.stringify(head), JSON.stringify(tail), tail.codePointAt(0).toString(16));Output
Captured from a sandboxed run of this snippet in the build pipeline.
naive join : price: ���12 🚀
decoder join : price: €12 🚀
flushed tail : "" "�" fffdLogic trace — StringDecoder Reassembles Split UTF-8 Byte Chunks
Repetition is confined to for (const chunk of chunks) — the rest of the file is straight-line. The only import source is node:buffer, node:string_decoder, a Node.js built-in, exposing Buffer, StringDecoder.
Top-level bindings payload, chunks, naive, decoder hold the demo state — nothing sits inside a function scope.
What to watch for
- The dependency surface is just
node:buffer, and that one is built into Node.js.
Applying it
Execution logs formatted markers — naive join :, decoder join :, flushed tail : — when the file runs.
Statements that matter
const naive = chunks.map((c) => c.toString('utf8')).join('');
assembled += decoder.write(chunk);
assembled += decoder.end();
Interactive Tools for This Topic
Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Is the imported module an npm package?
- No — `node:buffer` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.
Report a problem with this exampleOpens a pre-filled issue on GitHub.