Buffer.alloc()
Allocates a new zero-filled Buffer of the given size.
Syntax
Buffer.alloc(size[, fill[, encoding]]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
size | number | Yes | The number of bytes to allocate. |
fill | string | Buffer | number | No | A value to pre-fill the buffer with (default 0). |
encoding | string | No | Encoding when `fill` is a string. |
Returns
Buffer — A new, safely zero-initialized Buffer.
Examples
const buf = Buffer.alloc(4);
console.log(buf);
Output
<Buffer 00 00 00 00>
const buf = Buffer.alloc(8);
buf.writeUInt32BE(0xdeadbeef, 0);
console.log(buf.toString('hex'));
Output
deadbeef0000000000
Notes
`Buffer.alloc` zero-fills and is safe. `Buffer.allocUnsafe` is faster
but returns uninitialized memory that may contain old data, so only
use it when you immediately overwrite every byte.