buf.fill(value[, offset[, end]][, encoding])
value<string> | <Buffer> | <Uint8Array> | <integer> 用于填充buf的值。offset<integer> 在开始填充buf之前要跳过的字节数。 默认值:0。end<integer> 停止填充buf(不包括在内)的位置。 默认值:buf.length.encoding<string> 如果value是字符串,则为value的编码。 默认值:'utf8'。- 返回: <Buffer>
buf的引用。
用指定的 value 填充 buf。
如果没有给定 offset 和 end,则整个 buf 都会被填满:
// 用 ASCII 字符 'h' 填充 `Buffer`。
const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString());
// 打印: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh如果 value 不是字符串、Buffer 或整数,则将其强制为 uint32 值。
如果结果整数大于 255(十进制),则 buf 将填充 value & 255。
如果 fill() 操作的最终写入落在多字节字符上,则仅写入适合 buf 的该字符的字节:
// 用在 UTF-8 中占用两个字节的字符填充 `Buffer`。
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// 打印: <Buffer c8 a2 c8 a2 c8>如果 value 包含无效字符,则截断;如果没有有效的填充数据,则抛出异常:
const buf = Buffer.allocUnsafe(5);
console.log(buf.fill('a'));
// 打印: <Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// 打印: <Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// 抛出异常。value<string> | <Buffer> | <Uint8Array> | <integer> The value with which to fillbuf.offset<integer> Number of bytes to skip before starting to fillbuf. Default:0.end<integer> Where to stop fillingbuf(not inclusive). Default:buf.length.encoding<string> The encoding forvalueifvalueis a string. Default:'utf8'.- Returns: <Buffer> A reference to
buf.
Fills buf with the specified value. If the offset and end are not given,
the entire buf will be filled:
// Fill a `Buffer` with the ASCII character 'h'.
const b = Buffer.allocUnsafe(50).fill('h');
console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhvalue is coerced to a uint32 value if it is not a string, Buffer, or
integer. If the resulting integer is greater than 255 (decimal), buf will be
filled with value & 255.
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:
// 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>If value contains invalid characters, it is truncated; if no valid
fill data remains, an exception is thrown:
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.