buf.toString([encoding[, start[, end]]])


  • encoding <string> 使用的字符编码。默认值: 'utf8'
  • start <integer> 开始解码的字节偏移量。默认值: 0
  • end <integer> 停止解码的字节偏移量(不包括该位置)。默认值: buf.length
  • 返回值: <string>

根据指定的字符编码 encodingbuf 解码为字符串。可以传入 startend 只解码 buf 的一部分。

【Decodes buf to a string according to the specified character encoding in encoding. start and end may be passed to decode only a subset of buf.】

如果 encoding'utf8',且输入中的字节序列不是有效的 UTF-8,则每个无效字节都会被替换为替代字符 U+FFFD

【If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8, then each invalid byte is replaced with the replacement character U+FFFD.】

字符串实例的最大长度(以 UTF-16 代码单元计)可通过 buffer.constants.MAX_STRING_LENGTH 获得。

【The maximum length of a string instance (in UTF-16 code units) is available as buffer.constants.MAX_STRING_LENGTH.】

import { Buffer } from 'node:buffer';

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde

const buf2 = Buffer.from('tést');

console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: téconst { Buffer } = require('node:buffer');

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde

const buf2 = Buffer.from('tést');

console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: té