静态方法:Buffer.stringLength(input[, encoding])
🌐 Static method: Buffer.stringLength(input[, encoding])
input<Buffer> | <ArrayBuffer> | <TypedArray> 将被解码的字节。encoding<string> 字符编码input会被解码为。默认:'utf8'。- 返回:<integer>
返回字符串的长度(以 UTF-16 代码单元为单位),这是 buf.toString(encoding) 对相同字节产生的结果,而不对它们进行解码。这是 Buffer.byteLength() 的对应操作,Buffer.byteLength() 返回字符串编码后的字节数。
🌐 Returns the length, in UTF-16 code units, of the string that
buf.toString(encoding) would produce for the same bytes, without decoding
them. This is the counterpart of Buffer.byteLength(), which returns the
number of bytes a string would encode to.
对于 'utf8',无效的字节序列会按解码方式进行计数:每个最长的无效子序列会变成一个 U+FFFD 替换字符。对于其他所有编码,结果只根据 input.byteLength 来计算。
🌐 For 'utf8', invalid byte sequences are counted as they would be decoded:
each maximal invalid subsequence becomes one U+FFFD replacement character.
For every other encoding the result is computed from input.byteLength alone.
一个分离的ArrayBuffer,或一个由它支持的TypedArray,被视为空的。
🌐 A detached ArrayBuffer, or a TypedArray backed by one, is treated as empty.
结果没有上限:在解码之前,将其与 buffer.constants.MAX_STRING_LENGTH 比较,以了解解码是否能成功。一个由 n 代码单元组成的字符串占用的内存在 n 到 2 * n 字节之间。
🌐 The result is not capped: compare it with
buffer.constants.MAX_STRING_LENGTH before decoding to know whether the
decode can succeed at all. A string of n code units occupies between n and
2 * n bytes of memory.
import { Buffer, constants } from 'node:buffer';
const buf = Buffer.from('€ 100', 'utf8');
console.log(Buffer.stringLength(buf));
// Prints: 5
console.log(Buffer.stringLength(buf, 'hex'));
// Prints: 14
console.log(Buffer.stringLength(buf) <= constants.MAX_STRING_LENGTH);
// Prints: trueconst { Buffer, constants } = require('node:buffer');
const buf = Buffer.from('€ 100', 'utf8');
console.log(Buffer.stringLength(buf));
// Prints: 5
console.log(Buffer.stringLength(buf, 'hex'));
// Prints: 14
console.log(Buffer.stringLength(buf) <= constants.MAX_STRING_LENGTH);
// Prints: true