Skip to main content
BufferConstructor.alloc - node__buffer.d.ts - Node documentation
method BufferConstructor.alloc

Usage in Deno

```typescript import { type BufferConstructor } from "node:node__buffer.d.ts"; ```
BufferConstructor.alloc(
size: number,
fill?:
string
| Uint8Array
| number
,
encoding?: BufferEncoding,
): Buffer
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. ```js import { Buffer } from 'node:buffer'; const buf = Buffer.alloc(5); console.log(buf); // Prints: ``` If `size` is larger than [constants.MAX_LENGTH](../.././node__buffer.d.ts/~/constants.MAX_LENGTH) or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. ```js import { Buffer } from 'node:buffer'; const buf = Buffer.alloc(5, 'a'); console.log(buf); // Prints: ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. ```js import { Buffer } from 'node:buffer'; const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // Prints: ``` Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance contents will never contain sensitive data from previous allocations, including data that might not have been allocated for `Buffer`s. A `TypeError` will be thrown if `size` is not a number.

Parameters

size: number
The desired length of the new `Buffer`.
optional
fill:
string
| Uint8Array
| number
= 0
A value to pre-fill the new `Buffer` with.
optional
encoding: BufferEncoding = 'utf8'
If `fill` is a string, this is its encoding.

Return Type