How Big Is a String in Bytes in Node?
A string's length and its size in bytes are not the same number, and confusing them breaks anything that counts bytes: upload limits, Content-Length headers, payload budgets. I measured both with a real run in Node.js 22. Full run in this Short: https://youtu.be/Kc37nb6lQqE
The test
Two strings of a million characters each. The first is a million plain "a" letters. The second is a million accented "e" characters. Both report length 1,000,000.
The numbers
Put them in a Buffer and the sizes split. The plain "a" string: 1,000,000 bytes, one byte per character, exactly what length suggests. The accented "e" string: 2,000,000 bytes, two bytes per character. Same length, double the size.
The reason is encoding. Node counts UTF-16 code units for length, but a Buffer holds UTF-8. Plain ASCII characters take one byte in UTF-8; accented characters take two; emoji take more. Length never tells you which case you are in.
The rule
Never use string length where bytes are meant. If a limit is in bytes - and wire formats, storage quotas and HTTP headers all are - measure the bytes, for example with Buffer.byteLength. Not tested here: emoji and other 4-byte characters, other encodings, and very large strings, each of which widens the gap.
Watch the run
The real terminal output is in the Short: https://youtu.be/Kc37nb6lQqE (narration is AI-generated; the output is from a real run in Node.js 22).
Subscribe to Ship Stack AI on YouTube and tell me in the comments what to build and break next.
About the author
- Real AI-built Node.js projects, tools and workflows. Every experiment is built and load-tested on camera, with the real numbers. Videos: https://www.youtube.com/@ShipStackAI
Comments
Join the discussionNo comments yet. Be the first to comment.