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


  • string <string> 要写入 buf 的字符串。
  • offset <integer> 开始写入 string 之前要跳过的字节数。 默认值: 0
  • length <integer> 要写入的最大字节数(写入的字节数不会超过 buf.length - offset)。 默认值: buf.length - offset
  • encoding <string> string 的字符编码。 默认值: 'utf8'
  • 返回: <integer> 写入的字节数。

根据 encoding 中的字符编码将 string 写入 bufoffset 处。 length 参数是要写入的字节数。 如果 buf 没有足够的空间来容纳整个字符串,则只会写入 string 的一部分。 但是,不会写入部分编码的字符。

import { Buffer } from 'node:buffer';

const buf = Buffer.alloc(256);

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

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

const buffer = Buffer.alloc(10);

const length = buffer.write('abcd', 8);

console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// 打印: 2 bytes : abconst { Buffer } = require('node:buffer');

const buf = Buffer.alloc(256);

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

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

const buffer = Buffer.alloc(10);

const length = buffer.write('abcd', 8);

console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// 打印: 2 bytes : ab
  • string <string> String to write to buf.
  • offset <integer> Number of bytes to skip before starting to write string. Default: 0.
  • length <integer> Maximum number of bytes to write (written bytes will not exceed buf.length - offset). 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.

import { Buffer } from 'node:buffer';

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: ½ + ¼ = ¾

const buffer = Buffer.alloc(10);

const length = buffer.write('abcd', 8);

console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : abconst { Buffer } = require('node:buffer');

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: ½ + ¼ = ¾

const buffer = Buffer.alloc(10);

const length = buffer.write('abcd', 8);

console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : ab