buf.fill(value[, offset[, end]][, encoding])
value<string> | <Buffer> | <Uint8Array> | <integer> 用于填充buf的值。空值(字符串、Uint8Array、Buffer)会被强制转换为0。offset<integer> 开始填充buf之前要跳过的字节数。默认值:0。end<integer> 填充buf的终止位置(不包括该位置)。默认值:buf.length。encoding<string> 如果value是字符串时,value的编码方式。默认值:'utf8'。- 返回:<Buffer>
buf的引用。
用指定的 value 填充 buf。如果未给出 offset 和 end,则整个 buf 都会被填充:
【Fills buf with the specified value. If the offset and end are not given,
the entire buf will be filled:】
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with the ASCII character 'h'.
const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');
console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>const { Buffer } = require('node:buffer');
// Fill a `Buffer` with the ASCII character 'h'.
const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');
console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>value 会被强制转为 uint32 值,如果它不是字符串、Buffer 或整数。如果得到的整数大于 255(十进制),buf 将会被填充为 value & 255。
如果 fill() 操作的最终写入发生在一个多字节字符上,那么只有能够放入 buf 的该字符的字节会被写入:
【If the final write of a fill() operation falls on a multi-byte character,
then only the bytes of that character that fit into buf are written:】
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints: <Buffer c8 a2 c8 a2 c8>const { Buffer } = require('node:buffer');
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints: <Buffer c8 a2 c8 a2 c8>如果 value 包含无效字符,则会被截断;如果没有剩余有效的填充数据,则会抛出异常:
【If value contains invalid characters, it is truncated; if no valid
fill data remains, an exception is thrown:】
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(5);
console.log(buf.fill('a'));
// Prints: <Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// Prints: <Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// Throws an exception.const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(5);
console.log(buf.fill('a'));
// Prints: <Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// Prints: <Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// Throws an exception.