Buffer.alloc(size[, fill[, encoding]])


  • size <integer> 新建的 Buffer 的长度。
  • fill <string> | <Buffer> | <integer> 预填充 Buffer 的值。默认为 0
  • encoding <string> 如果 fill 是字符串,则指定 fill 的字符编码。默认为 'utf8'

创建一个大小为 size 字节的 Buffer。 如果 fillundefined,则用 0 填充 Buffer

const buf = Buffer.alloc(5);

console.log(buf);
// 输出: <Buffer 00 00 00 00 00>

如果 size 大于 buffer.constants.MAX_LENGTH 或小于 0,则抛出 ERR_INVALID_OPT_VALUE。 如果 size 为 0,则创建一个长度为 0 的 Buffer

如果指定了 fill,则调用 buf.fill(fill) 初始化 Buffer

const buf = Buffer.alloc(5, 'a');

console.log(buf);
// 输出: <Buffer 61 61 61 61 61>

如果同时指定了 fillencoding,则调用 buf.fill(fill, encoding) 初始化 Buffer

const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');

console.log(buf);
// 输出: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>

Buffer.alloc()Buffer.allocUnsafe() 慢,但能确保新建的 Buffer 不会包含旧数据。

  • size <integer> The desired length of the new Buffer.
  • fill <string> | <Buffer> | <integer> A value to pre-fill the new Buffer with. Default: 0.
  • encoding <string> If fill is a string, this is its encoding. Default: 'utf8'.

Allocates a new Buffer of size bytes. If fill is undefined, the Buffer will be zero-filled.

const buf = Buffer.alloc(5);

console.log(buf);
// Prints: <Buffer 00 00 00 00 00>

Allocates a new Buffer of size bytes. If size is larger than buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE is thrown. A zero-length Buffer is created if size is 0.

If fill is specified, the allocated Buffer will be initialized by calling buf.fill(fill).

const buf = Buffer.alloc(5, 'a');

console.log(buf);
// Prints: <Buffer 61 61 61 61 61>

If both fill and encoding are specified, the allocated Buffer will be initialized by calling buf.fill(fill, encoding).

const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');

console.log(buf);
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>

Calling Buffer.alloc() can be significantly slower than the alternative Buffer.allocUnsafe() but ensures that the newly created Buffer instance contents will never contain sensitive data.

A TypeError will be thrown if size is not a number.