alloc

fun alloc(size: Number): Buffer(source)
fun alloc(size: Number, fill: String = definedExternally, encoding: BufferEncoding = definedExternally): Buffer(source)
fun alloc(size: Number, fill: Uint8Array<*> = definedExternally, encoding: BufferEncoding = definedExternally): Buffer(source)
fun alloc(size: Number, fill: Double = definedExternally, encoding: BufferEncoding = definedExternally): Buffer(source)

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

import { Buffer } from 'node:buffer';

const buf = Buffer.alloc(5);

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

If size is larger than {@link 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).

import { Buffer } from 'node:buffer';

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).

import { Buffer } from 'node:buffer';

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 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 Buffers.

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

Since

v5.10.0

Parameters

size

The desired length of the new Buffer.

encoding='utf8' If fill is a string, this is its encoding.