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.

JavascriptData Integrity

Code

snippet
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 : "" "�" fffd

Logic 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

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.