Buffer.byteLength(string[, encoding])


返回字符串的实际字节长度。 与 String.prototype.length 不同,后者返回字符串的字符数。

const str = '\u00bd + \u00bc = \u00be';

console.log(`${str}: ${str.length} 个字符, ` +
            `${Buffer.byteLength(str, 'utf8')} 个字节`);
// 打印: ½ + ¼ = ¾: 9 个字符, 12 个字节

Returns the actual byte length of a string. This is not the same as String.prototype.length since that returns the number of characters in a string.

For 'base64' and 'hex', this function assumes valid input. For strings that contain non-Base64/Hex-encoded data (e.g. whitespace), the return value might be greater than the length of a Buffer created from the string.

const str = '\u00bd + \u00bc = \u00be';

console.log(`${str}: ${str.length} characters, ` +
            `${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes

When string is a Buffer/DataView/TypedArray/ArrayBuffer/ SharedArrayBuffer, the actual byte length is returned.