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

Usage in Deno

```typescript import { type BufferConstructor } from "node:node__buffer.d.ts"; ```
BufferConstructor.allocUnsafe(size: number): Buffer
Allocates a new `Buffer` of `size` bytes. 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. The underlying memory for `Buffer` instances created in this way is _not_ _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. ```js import { Buffer } from 'node:buffer'; const buf = Buffer.allocUnsafe(10); console.log(buf); // Prints (contents may vary): buf.fill(0); console.log(buf); // Prints: ``` A `TypeError` will be thrown if `size` is not a number. The `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe()` provides.

Parameters

size: number
The desired length of the new `Buffer`.

Return Type