Buffer.byteLength(string[, encoding])
string<string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 用于计算长度的值。encoding<string> 如果string是字符串,则这就是它的编码。 默认值:'utf8'。- 返回: <integer>
string中包含的字节数。
使用 encoding 编码时返回字符串的字节长度。
这与 String.prototype.length 不同,String.prototype.length 不考虑用于将字符串转换为字节的编码。
对于 'base64'、'base64url' 和 'hex',此函数假定输入有效。
对于包含非 base64/hex 编码数据(例如空格)的字符串,返回值可能大于从字符串创建的 Buffer 的长度。
import { Buffer } from 'node:buffer';
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// 打印: ½ + ¼ = ¾: 9 characters, 12 bytesconst { Buffer } = require('node:buffer');
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// 打印: ½ + ¼ = ¾: 9 characters, 12 bytes当 string 为 Buffer/DataView/TypedArray/ArrayBuffer/SharedArrayBuffer 时,返回 .byteLength 报告的字节长度。
string<string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> A value to calculate the length of.encoding<string> Ifstringis a string, this is its encoding. Default:'utf8'.- Returns: <integer> The number of bytes contained within
string.
Returns the byte length of a string when encoded using encoding.
This is not the same as String.prototype.length, which does not account
for the encoding that is used to convert the string into bytes.
For 'base64', 'base64url', 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.
import { Buffer } from 'node:buffer';
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytesconst { Buffer } = require('node:buffer');
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytesWhen string is a Buffer/DataView/TypedArray/ArrayBuffer/
SharedArrayBuffer, the byte length as reported by .byteLength
is returned.