trait BufferConstructor extends Object with StObject with Instantiable1[|[|[|[|[|[|[Any, Array[Any]], ArrayBuffer], Buffer], Double], String], Uint8Array], Buffer] with Instantiable2[String, BufferEncoding, Buffer]
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'
- Annotations
- @JSType() @native()
- Alphabetic
- By Inheritance
- BufferConstructor
- Instantiable2
- Instantiable1
- StObject
- Object
- Any
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Value Members
- final def !=(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- final def ##: Int
- Definition Classes
- AnyRef → Any
- final def ==(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- def alloc(size: Double, fill: Unit, encoding: BufferEncoding): Buffer
- def alloc(size: Double, fill: Double, encoding: BufferEncoding): Buffer
- def alloc(size: Double, fill: Double): Buffer
- def alloc(size: Double, fill: String, encoding: BufferEncoding): Buffer
- def alloc(size: Double, fill: String): Buffer
- def alloc(size: Double, fill: Buffer, encoding: BufferEncoding): Buffer
- def alloc(size: Double, fill: Buffer): Buffer
- def alloc(size: Double): Buffer
Allocates a new
Buffer
ofsize
bytes.Allocates a new
Buffer
ofsize
bytes. Iffill
isundefined
, theBuffer
will be zero-filled.js import { Buffer } from 'buffer';
const buf = Buffer.alloc(5);
console.log(buf); // Prints: <Buffer 00 00 00 00 00>
If
size
is larger thanconstants.MAX_LENGTH
or smaller than 0,ERR_INVALID_ARG_VALUE
is thrown.If
fill
is specified, the allocatedBuffer
will be initialized by callingbuf.fill(fill)
.js import { Buffer } from 'buffer';
const buf = Buffer.alloc(5, 'a');
console.log(buf); // Prints: <Buffer 61 61 61 61 61>
If both
fill
andencoding
are specified, the allocatedBuffer
will be initialized by callingbuf.fill(fill, encoding)
.js import { Buffer } from '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 alternativeBuffer.allocUnsafe()
but ensures that the newly createdBuffer
instance contents will never contain sensitive data from previous allocations, including data that might not have been allocated forBuffer
s.A
TypeError
will be thrown ifsize
is not a number.- size
The desired length of the new
Buffer
.
- Since
v5.10.0
- def allocUnsafe(size: Double): Buffer
Allocates a new
Buffer
ofsize
bytes.Allocates a new
Buffer
ofsize
bytes. Ifsize
is larger thanconstants.MAX_LENGTH
or smaller than 0,ERR_INVALID_ARG_VALUE
is thrown.The underlying memory for
Buffer
instances created in this way is _not_ _initialized_. The contents of the newly createdBuffer
are unknown and_may contain sensitive data_. UseBuffer.alloc()
instead to initializeBuffer
instances with zeroes.js import { Buffer } from 'buffer';
const buf = Buffer.allocUnsafe(10);
console.log(buf); // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
buf.fill(0);
console.log(buf); // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
A
TypeError
will be thrown ifsize
is not a number.The
Buffer
module pre-allocates an internalBuffer
instance of sizeBuffer.poolSize
that is used as a pool for the fast allocation of newBuffer
instances created usingBuffer.allocUnsafe()
,Buffer.from(array)
,Buffer.concat()
, and the deprecatednew Buffer(size)
constructor only whensize
is less than or equal toBuffer.poolSize >> 1
(floor ofBuffer.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 internalBuffer
pool, whileBuffer.allocUnsafe(size).fill(fill)
_will_ use the internalBuffer
pool ifsize
is less than or equal to halfBuffer.poolSize
. The difference is subtle but can be important when an application requires the additional performance thatBuffer.allocUnsafe()
provides.- size
The desired length of the new
Buffer
.
- Since
v5.10.0
- def allocUnsafeSlow(size: Double): Buffer
Allocates a new
Buffer
ofsize
bytes.Allocates a new
Buffer
ofsize
bytes. Ifsize
is larger thanconstants.MAX_LENGTH
or smaller than 0,ERR_INVALID_ARG_VALUE
is thrown. A zero-lengthBuffer
is created ifsize
is 0.The underlying memory for
Buffer
instances created in this way is _not_ _initialized_. The contents of the newly createdBuffer
are unknown and_may contain sensitive data_. Usebuf.fill(0)
to initialize suchBuffer
instances with zeroes.When using
Buffer.allocUnsafe()
to allocate newBuffer
instances, allocations under 4 KB are sliced from a single pre-allocatedBuffer
. This allows applications to avoid the garbage collection overhead of creating many individually allocatedBuffer
instances. This approach improves both performance and memory usage by eliminating the need to track and clean up as many individualArrayBuffer
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 usingBuffer.allocUnsafeSlow()
and then copying out the relevant bits.js import { Buffer } from '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 ifsize
is not a number.- size
The desired length of the new
Buffer
.
- Since
v5.12.0
- final def asInstanceOf[T0]: T0
- Definition Classes
- Any
- def byteLength(string: ArrayBuffer, encoding: BufferEncoding): Double
- def byteLength(string: ArrayBuffer): Double
- def byteLength(string: Any, encoding: BufferEncoding): Double
- def byteLength(string: Any): Double
- def byteLength(string: String, encoding: BufferEncoding): Double
- def byteLength(string: String): Double
Returns the byte length of a string when encoded using
encoding
.Returns the byte length of a string when encoded using
encoding
. This is not the same as [String.prototype.length
](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/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 aBuffer
created from the string.js import { Buffer } from 'buffer';
const str = '\\u00bd + \\u00bc = \\u00be';
console.log(
${str}: ${str.length} characters,
+${Buffer.byteLength(str, 'utf8')} bytes
); // Prints: ½ + ¼ = ¾: 9 characters, 12 bytesWhen
string
is aBuffer
/[DataView
](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[TypedArray
](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- Reference/Global_Objects/TypedArray)/[ArrayBuffer
](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[SharedArrayBuffer
](https://develop- er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by.byteLength
is returned.- string
A value to calculate the length of.
- returns
The number of bytes contained within
string
.
- Since
v0.1.90
- def byteLength(string: ArrayBufferView, encoding: BufferEncoding): Double
- def byteLength(string: ArrayBufferView): Double
- def clone(): AnyRef
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.CloneNotSupportedException]) @native() @HotSpotIntrinsicCandidate()
- def compare(buf1: Uint8Array, buf2: Uint8Array): Double
Compares
buf1
tobuf2
, typically for the purpose of sorting arrays ofBuffer
instances.Compares
buf1
tobuf2
, typically for the purpose of sorting arrays ofBuffer
instances. This is equivalent to callingbuf1.compare(buf2)
.js import { Buffer } from 'buffer';
const buf1 = Buffer.from('1234'); const buf2 = Buffer.from('0123'); const arr = [buf1, buf2];
console.log(arr.sort(Buffer.compare)); // Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ] // (This result is equal to: [buf2, buf1].)
- returns
Either
-1
,0
, or1
, depending on the result of the comparison. Seecompare
for details.
- Since
v0.11.13
- def concat(list: Array[Uint8Array], totalLength: Double): Buffer
- def concat(list: Array[Uint8Array]): Buffer
Returns a new
Buffer
which is the result of concatenating all theBuffer
instances in thelist
together.Returns a new
Buffer
which is the result of concatenating all theBuffer
instances in thelist
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 theBuffer
instances inlist
by adding their lengths.If
totalLength
is provided, it is coerced to an unsigned integer. If the combined length of theBuffer
s inlist
exceedstotalLength
, the result is truncated tototalLength
.js import { Buffer } from 'buffer';
// Create a single
Buffer
from a list of threeBuffer
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 internalBuffer
pool likeBuffer.allocUnsafe()
does.- list
List of
Buffer
orUint8Array
instances to concatenate.
- Since
v0.7.11
- final def eq(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- def equals(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef → Any
- def from(str: WithImplicitCoercion[String], encoding: BufferEncoding): Buffer
- def from(str: ToPrimitive, encoding: BufferEncoding): Buffer
- def from(str: ToPrimitive): Buffer
- def from(data: Uint8Array): Buffer
Creates a new Buffer using the passed {data}
Creates a new Buffer using the passed {data}
- data
data to create a new Buffer
- def from(data: Array[Double]): Buffer
- def from(arrayBuffer: WithImplicitCoercion[|[ArrayBuffer, Any]], byteOffset: Unit, length: Double): Buffer
- def from(arrayBuffer: WithImplicitCoercion[|[ArrayBuffer, Any]], byteOffset: Double, length: Double): Buffer
- def from(arrayBuffer: WithImplicitCoercion[|[ArrayBuffer, Any]], byteOffset: Double): Buffer
- def from(arrayBuffer: WithImplicitCoercion[|[|[|[|[Any, Array[Double]], ArrayBuffer], String], Uint8Array]]): Buffer
Creates a new Buffer containing the given JavaScript string {str}.
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'.
- final def getClass(): Class[_ <: AnyRef]
- Definition Classes
- AnyRef → Any
- Annotations
- @native() @HotSpotIntrinsicCandidate()
- def hasOwnProperty(v: String): Boolean
- Definition Classes
- Object
- def hashCode(): Int
- Definition Classes
- AnyRef → Any
- Annotations
- @native() @HotSpotIntrinsicCandidate()
- def isBuffer(obj: Any): Boolean
Returns
true
ifobj
is aBuffer
,false
otherwise.Returns
true
ifobj
is aBuffer
,false
otherwise.js import { Buffer } from 'buffer';
Buffer.isBuffer(Buffer.alloc(10)); // true Buffer.isBuffer(Buffer.from('foo')); // true Buffer.isBuffer('a string'); // false Buffer.isBuffer([]); // false Buffer.isBuffer(new Uint8Array(1024)); // false
- Since
v0.1.101
- def isEncoding(encoding: String): Boolean
Returns
true
ifencoding
is the name of a supported character encoding, orfalse
otherwise.Returns
true
ifencoding
is the name of a supported character encoding, orfalse
otherwise.js import { Buffer } from 'buffer';
console.log(Buffer.isEncoding('utf8')); // Prints: true
console.log(Buffer.isEncoding('hex')); // Prints: true
console.log(Buffer.isEncoding('utf/8')); // Prints: false
console.log(Buffer.isEncoding()); // Prints: false
- encoding
A character encoding name to check.
- Since
v0.9.1
- final def isInstanceOf[T0]: Boolean
- Definition Classes
- Any
- def isPrototypeOf(v: Object): Boolean
- Definition Classes
- Object
- final def ne(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- final def notify(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native() @HotSpotIntrinsicCandidate()
- final def notifyAll(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native() @HotSpotIntrinsicCandidate()
- def of(items: Double*): Buffer
Creates a new Buffer using the passed {data}
- val poolSize: Double
This is the size (in bytes) of pre-allocated internal
Buffer
instances used for pooling.This is the size (in bytes) of pre-allocated internal
Buffer
instances used for pooling. This value may be modified.- Since
v0.11.3
- def propertyIsEnumerable(v: String): Boolean
- Definition Classes
- Object
- final def synchronized[T0](arg0: => T0): T0
- Definition Classes
- AnyRef
- def toLocaleString(): String
- Definition Classes
- Object
- def toString(): String
- Definition Classes
- AnyRef → Any
- def valueOf(): Any
- Definition Classes
- Object
- final def wait(arg0: Long, arg1: Int): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
- final def wait(arg0: Long): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException]) @native()
- final def wait(): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
Deprecated Value Members
- def finalize(): Unit
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.Throwable]) @Deprecated
- Deprecated