Node.js

Measure UTF-8 text in bytes with Buffer

Use Buffer.byteLength when a Node.js limit is expressed in encoded bytes. JavaScript string length counts UTF-16 code units and is not a reliable UTF-8 byte count.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const text = "café";
console.log(text.length);
console.log(Buffer.byteLength(text, "utf8"));
console.log(Buffer.from(text, "utf8").length);

How it works

The final letter occupies two bytes in UTF-8, so the text has four code units but five encoded bytes. ByteLength measures that size without requiring your code to retain a new Buffer solely to count its length.

Limits and mistakes

Use the encoding that the destination actually expects. Byte count is not visual width, grapheme count, or compressed size. For files that already exist, filesystem metadata reports stored bytes without re-encoding their contents.

Check the result

Expect 4, 5, 5. Add an emoji and compare all three measurements to make the distinction between text units and encoded bytes visible.

Sources

Reference documentation for the behavior used in this guide: