TextDecoder Streams Chunked Bytes Into Text

Decode byte chunks with streaming: true so multi-byte characters split across reads survive, and final flush drops nothing at the boundary.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
import fs from 'node:fs';

// Write UTF-8 bytes first, then read them back in fixed-size chunks.
fs.writeFileSync('notes.txt', Buffer.from('naive café résumé', 'utf8'));
const bytes = fs.readFileSync('notes.txt');

const decoder = new TextDecoder('utf-8');
let text = '';

// 4-byte chunks cut inside multi-byte characters on purpose.
for (let i = 0; i < bytes.length; i += 4) {
  const chunk = bytes.subarray(i, i + 4);
  // streaming: true keeps partial sequences pending until more bytes arrive
  text += decoder.decode(chunk, { stream: true });
}
text += decoder.decode(); // flush: emits whatever was still pending

console.log('round trip intact:', text === 'naive café résumé');
console.log(text);

process.on('exit', () => fs.rmSync('notes.txt', { force: true }));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

round trip intact: true
naive café résumé

What the code does

Iteration happens inside for (let i = 0; i < bytes.length; i += 4) — everything outside it runs once.

Top-level bindings bytes, decoder, text hold the demo state — nothing sits inside a function scope.

What to watch for

  • node:fs is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Using it

Output lines are prefixed (round trip intact:), making each step’s effect easy to spot.

Key statements

text += decoder.decode(); // flush: emits whatever was still pending
console.log('round trip intact:', text === 'naive café résumé');
process.on('exit', () => fs.rmSync('notes.txt', { force: true }));
text += decoder.decode(chunk, { stream: true });

Interactive Tools for This Topic

FAQ

What does this import from outside the project?
Only `node:fs`, and that is a Node.js built-in — it comes with the runtime.