Intermediate LevelNode JS
Why does Buffer.byteLength() differ from String.length for multi-byte Unicode strings?
❓ Interview Prompt: String.length returns the number of UTF-16 code units. Buffer.byteLength('😀') returns 4 bytes because emojis consume 4 bytes in UTF-8 encoding. Setting HTTP Content-Length to String.length truncates HTTP response payloads!
The Flaw:
'String.length' counts UTF-16 code units (characters). 'Buffer.byteLength()' counts actual binary byte size in a target encoding ('utf8'):
Impact on HTTP Headers:
Setting 'Content-Length' to 'str.length' on multi-byte text (emojis, non-English scripts) truncates response payloads! Always use 'Buffer.byteLength(str)' for 'Content-Length' headers.
Code Implementation Example
javascript
const emojiStr = 'Hello 😀';
console.log('String Length:', emojiStr.length); // 8 (Characters)
console.log('Byte Length:', Buffer.byteLength(emojiStr, 'utf8')); // 10 (Bytes!)
// Correct HTTP Content-Length header:
const contentLength = Buffer.byteLength(emojiStr, 'utf8');💡Comparing String.length with Buffer.byteLength for HTTP headers.
🎯 Interview Key Takeaway
Always use Buffer.byteLength() when computing HTTP Content-Length headers for string payloads.
#Buffer.byteLength#Content-Length#UTF-8#Intermediate
Back to all Node JS Questions→