Buffer.byteLength Counts UTF-8 Bytes

Measure the wire size of strings and buffers with Buffer.byteLength, because .length counts UTF-16 code units and diverges for CJK and emoji.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
import { Buffer } from 'node:buffer';

const samples = ['hello', '仓库管理系统', 'café', '👍'];

for (const s of samples) {
  const utf8 = Buffer.byteLength(s, 'utf8');
  const utf16 = s.length; // code units, not bytes
  console.log(JSON.stringify(s), 'utf8:', utf8, 'length:', utf16);
}

// Buffer.byteLength accepts Buffer inputs too — same number as utf8.
const buf = Buffer.from('仓库管理系统', 'utf8');
console.log('buffer:', Buffer.byteLength(buf), 'buffer.length:', buf.length);

// Frames and protocols size in bytes, so UTF-16 length lies to them.
const budget = 40;
const title = '发布清单 2026';
const wire = Buffer.byteLength(title, 'utf8');
console.log('fits budget:', wire <= budget, '(', wire, 'bytes )');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

"hello" utf8: 5 length: 5
"仓库管理系统" utf8: 18 length: 6
"café" utf8: 5 length: 4
"👍" utf8: 4 length: 2
buffer: 18 buffer.length: 18
fits budget: true ( 17 bytes )

How it works

One loop does the cycling here: for (const s of samples). The only import source is node:buffer, a Node.js built-in, exposing Buffer.

Top-level bindings samples, buf, budget, title hold the demo state — nothing sits inside a function scope.

What to watch for

  • node:buffer is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Applying it

The run prints buffer:, fits budget: — each prefix names the step that produced it.

Statements that matter

const samples = ['hello', '仓库管理系统', 'café', '👍'];
const utf16 = s.length; // code units, not bytes
console.log(JSON.stringify(s), 'utf8:', utf8, 'length:', utf16);
const wire = Buffer.byteLength(title, 'utf8');

Interactive Tools for This Topic

FAQ

Does this require external packages?
No — `node:buffer` is a Node.js built-in module; nothing to install.