How to Use Buffer.alloc in Node.js: Syntax and Examples
In Node.js, use
Buffer.alloc(size) to create a new buffer of a specified size filled with zeros. This method ensures the buffer is securely initialized, avoiding old data exposure unlike Buffer.allocUnsafe.Syntax
The Buffer.alloc method creates a new buffer of a given size filled with zeros. It takes three parameters:
- size (required): Number of bytes to allocate.
- fill (optional): Value to fill the buffer with, defaults to 0.
- encoding (optional): Encoding if
fillis a string.
javascript
Buffer.alloc(size[, fill[, encoding]])
Example
This example creates a buffer of 10 bytes filled with zeros, then prints its content as an array of numbers.
javascript
const buf = Buffer.alloc(10); console.log(buf); console.log(buf.toJSON().data);
Output
<Buffer 00 00 00 00 00 00 00 00 00 00>
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Common Pitfalls
A common mistake is using Buffer.allocUnsafe when you need a zero-filled buffer. Buffer.allocUnsafe creates a buffer faster but may contain old data, which can cause security issues.
Also, forgetting to specify size or passing a non-number causes errors.
javascript
/* Wrong: allocUnsafe may contain old data */ const unsafeBuf = Buffer.allocUnsafe(5); console.log(unsafeBuf); /* Right: alloc creates zero-filled buffer */ const safeBuf = Buffer.alloc(5); console.log(safeBuf);
Output
/* Output varies for allocUnsafe, may show random bytes */
<Buffer 7f 2a 00 1c 5d>
<Buffer 00 00 00 00 00>
Quick Reference
Use Buffer.alloc(size) to safely create zero-filled buffers. Use fill to initialize with other values. Avoid Buffer.allocUnsafe unless you manually fill the buffer immediately.
| Method | Description |
|---|---|
| Buffer.alloc(size) | Creates zero-filled buffer of given size |
| Buffer.alloc(size, fill) | Creates buffer filled with specified value |
| Buffer.allocUnsafe(size) | Creates buffer without zero-fill, may contain old data |
Key Takeaways
Use Buffer.alloc(size) to create a safe, zero-filled buffer in Node.js.
Avoid Buffer.allocUnsafe unless you fill the buffer immediately to prevent data leaks.
Buffer.alloc accepts optional fill and encoding parameters for custom initialization.
Always specify the size as a positive integer to avoid errors.
Buffer.alloc is the recommended way to create buffers in modern Node.js versions.