QA
Beginner LevelNode JS

Why should you use string_decoder over Buffer.toString() for streaming multi-byte UTF-8 data?

❓ Interview Prompt: Explain `node:string_decoder` module, handling multi-byte UTF-8 character boundaries across stream buffer chunks.

Multi-byte UTF-8 characters (like emojis or non-English scripts) span up to 4 bytes. If a stream chunk cuts a character in half, 'buffer.toString()' corrupts the text!

StringDecoder Solution:

'StringDecoder' buffers incomplete multi-byte characters until the remaining byte chunks arrive, preventing text corruption!

Code Implementation Example

javascript
import { StringDecoder } from 'node:string_decoder';

const decoder = new StringDecoder('utf8');
const chunk1 = Buffer.from([0xf0, 0x9f]); // Half of an emoji byte sequence!
const chunk2 = Buffer.from([0x98, 0x80]); // Second half

console.log(decoder.write(chunk1)); // '' (Buffered, no corruption!)
console.log(decoder.write(chunk2)); // '😀' (Decoded complete emoji!)
💡Decoding multi-byte UTF-8 stream buffers using StringDecoder.
🎯 Interview Key Takeaway

Use StringDecoder when parsing streaming binary buffers to prevent multi-byte character corruption.

#StringDecoder#UTF-8#Buffer#Streams#Beginner
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?