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.
Code
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:fsis 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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.