BufferConstructor
Raw data is stored in instances of the Buffer class. A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex'
Constructors
constructor
**new BufferConstructor**(str, encoding?)
Allocates a new buffer containing the given {str}.
Parameters
strstringRequiredencodingBufferEncodingDeprecated
since v10.0.0 - Use Buffer.from(string[, encoding]) instead.
**new BufferConstructor**(size)
Allocates a new buffer of {size} octets.
Parameters
sizenumberRequiredDeprecated
since v10.0.0 - Use Buffer.alloc() instead (also see Buffer.allocUnsafe()).
**new BufferConstructor**(array)
Allocates a new buffer containing the given {array} of octets.
Parameters
arrayUint8ArrayRequiredDeprecated
since v10.0.0 - Use Buffer.from(array) instead.
**new BufferConstructor**(arrayBuffer)
Produces a Buffer backed by the same allocated memory as the given {ArrayBuffer}/{SharedArrayBuffer}.
Parameters
Deprecated
since v10.0.0 - Use Buffer.from(arrayBuffer[, byteOffset[, length]]) instead.
**new BufferConstructor**(array)
Allocates a new buffer containing the given {array} of octets.
Parameters
arrayreadonly any[]RequiredDeprecated
since v10.0.0 - Use Buffer.from(array) instead.
**new BufferConstructor**(buffer)
Copies the passed {buffer} data onto a new {Buffer} instance.
Parameters
Deprecated
since v10.0.0 - Use Buffer.from(buffer) instead.
Properties
poolSizenumberRequiredBuffer instances used for pooling. This value may be modified.Methods
alloc
**alloc**(size, fill?, encoding?): [Buffer](/references/services/#buffer)
Allocates a new Buffer of size bytes. If fill is undefined, theBuffer will be zero-filled.
If size is larger than 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).
If both fill and encoding are specified, the allocated Buffer will be
initialized by calling buf.fill(fill, encoding).
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.
Parameters
sizenumberRequiredBuffer.fillstring | number | Uint8ArrayBuffer with.encodingBufferEncodingfill is a string, this is its encoding.Returns
Since
v5.10.0
allocUnsafe
**allocUnsafe**(size): [Buffer](/references/services/#buffer)
Allocates a new Buffer of size bytes. If size is larger than 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 initializeBuffer instances with zeroes.
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 newBuffer instances created using Buffer.allocUnsafe(), Buffer.from(array),
and Buffer.concat() only when size is less than or equal toBuffer.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 Bufferpool, while Buffer.allocUnsafe(size).fill(fill)_will_ use the internalBuffer 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
sizenumberRequiredBuffer.Returns
Since
v5.10.0
allocUnsafeSlow
**allocUnsafeSlow**(size): [Buffer](/references/services/#buffer)
Allocates a new Buffer of size bytes. If size is larger than constants.MAX_LENGTH or smaller than 0, ERR_OUT_OF_RANGE is thrown. A zero-length Buffer is created if
size is 0.
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 buf.fill(0) to initialize
such Buffer instances with zeroes.
When using Buffer.allocUnsafe() to allocate new Buffer instances,
allocations under 4 KiB are sliced from a single pre-allocated Buffer. This
allows applications to avoid the garbage collection overhead of creating many
individually allocated Buffer instances. This approach improves both
performance and memory usage by eliminating the need to track and clean up as
many individual ArrayBuffer objects.
However, in the case where a developer may need to retain a small chunk of
memory from a pool for an indeterminate amount of time, it may be appropriate
to create an un-pooled Buffer instance using Buffer.allocUnsafeSlow() and
then copying out the relevant bits.
import { Buffer } from 'node:buffer';
// Need to keep around a few small chunks of memory.
const store = [];
socket.on('readable', () => {
let data;
while (null !== (data = readable.read())) {
// Allocate for retained data.
const sb = Buffer.allocUnsafeSlow(10);
// Copy the data into the new allocation.
data.copy(sb, 0, 0, 10);
store.push(sb);
}
});
A TypeError will be thrown if size is not a number.
Parameters
sizenumberRequiredBuffer.Returns
Since
v5.12.0
byteLength
**byteLength**(string, encoding?): number
Returns the byte length of a string when encoded using encoding.
This is not the same as String.prototype.length, which does not account
for the encoding that is used to convert the string into bytes.
For 'base64', 'base64url', and 'hex', this function assumes valid input.
For strings that contain non-base64/hex-encoded data (e.g. whitespace), the
return value might be greater than the length of a Buffer created from the
string.
When string is a
Buffer/DataView/[TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/-
Reference/Global_Objects/TypedArray)/ArrayBuffer/[SharedArrayBuffer](https://develop-
er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by .byteLengthis returned.
Parameters
encodingBufferEncodingstring is a string, this is its encoding.Returns
number
numbernumberstring.Since
v0.1.90
compare
**compare**(buf1, buf2): 0 \| 1 \| -1
Compares buf1 to buf2, typically for the purpose of sorting arrays ofBuffer instances. This is equivalent to calling buf1.compare(buf2).
Parameters
buf1Uint8ArrayRequiredbuf2Uint8ArrayRequiredReturns
0 | 1 | -1
0 \| 1 \| -10 | 1 | -1-1, 0, or 1, depending on the result of the comparison. See compare for details.Since
v0.11.13
concat
**concat**(list, totalLength?): [Buffer](/references/services/#buffer)
Returns a new Buffer which is the result of concatenating all the Bufferinstances in the list together.
If the list has no items, or if the totalLength is 0, then a new zero-lengthBuffer is returned.
If totalLength is not provided, it is calculated from the Buffer instances
in list by adding their lengths.
If totalLength is provided, it is coerced to an unsigned integer. If the
combined length of the Buffers in list exceeds totalLength, the result is
truncated to totalLength.
import { Buffer } from 'node:buffer';
// Create a single `Buffer` from a list of three `Buffer` instances.
const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;
console.log(totalLength);
// Prints: 42
const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
console.log(bufA);
// Prints: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// Prints: 42
Buffer.concat() may also use the internal Buffer pool like Buffer.allocUnsafe() does.
Parameters
listreadonly Uint8Array[]RequiredBuffer or Uint8Array instances to concatenate.totalLengthnumberBuffer instances in list when concatenated.Returns
Since
v0.7.11
copyBytesFrom
**copyBytesFrom**(view, offset?, length?): [Buffer](/references/services/#buffer)
Copies the underlying memory of view into a new Buffer.
Parameters
offsetnumberview.lengthnumberview to copy.Returns
Since
v19.8.0
from
**from**(arrayBuffer, byteOffset?, length?): [Buffer](/references/services/#buffer)
Allocates a new Buffer using an array of bytes in the range 0 – 255.
Array entries outside that range will be truncated to fit into it.
If array is an Array-like object (that is, one with a length property of
type number), it is treated as if it is an array, unless it is a Buffer or
a Uint8Array. This means all other TypedArray variants get treated as anArray. To create a Buffer from the bytes backing a TypedArray, use Buffer.copyBytesFrom().
A TypeError will be thrown if array is not an Array or another type
appropriate for Buffer.from() variants.
Buffer.from(array) and Buffer.from(string) may also use the internalBuffer pool like Buffer.allocUnsafe() does.
Parameters
byteOffsetnumberlengthnumberReturns
Since
v5.10.0
**from**(data): [Buffer](/references/services/#buffer)
Creates a new Buffer using the passed {data}
Parameters
dataUint8Array | readonly number[]RequiredReturns
**from**(data): [Buffer](/references/services/#buffer)
Parameters
Returns
**from**(str, encoding?): [Buffer](/references/services/#buffer)
Creates a new Buffer containing the given JavaScript string {str}. If provided, the {encoding} parameter identifies the character encoding. If not provided, {encoding} defaults to 'utf8'.
Parameters
encodingBufferEncodingReturns
isBuffer
**isBuffer**(obj): obj is Buffer
Returns true if obj is a Buffer, false otherwise.
Parameters
objanyRequiredReturns
obj is Buffer
objobj is BufferSince
v0.1.101
isEncoding
**isEncoding**(encoding): encoding is BufferEncoding
Returns true if encoding is the name of a supported character encoding,
or false otherwise.
Parameters
encodingstringRequiredReturns
encoding is BufferEncoding
encodingencoding is BufferEncodingSince
v0.9.1
of
**of**(...items): [Buffer](/references/services/#buffer)
Creates a new Buffer using the passed {data}
Parameters
itemsnumber[]Required