buf.write(string[, offset[, length]][, encoding])


  • string <string> 要写入 buf 的字符串。
  • offset <integer> 开始写入的偏移量。默认 0
  • length <integer> 要写入的字节数。默认为 buf.length - offset
  • encoding <string> string 的字符编码。默认为 'utf8'
  • 返回: <integer> 已写入的字节数。

根据 encoding 指定的字符编码将 string 写入到 buf 中的 offset 位置。 如果 buf 没有足够的空间保存整个字符串,则只会写入 string 的一部分。

const buf = Buffer.alloc(256);

const len = buf.write('\u00bd + \u00bc = \u00be', 0);

console.log(`${len} 个字节: ${buf.toString('utf8', 0, len)}`);
// 输出: 12 个字节: ½ + ¼ = ¾
  • string <string> String to write to buf.
  • offset <integer> Number of bytes to skip before starting to write string. Default: 0.
  • length <integer> Number of bytes to write. Default: buf.length - offset.
  • encoding <string> The character encoding of string. Default: 'utf8'.
  • Returns: <integer> Number of bytes written.

Writes string to buf at offset according to the character encoding in encoding. The length parameter is the number of bytes to write. If buf did not contain enough space to fit the entire string, only part of string will be written. However, partially encoded characters will not be written.

const buf = Buffer.alloc(256);

const len = buf.write('\u00bd + \u00bc = \u00be', 0);

console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾