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 写入 buf 的 offset 位置。参数 length 是要写入的字节数。如果 buf 没有足够的空间容纳整个字符串,则只会写入部分 string。但是,部分编码的字符将不会被写入。
【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