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.
Code
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:bufferis 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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- Does this require external packages?
- No — `node:buffer` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.