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 的一部分。
但是,不会写入部分编码的字符。
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 : abstring<string> String to write tobuf.offset<integer> Number of bytes to skip before starting to writestring. Default:0.length<integer> Maximum number of bytes to write (written bytes will not exceedbuf.length - offset). Default:buf.length - offset.encoding<string> The character encoding ofstring. 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: ½ + ¼ = ¾
const buffer = Buffer.alloc(10);
const length = buffer.write('abcd', 8);
console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : ab