← Back to Node.js, page 6

nodejs-0107 · Easy fresher

What encoding mistakes happen with Buffers and strings (utf8, hex, base64, binary data), and how do you avoid them?

String length counts UTF-16 units, Buffer length counts bytes, so they differ for non-ASCII text. Invalid utf8 bytes become the replacement character, which makes binary data in utf8 strings lossy. Hex strings with an odd length or bad characters are silently cut. Use base64, base64url or hex for binary data in text, and Buffer.byteLength when you need a byte count.

Full answer

Common traps and the safe habit for each:

  • Length: 'cafe\u0301'.length counts UTF-16 code units. Buffer.byteLength(text) counts bytes in an encoding. Use bytes for Content-Length, size limits and storage.
  • Invalid bytes: Buffer.from([0xff]).toString('utf8') does not throw. It returns the replacement character (U+FFFD), and the original byte is gone. Never turn binary data (images, encrypted bytes, hashes) into a utf8 string. Keep it as a Buffer, or encode it with base64 or hex.
  • Cut characters: slicing a Buffer in the middle of a multi-byte character, or decoding streamed chunks one by one, produces broken text. Decode after joining chunks, or with StringDecoder.
  • Hex and base64 parsing are forgiving. Buffer.from('abc', 'hex') returns one byte (the odd digit is dropped), and bad characters stop the parsing. Validate the input with a regular expression before decoding.
  • base64 vs base64url: base64 uses + and / and padding with =. URLs and JWTs use base64url (- and _, no padding). Node supports 'base64url'.
  • latin1 (binary) maps one byte to one character 0 to 255. It is lossless for bytes but wrong for text.
  • Emoji and other characters outside the basic plane use 4 bytes in utf8 and two UTF-16 units.

Rules: pick an encoding on purpose, specify it on every conversion, and treat text and bytes as separate types.

javascript
const text = 'caf\u00e9 \u20ac \ud83d\ude00';
console.log('string length:', text.length, '| utf8 bytes:', Buffer.byteLength(text, 'utf8'), '| utf16le bytes:', Buffer.byteLength(text, 'utf16le'));

// Binary data does not survive a trip through a utf8 string.
const binary = Buffer.from([0xff, 0xd8, 0x41, 0x80]);
const viaUtf8 = Buffer.from(binary.toString('utf8'), 'utf8');
console.log('binary as hex       :', binary.toString('hex'));
console.log('after utf8 roundtrip:', viaUtf8.toString('hex'), '| equal:', binary.equals(viaUtf8));
console.log('after base64        :', Buffer.from(binary.toString('base64'), 'base64').equals(binary));

// Cutting a multi-byte character.
const euro = Buffer.from('\u20ac'); // 3 bytes
console.log('euro bytes:', euro.length, '| first two bytes decode to', JSON.stringify(euro.subarray(0, 2).toString()));

// Forgiving decoders.
console.log("Buffer.from('abc', 'hex') length:", Buffer.from('abc', 'hex').length);
console.log("Buffer.from('zz12', 'hex') length:", Buffer.from('zz12', 'hex').length);
const isHex = (s) => /^([0-9a-f]{2})+$/i.test(s);
console.log('strict hex check:', isHex('abc'), isHex('abcd'));

// base64 and base64url
const token = Buffer.from([0xfb, 0xff, 0xfe]);
console.log('base64   :', token.toString('base64'));
console.log('base64url:', token.toString('base64url'));

// latin1 keeps bytes but is not text
console.log('latin1 roundtrip equal:', Buffer.from(binary.toString('latin1'), 'latin1').equals(binary));

Every line prints a fact: lengths, a lossy round trip, cut characters and decoders that do not complain. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): string length: 9 | utf8 bytes: 14 | utf16le bytes: 18 binary as hex : ffd84180 after utf8 roundtrip: efbfbdefbfbd41efbfbd | equal: false after base64 : true euro bytes: 3 | first two bytes decode to "�" Buffer.from('abc', 'hex') length: 1 Buffer.from('zz12', 'hex') length: 0 strict hex check: false true base64 : +//+ base64url: -__- latin1 roundtrip equal: true

Key points

  • String length is not byte length.
  • Invalid utf8 becomes U+FFFD, so binary data is lost in a utf8 string.
  • Hex and base64 decoding silently drop bad input.
  • Use base64url for URLs and tokens.
  • Decode streamed chunks with StringDecoder.

Common mistakes

  • Using string length to check a byte limit.
  • Reading an image into a utf8 string.
  • Sending base64 in a URL without switching to base64url.
  • Trusting Buffer.from(input, 'hex') to throw on bad input.
  • Decoding each streamed chunk separately.

Follow-ups

  • Why can a hash digest not be stored as a utf8 string?
  • How do you check that a string is valid base64?
  • What does TextDecoder with fatal: true do?

Tips

  • Open with 'characters are not bytes'.
  • Give the utf8 roundtrip as the strongest example.
  • Mention base64url for tokens.