home / documentation / v16 / buffer

Buffer

目录

自 v0.1.90 版本开始新增

稳定级别:2 - Stable

Buffer objects are used to represent a fixed-length sequence of bytes. Many Node.js APIs support Buffers.

The Buffer class is a subclass of JavaScript's Uint8Array class and extends it with methods that cover additional use cases. Node.js APIs accept plain Uint8Arrays wherever Buffers are supported as well.

While the Buffer class is available within the global scope, it is still recommended to explicitly reference it via an import or require statement.

MJS
CJS

Buffers and character encodings

When converting between Buffers and strings, a character encoding may be specified. If no character encoding is specified, UTF-8 will be used as the default.

MJS
CJS

Node.js buffers accept all case variations of encoding strings that they receive. For example, UTF-8 can be specified as 'utf8', 'UTF8', or 'uTf8'.

The character encodings currently supported by Node.js are the following:

  • 'utf8' (alias: 'utf-8'): Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8. This is the default character encoding. When decoding a Buffer into a string that does not exclusively contain valid UTF-8 data, the Unicode replacement character U+FFFD � will be used to represent those errors.

  • 'utf16le' (alias: 'utf-16le'): Multi-byte encoded Unicode characters. Unlike 'utf8', each character in the string will be encoded using either 2 or 4 bytes. Node.js only supports the little-endian variant of UTF-16.

  • 'latin1': Latin-1 stands for ISO-8859-1. This character encoding only supports the Unicode characters from U+0000 to U+00FF. Each character is encoded using a single byte. Characters that do not fit into that range are truncated and will be mapped to characters in that range.

Converting a Buffer into a string using one of the above is referred to as decoding, and converting a string into a Buffer is referred to as encoding.

Node.js also supports the following binary-to-text encodings. For binary-to-text encodings, the naming convention is reversed: Converting a Buffer into a string is typically referred to as encoding, and converting a string into a Buffer as decoding.

  • 'base64': Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC 4648, Section 5. Whitespace characters such as spaces, tabs, and new lines contained within the base64-encoded string are ignored.

  • 'base64url': base64url encoding as specified in RFC 4648, Section 5. When creating a Buffer from a string, this encoding will also correctly accept regular base64-encoded strings. When encoding a Buffer to a string, this encoding will omit padding.

  • 'hex': Encode each byte as two hexadecimal characters. Data truncation may occur when decoding strings that do not exclusively consist of an even number of hexadecimal characters. See below for an example.

The following legacy character encodings are also supported:

  • 'ascii': For 7-bit ASCII data only. When encoding a string into a Buffer, this is equivalent to using 'latin1'. When decoding a Buffer into a string, using this encoding will additionally unset the highest bit of each byte before decoding as 'latin1'. Generally, there should be no reason to use this encoding, as 'utf8' (or, if the data is known to always be ASCII-only, 'latin1') will be a better choice when encoding or decoding ASCII-only text. It is only provided for legacy compatibility.

  • 'binary': Alias for 'latin1'. See binary strings for more background on this topic. The name of this encoding can be very misleading, as all of the encodings listed here convert between strings and binary data. For converting between strings and Buffers, typically 'utf8' is the right choice.

  • 'ucs2', 'ucs-2': Aliases of 'utf16le'. UCS-2 used to refer to a variant of UTF-16 that did not support characters that had code points larger than U+FFFF. In Node.js, these code points are always supported.

MJS
CJS

Modern Web browsers follow the WHATWG Encoding Standard which aliases both 'latin1' and 'ISO-8859-1' to 'win-1252'. This means that while doing something like http.get(), if the returned charset is one of those listed in the WHATWG specification it is possible that the server actually returned 'win-1252'-encoded data, and using 'latin1' encoding may incorrectly decode the characters.

Buffers and TypedArrays

Buffer instances are also JavaScript Uint8Array and TypedArray instances. All TypedArray methods are available on Buffers. There are, however, subtle incompatibilities between the Buffer API and the TypedArray API.

In particular:

There are two ways to create new TypedArray instances from a Buffer:

  • Passing a Buffer to a TypedArray constructor will copy the Buffers contents, interpreted as an array of integers, and not as a byte sequence of the target type.
MJS
CJS
  • Passing the Buffers underlying ArrayBuffer will create a TypedArray that shares its memory with the Buffer.
MJS
CJS

It is possible to create a new Buffer that shares the same allocated memory as a TypedArray instance by using the TypedArray object's .buffer property in the same way. Buffer.from() behaves like new Uint8Array() in this context.

MJS
CJS

When creating a Buffer using a TypedArray's .buffer, it is possible to use only a portion of the underlying ArrayBuffer by passing in byteOffset and length parameters.

MJS
CJS

The Buffer.from() and TypedArray.from() have different signatures and implementations. Specifically, the TypedArray variants accept a second argument that is a mapping function that is invoked on every element of the typed array:

  • TypedArray.from(source[, mapFn[, thisArg]])

The Buffer.from() method, however, does not support the use of a mapping function:

Buffers and iteration

Buffer instances can be iterated over using for..of syntax:

MJS
CJS

Additionally, the buf.values(), buf.keys(), and buf.entries() methods can be used to create iterators.

C Blob

历史
版本历史变更
v16.17.0No longer experimental.
v15.7.0, v14.18.0自 v15.7.0, v14.18.0 版本开始新增

A Blob encapsulates immutable, raw data that can be safely shared across multiple worker threads.

M new buffer.Blob([sources[, options]])

历史
版本历史变更
v16.7.0Added the standard `endings` option to replace line-endings, and removed the non-standard `encoding` option.
v15.7.0自 v15.7.0 版本开始新增
  • sources string[]|ArrayBuffer[]|TypedArray[]|DataView[]|Blob[] An array of string, ArrayBuffer, TypedArray, DataView, or Blob objects, or any mix of such objects, that will be stored within the Blob.
  • options Object
    • endings string One of either 'transparent' or 'native'. When set to 'native', line endings in string source parts will be converted to the platform native line-ending as specified by require('node:os').EOL.
    • type string The Blob content-type. The intent is for type to convey the MIME media type of the data, however no validation of the type format is performed.

Creates a new Blob object containing a concatenation of the given sources.

ArrayBuffer, TypedArray, DataView, and Buffer sources are copied into the 'Blob' and can therefore be safely modified after the 'Blob' is created.

String sources are encoded as UTF-8 byte sequences and copied into the Blob. Unmatched surrogate pairs within each string part will be replaced by Unicode U+FFFD replacement characters.

M blob.arrayBuffer()

自 v15.7.0 版本开始新增

Returns a promise that fulfills with an ArrayBuffer containing a copy of the Blob data.

M blob.size

自 v15.7.0 版本开始新增

The total size of the Blob in bytes.

M blob.slice([start[, end[, type]]])

自 v15.7.0 版本开始新增

  • start number The starting index.
  • end number The ending index.
  • type string The content-type for the new Blob

Creates and returns a new Blob containing a subset of this Blob objects data. The original Blob is not altered.

M blob.stream()

自 v16.7.0 版本开始新增

Returns a new ReadableStream that allows the content of the Blob to be read.

M blob.text()

自 v15.7.0 版本开始新增

Returns a promise that fulfills with the contents of the Blob decoded as a UTF-8 string.

M blob.type

自 v15.7.0 版本开始新增

The content-type of the Blob.

M Blob objects and MessageChannel

Once a Blob object is created, it can be sent via MessagePort to multiple destinations without transferring or immediately copying the data. The data contained by the Blob is copied only when the arrayBuffer() or text() methods are called.

MJS
CJS

C Buffer

The Buffer class is a global type for dealing with binary data directly. It can be constructed in a variety of ways.

Static method: Buffer.alloc(size[, fill[, encoding]])

历史
版本历史变更
v15.0.0Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments.
v10.0.0Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception.
v10.0.0Specifying an invalid string for `fill` triggers a thrown exception.
v8.9.3Specifying an invalid string for `fill` now results in a zero-filled buffer.
v5.10.0自 v5.10.0 版本开始新增
  • size integer The desired length of the new Buffer.
  • fill string | Buffer | Uint8Array | integer A value to pre-fill the new Buffer with. Default: 0.
  • encoding string If fill is a string, this is its encoding. Default: 'utf8'.

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

MJS
CJS

If size is larger than buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_ARG_VALUE is thrown.

If fill is specified, the allocated Buffer will be initialized by calling buf.fill(fill).

MJS
CJS

If both fill and encoding are specified, the allocated Buffer will be initialized by calling buf.fill(fill, encoding).

MJS
CJS

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.

Static method: Buffer.allocUnsafe(size)

历史
版本历史变更
v15.0.0Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments.
v7.0.0Passing a negative `size` will now throw an error.
v5.10.0自 v5.10.0 版本开始新增
  • size integer The desired length of the new Buffer.

Allocates a new Buffer of size bytes. If size is larger than buffer.constants.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 created Buffer are unknown and may contain sensitive data. Use Buffer.alloc() instead to initialize Buffer instances with zeroes.

MJS
CJS

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), Buffer.concat(), and the deprecated new Buffer(size) constructor only when size is less than or equal to 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.

Static method: Buffer.allocUnsafeSlow(size)

历史
版本历史变更
v15.0.0Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments.
v5.12.0自 v5.12.0 版本开始新增
  • size integer The desired length of the new Buffer.

Allocates a new Buffer of size bytes. If size is larger than buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_ARG_VALUE 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.

MJS
CJS

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

Static method: Buffer.byteLength(string[, encoding])

历史
版本历史变更
v7.0.0Passing invalid input will now throw an error.
v5.10.0The `string` parameter can now be any `TypedArray`, `DataView` or `ArrayBuffer`.
v0.1.90自 v0.1.90 版本开始新增

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.

MJS
CJS

When string is a Buffer/DataView/TypedArray/ArrayBuffer/ SharedArrayBuffer, the byte length as reported by .byteLength is returned.

Static method: Buffer.compare(buf1, buf2)

历史
版本历史变更
v8.0.0The arguments can now be `Uint8Array`s.
v0.11.13自 v0.11.13 版本开始新增

Compares buf1 to buf2, typically for the purpose of sorting arrays of Buffer instances. This is equivalent to calling buf1.compare(buf2).

MJS
CJS

Static method: Buffer.concat(list[, totalLength])

历史
版本历史变更
v8.0.0The elements of `list` can now be `Uint8Array`s.
v0.7.11自 v0.7.11 版本开始新增
  • list Buffer[] | Uint8Array[] List of Buffer or Uint8Array instances to concatenate.
  • totalLength integer Total length of the Buffer instances in list when concatenated.
  • Returns: Buffer

Returns a new Buffer which is the result of concatenating all the Buffer instances in the list together.

If the list has no items, or if the totalLength is 0, then a new zero-length Buffer 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.

MJS
CJS

Buffer.concat() may also use the internal Buffer pool like Buffer.allocUnsafe() does.

Static method: Buffer.from(array)

自 v5.10.0 版本开始新增

  • array integer[]

Allocates a new Buffer using an array of bytes in the range 0255. Array entries outside that range will be truncated to fit into it.

MJS
CJS

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 internal Buffer pool like Buffer.allocUnsafe() does.

Static method: Buffer.from(arrayBuffer[, byteOffset[, length]])

自 v5.10.0 版本开始新增

This creates a view of the ArrayBuffer without copying the underlying memory. For example, when passed a reference to the .buffer property of a TypedArray instance, the newly created Buffer will share the same allocated memory as the TypedArray's underlying ArrayBuffer.

MJS
CJS

The optional byteOffset and length arguments specify a memory range within the arrayBuffer that will be shared by the Buffer.

MJS
CJS

A TypeError will be thrown if arrayBuffer is not an ArrayBuffer or a SharedArrayBuffer or another type appropriate for Buffer.from() variants.

It is important to remember that a backing ArrayBuffer can cover a range of memory that extends beyond the bounds of a TypedArray view. A new Buffer created using the buffer property of a TypedArray may extend beyond the range of the TypedArray:

MJS
CJS

Static method: Buffer.from(buffer)

自 v5.10.0 版本开始新增

Copies the passed buffer data onto a new Buffer instance.

MJS
CJS

A TypeError will be thrown if buffer is not a Buffer or another type appropriate for Buffer.from() variants.

Static method: Buffer.from(object[, offsetOrEncoding[, length]])

自 v8.2.0 版本开始新增

  • object Object An object supporting Symbol.toPrimitive or valueOf().
  • offsetOrEncoding integer | string A byte-offset or encoding.
  • length integer A length.

For objects whose valueOf() function returns a value not strictly equal to object, returns Buffer.from(object.valueOf(), offsetOrEncoding, length).

MJS
CJS

For objects that support Symbol.toPrimitive, returns Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding).

MJS
CJS

A TypeError will be thrown if object does not have the mentioned methods or is not of another type appropriate for Buffer.from() variants.

Static method: Buffer.from(string[, encoding])

自 v5.10.0 版本开始新增

  • string string A string to encode.
  • encoding string The encoding of string. Default: 'utf8'.

Creates a new Buffer containing string. The encoding parameter identifies the character encoding to be used when converting string into bytes.

MJS
CJS

A TypeError will be thrown if string is not a string or another type appropriate for Buffer.from() variants.

Static method: Buffer.isBuffer(obj)

自 v0.1.101 版本开始新增

Returns true if obj is a Buffer, false otherwise.

MJS
CJS

Static method: Buffer.isEncoding(encoding)

自 v0.9.1 版本开始新增

  • encoding string A character encoding name to check.
  • Returns: boolean

Returns true if encoding is the name of a supported character encoding, or false otherwise.

MJS
CJS

Class property: Buffer.poolSize

自 v0.11.3 版本开始新增

This is the size (in bytes) of pre-allocated internal Buffer instances used for pooling. This value may be modified.

M buf[index]

The index operator [index] can be used to get and set the octet at position index in buf. The values refer to individual bytes, so the legal value range is between 0x00 and 0xFF (hex) or 0 and 255 (decimal).

This operator is inherited from Uint8Array, so its behavior on out-of-bounds access is the same as Uint8Array. In other words, buf[index] returns undefined when index is negative or greater or equal to buf.length, and buf[index] = value does not modify the buffer if index is negative or >= buf.length.

MJS
CJS

M buf.buffer

  • ArrayBuffer The underlying ArrayBuffer object based on which this Buffer object is created.

This ArrayBuffer is not guaranteed to correspond exactly to the original Buffer. See the notes on buf.byteOffset for details.

MJS
CJS

M buf.byteOffset

  • integer The byteOffset of the Buffers underlying ArrayBuffer object.

When setting byteOffset in Buffer.from(ArrayBuffer, byteOffset, length), or sometimes when allocating a Buffer smaller than Buffer.poolSize, the buffer does not start from a zero offset on the underlying ArrayBuffer.

This can cause problems when accessing the underlying ArrayBuffer directly using buf.buffer, as other parts of the ArrayBuffer may be unrelated to the Buffer object itself.

A common issue when creating a TypedArray object that shares its memory with a Buffer is that in this case one needs to specify the byteOffset correctly:

MJS
CJS

M buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])

历史
版本历史变更
v8.0.0The `target` parameter can now be a `Uint8Array`.
v5.11.0Additional parameters for specifying offsets are supported now.
v0.11.13自 v0.11.13 版本开始新增
  • target Buffer | Uint8Array A Buffer or Uint8Array with which to compare buf.
  • targetStart integer The offset within target at which to begin comparison. Default: 0.
  • targetEnd integer The offset within target at which to end comparison (not inclusive). Default: target.length.
  • sourceStart integer The offset within buf at which to begin comparison. Default: 0.
  • sourceEnd integer The offset within buf at which to end comparison (not inclusive). Default: buf.length.
  • Returns: integer

Compares buf with target and returns a number indicating whether buf comes before, after, or is the same as target in sort order. Comparison is based on the actual sequence of bytes in each Buffer.

  • 0 is returned if target is the same as buf
  • 1 is returned if target should come before buf when sorted.
  • -1 is returned if target should come after buf when sorted.
MJS
CJS

The optional targetStart, targetEnd, sourceStart, and sourceEnd arguments can be used to limit the comparison to specific ranges within target and buf respectively.

MJS
CJS

ERR_OUT_OF_RANGE is thrown if targetStart < 0, sourceStart < 0, targetEnd > target.byteLength, or sourceEnd > source.byteLength.

M buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])

自 v0.1.90 版本开始新增

  • target Buffer | Uint8Array A Buffer or Uint8Array to copy into.
  • targetStart integer The offset within target at which to begin writing. Default: 0.
  • sourceStart integer The offset within buf from which to begin copying. Default: 0.
  • sourceEnd integer The offset within buf at which to stop copying (not inclusive). Default: buf.length.
  • Returns: integer The number of bytes copied.

Copies data from a region of buf to a region in target, even if the target memory region overlaps with buf.

TypedArray.prototype.set() performs the same operation, and is available for all TypedArrays, including Node.js Buffers, although it takes different function arguments.

MJS
CJS
MJS
CJS

M buf.entries()

自 v1.1.0 版本开始新增

Creates and returns an iterator of [index, byte] pairs from the contents of buf.

MJS
CJS

M buf.equals(otherBuffer)

历史
版本历史变更
v8.0.0The arguments can now be `Uint8Array`s.
v0.11.13自 v0.11.13 版本开始新增

Returns true if both buf and otherBuffer have exactly the same bytes, false otherwise. Equivalent to buf.compare(otherBuffer) === 0.

MJS
CJS

M buf.fill(value[, offset[, end]][, encoding])

历史
版本历史变更
v11.0.0Throws `ERR_OUT_OF_RANGE` instead of `ERR_INDEX_OUT_OF_RANGE`.
v10.0.0Negative `end` values throw an `ERR_INDEX_OUT_OF_RANGE` error.
v10.0.0Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception.
v10.0.0Specifying an invalid string for `value` triggers a thrown exception.
v5.7.0The `encoding` parameter is supported now.
v0.5.0自 v0.5.0 版本开始新增
  • value string | Buffer | Uint8Array | integer The value with which to fill buf.
  • offset integer Number of bytes to skip before starting to fill buf. Default: 0.
  • end integer Where to stop filling buf (not inclusive). Default:buf.length.
  • encoding string The encoding for value if value is a string. Default: 'utf8'.
  • Returns: Buffer A reference to buf.

Fills buf with the specified value. If the offset and end are not given, the entire buf will be filled:

MJS
CJS

value is coerced to a uint32 value if it is not a string, Buffer, or integer. If the resulting integer is greater than 255 (decimal), buf will be filled with value & 255.

If the final write of a fill() operation falls on a multi-byte character, then only the bytes of that character that fit into buf are written:

MJS
CJS

If value contains invalid characters, it is truncated; if no valid fill data remains, an exception is thrown:

MJS
CJS

M buf.includes(value[, byteOffset][, encoding])

自 v5.3.0 版本开始新增

  • value string | Buffer | Uint8Array | integer What to search for.
  • byteOffset integer Where to begin searching in buf. If negative, then offset is calculated from the end of buf. Default: 0.
  • encoding string If value is a string, this is its encoding. Default: 'utf8'.
  • Returns: boolean true if value was found in buf, false otherwise.

Equivalent to buf.indexOf() !== -1.

MJS
CJS

M buf.indexOf(value[, byteOffset][, encoding])

历史
版本历史变更
v8.0.0The `value` can now be a `Uint8Array`.
v5.7.0, v4.4.0When `encoding` is being passed, the `byteOffset` parameter is no longer required.
v1.5.0自 v1.5.0 版本开始新增
  • value string | Buffer | Uint8Array | integer What to search for.
  • byteOffset integer Where to begin searching in buf. If negative, then offset is calculated from the end of buf. Default: 0.
  • encoding string If value is a string, this is the encoding used to determine the binary representation of the string that will be searched for in buf. Default: 'utf8'.
  • Returns: integer The index of the first occurrence of value in buf, or -1 if buf does not contain value.

If value is:

  • a string, value is interpreted according to the character encoding in encoding.
  • a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use buf.subarray.
  • a number, value will be interpreted as an unsigned 8-bit integer value between 0 and 255.
MJS
CJS

If value is not a string, number, or Buffer, this method will throw a TypeError. If value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.

If byteOffset is not a number, it will be coerced to a number. If the result of coercion is NaN or 0, then the entire buffer will be searched. This behavior matches String.prototype.indexOf().

MJS
CJS

If value is an empty string or empty Buffer and byteOffset is less than buf.length, byteOffset will be returned. If value is empty and byteOffset is at least buf.length, buf.length will be returned.

M buf.keys()

自 v1.1.0 版本开始新增

Creates and returns an iterator of buf keys (indices).

MJS
CJS

M buf.lastIndexOf(value[, byteOffset][, encoding])

历史
版本历史变更
v8.0.0The `value` can now be a `Uint8Array`.
v6.0.0自 v6.0.0 版本开始新增
  • value string | Buffer | Uint8Array | integer What to search for.
  • byteOffset integer Where to begin searching in buf. If negative, then offset is calculated from the end of buf. Default:buf.length - 1.
  • encoding string If value is a string, this is the encoding used to determine the binary representation of the string that will be searched for in buf. Default: 'utf8'.
  • Returns: integer The index of the last occurrence of value in buf, or -1 if buf does not contain value.

Identical to buf.indexOf(), except the last occurrence of value is found rather than the first occurrence.

MJS
CJS

If value is not a string, number, or Buffer, this method will throw a TypeError. If value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.

If byteOffset is not a number, it will be coerced to a number. Any arguments that coerce to NaN, like {} or undefined, will search the whole buffer. This behavior matches String.prototype.lastIndexOf().

MJS
CJS

If value is an empty string or empty Buffer, byteOffset will be returned.

M buf.length

自 v0.1.90 版本开始新增

Returns the number of bytes in buf.

MJS
CJS

M buf.parent

自 v8.0.0 版本开始弃用

稳定级别:0 - Deprecated: Use `buf.buffer` instead.

The buf.parent property is a deprecated alias for buf.buffer.

M buf.readBigInt64BE([offset])

自 v12.0.0, v10.20.0 版本开始新增

  • offset integer Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: bigint

Reads a signed, big-endian 64-bit integer from buf at the specified offset.

Integers read from a Buffer are interpreted as two's complement signed values.

M buf.readBigInt64LE([offset])

自 v12.0.0, v10.20.0 版本开始新增

  • offset integer Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: bigint

Reads a signed, little-endian 64-bit integer from buf at the specified offset.

Integers read from a Buffer are interpreted as two's complement signed values.

M buf.readBigUInt64BE([offset])

历史
版本历史变更
v14.10.0, v12.19.0This function is also available as `buf.readBigUint64BE()`.
v12.0.0, v10.20.0自 v12.0.0, v10.20.0 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: bigint

Reads an unsigned, big-endian 64-bit integer from buf at the specified offset.

This function is also available under the readBigUint64BE alias.

MJS
CJS

M buf.readBigUInt64LE([offset])

历史
版本历史变更
v14.10.0, v12.19.0This function is also available as `buf.readBigUint64LE()`.
v12.0.0, v10.20.0自 v12.0.0, v10.20.0 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: bigint

Reads an unsigned, little-endian 64-bit integer from buf at the specified offset.

This function is also available under the readBigUint64LE alias.

MJS
CJS

M buf.readDoubleBE([offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: number

Reads a 64-bit, big-endian double from buf at the specified offset.

MJS
CJS

M buf.readDoubleLE([offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: number

Reads a 64-bit, little-endian double from buf at the specified offset.

MJS
CJS

M buf.readFloatBE([offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: number

Reads a 32-bit, big-endian float from buf at the specified offset.

MJS
CJS

M buf.readFloatLE([offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: number

Reads a 32-bit, little-endian float from buf at the specified offset.

MJS
CJS

M buf.readInt8([offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.0自 v0.5.0 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.
  • Returns: integer

Reads a signed 8-bit integer from buf at the specified offset.

Integers read from a Buffer are interpreted as two's complement signed values.

MJS
CJS

M buf.readInt16BE([offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
  • Returns: integer

Reads a signed, big-endian 16-bit integer from buf at the specified offset.

Integers read from a Buffer are interpreted as two's complement signed values.

MJS
CJS

M buf.readInt16LE([offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
  • Returns: integer

Reads a signed, little-endian 16-bit integer from buf at the specified offset.

Integers read from a Buffer are interpreted as two's complement signed values.

MJS
CJS

M buf.readInt32BE([offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer

Reads a signed, big-endian 32-bit integer from buf at the specified offset.

Integers read from a Buffer are interpreted as two's complement signed values.

MJS
CJS

M buf.readInt32LE([offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer

Reads a signed, little-endian 32-bit integer from buf at the specified offset.

Integers read from a Buffer are interpreted as two's complement signed values.

MJS
CJS

M buf.readIntBE(offset, byteLength)

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.
  • byteLength integer Number of bytes to read. Must satisfy 0 < byteLength <= 6.
  • Returns: integer

Reads byteLength number of bytes from buf at the specified offset and interprets the result as a big-endian, two's complement signed value supporting up to 48 bits of accuracy.

MJS
CJS

M buf.readIntLE(offset, byteLength)

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.
  • byteLength integer Number of bytes to read. Must satisfy 0 < byteLength <= 6.
  • Returns: integer

Reads byteLength number of bytes from buf at the specified offset and interprets the result as a little-endian, two's complement signed value supporting up to 48 bits of accuracy.

MJS
CJS

M buf.readUInt8([offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.readUint8()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.0自 v0.5.0 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.
  • Returns: integer

Reads an unsigned 8-bit integer from buf at the specified offset.

This function is also available under the readUint8 alias.

MJS
CJS

M buf.readUInt16BE([offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.readUint16BE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
  • Returns: integer

Reads an unsigned, big-endian 16-bit integer from buf at the specified offset.

This function is also available under the readUint16BE alias.

MJS
CJS

M buf.readUInt16LE([offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.readUint16LE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
  • Returns: integer

Reads an unsigned, little-endian 16-bit integer from buf at the specified offset.

This function is also available under the readUint16LE alias.

MJS
CJS

M buf.readUInt32BE([offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.readUint32BE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer

Reads an unsigned, big-endian 32-bit integer from buf at the specified offset.

This function is also available under the readUint32BE alias.

MJS
CJS

M buf.readUInt32LE([offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.readUint32LE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer

Reads an unsigned, little-endian 32-bit integer from buf at the specified offset.

This function is also available under the readUint32LE alias.

MJS
CJS

M buf.readUIntBE(offset, byteLength)

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.readUintBE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.
  • byteLength integer Number of bytes to read. Must satisfy 0 < byteLength <= 6.
  • Returns: integer

Reads byteLength number of bytes from buf at the specified offset and interprets the result as an unsigned big-endian integer supporting up to 48 bits of accuracy.

This function is also available under the readUintBE alias.

MJS
CJS

M buf.readUIntLE(offset, byteLength)

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.readUintLE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • offset integer Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.
  • byteLength integer Number of bytes to read. Must satisfy 0 < byteLength <= 6.
  • Returns: integer

Reads byteLength number of bytes from buf at the specified offset and interprets the result as an unsigned, little-endian integer supporting up to 48 bits of accuracy.

This function is also available under the readUintLE alias.

MJS
CJS

M buf.subarray([start[, end]])

自 v3.0.0 版本开始新增

  • start integer Where the new Buffer will start. Default: 0.
  • end integer Where the new Buffer will end (not inclusive). Default: buf.length.
  • Returns: Buffer

Returns a new Buffer that references the same memory as the original, but offset and cropped by the start and end indices.

Specifying end greater than buf.length will return the same result as that of end equal to buf.length.

This method is inherited from TypedArray.prototype.subarray().

Modifying the new Buffer slice will modify the memory in the original Buffer because the allocated memory of the two objects overlap.

MJS
CJS

Specifying negative indexes causes the slice to be generated relative to the end of buf rather than the beginning.

MJS
CJS

M buf.slice([start[, end]])

历史
版本历史变更
v16.15.0The buf.slice() method has been deprecated.
v7.1.0, v6.9.2Coercing the offsets to integers now handles values outside the 32-bit integer range properly.
v7.0.0All offsets are now coerced to integers before doing any calculations with them.
v0.3.0自 v0.3.0 版本开始新增
  • start integer Where the new Buffer will start. Default: 0.
  • end integer Where the new Buffer will end (not inclusive). Default: buf.length.
  • Returns: Buffer
稳定级别:0 - Deprecated: Use `buf.subarray` instead.

Returns a new Buffer that references the same memory as the original, but offset and cropped by the start and end indices.

This method is not compatible with the Uint8Array.prototype.slice(), which is a superclass of Buffer. To copy the slice, use Uint8Array.prototype.slice().

MJS
CJS

M buf.swap16()

自 v5.10.0 版本开始新增

  • Returns: Buffer A reference to buf.

Interprets buf as an array of unsigned 16-bit integers and swaps the byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length is not a multiple of 2.

MJS
CJS

One convenient use of buf.swap16() is to perform a fast in-place conversion between UTF-16 little-endian and UTF-16 big-endian:

MJS
CJS

M buf.swap32()

自 v5.10.0 版本开始新增

  • Returns: Buffer A reference to buf.

Interprets buf as an array of unsigned 32-bit integers and swaps the byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length is not a multiple of 4.

MJS
CJS

M buf.swap64()

自 v6.3.0 版本开始新增

  • Returns: Buffer A reference to buf.

Interprets buf as an array of 64-bit numbers and swaps byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length is not a multiple of 8.

MJS
CJS

M buf.toJSON()

自 v0.9.2 版本开始新增

Returns a JSON representation of buf. JSON.stringify() implicitly calls this function when stringifying a Buffer instance.

Buffer.from() accepts objects in the format returned from this method. In particular, Buffer.from(buf.toJSON()) works like Buffer.from(buf).

MJS
CJS

M buf.toString([encoding[, start[, end]]])

自 v0.1.90 版本开始新增

  • encoding string The character encoding to use. Default: 'utf8'.
  • start integer The byte offset to start decoding at. Default: 0.
  • end integer The byte offset to stop decoding at (not inclusive). Default: buf.length.
  • Returns: string

Decodes buf to a string according to the specified character encoding in encoding. start and end may be passed to decode only a subset of buf.

If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8, then each invalid byte is replaced with the replacement character U+FFFD.

The maximum length of a string instance (in UTF-16 code units) is available as buffer.constants.MAX_STRING_LENGTH.

MJS
CJS

M buf.values()

自 v1.1.0 版本开始新增

Creates and returns an iterator for buf values (bytes). This function is called automatically when a Buffer is used in a for..of statement.

MJS
CJS

M buf.write(string[, offset[, length]][, encoding])

自 v0.1.90 版本开始新增

  • string string String to write to buf.
  • offset integer Number of bytes to skip before starting to write string. Default: 0.
  • length integer Maximum number of bytes to write (written bytes will not exceed buf.length - offset). Default: buf.length - offset.
  • encoding string The character encoding of string. Default: 'utf8'.
  • Returns: integer Number of bytes written.

Writes string to buf at offset according to the character encoding in encoding. The length parameter is the number of bytes to write. If buf did not contain enough space to fit the entire string, only part of string will be written. However, partially encoded characters will not be written.

MJS
CJS

M buf.writeBigInt64BE(value[, offset])

自 v12.0.0, v10.20.0 版本开始新增

  • value bigint Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as big-endian.

value is interpreted and written as a two's complement signed integer.

MJS
CJS

M buf.writeBigInt64LE(value[, offset])

自 v12.0.0, v10.20.0 版本开始新增

  • value bigint Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as little-endian.

value is interpreted and written as a two's complement signed integer.

MJS
CJS

M buf.writeBigUInt64BE(value[, offset])

历史
版本历史变更
v14.10.0, v12.19.0This function is also available as `buf.writeBigUint64BE()`.
v12.0.0, v10.20.0自 v12.0.0, v10.20.0 版本开始新增
  • value bigint Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as big-endian.

This function is also available under the writeBigUint64BE alias.

MJS
CJS

M buf.writeBigUInt64LE(value[, offset])

历史
版本历史变更
v14.10.0, v12.19.0This function is also available as `buf.writeBigUint64LE()`.
v12.0.0, v10.20.0自 v12.0.0, v10.20.0 版本开始新增
  • value bigint Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as little-endian

MJS
CJS

This function is also available under the writeBigUint64LE alias.

M buf.writeDoubleBE(value[, offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • value number Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as big-endian. The value must be a JavaScript number. Behavior is undefined when value is anything other than a JavaScript number.

MJS
CJS

M buf.writeDoubleLE(value[, offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • value number Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 8. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as little-endian. The value must be a JavaScript number. Behavior is undefined when value is anything other than a JavaScript number.

MJS
CJS

M buf.writeFloatBE(value[, offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • value number Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as big-endian. Behavior is undefined when value is anything other than a JavaScript number.

MJS
CJS

M buf.writeFloatLE(value[, offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • value number Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as little-endian. Behavior is undefined when value is anything other than a JavaScript number.

MJS
CJS

M buf.writeInt8(value[, offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.0自 v0.5.0 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset. value must be a valid signed 8-bit integer. Behavior is undefined when value is anything other than a signed 8-bit integer.

value is interpreted and written as a two's complement signed integer.

MJS
CJS

M buf.writeInt16BE(value[, offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as big-endian. The value must be a valid signed 16-bit integer. Behavior is undefined when value is anything other than a signed 16-bit integer.

The value is interpreted and written as a two's complement signed integer.

MJS
CJS

M buf.writeInt16LE(value[, offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as little-endian. The value must be a valid signed 16-bit integer. Behavior is undefined when value is anything other than a signed 16-bit integer.

The value is interpreted and written as a two's complement signed integer.

MJS
CJS

M buf.writeInt32BE(value[, offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as big-endian. The value must be a valid signed 32-bit integer. Behavior is undefined when value is anything other than a signed 32-bit integer.

The value is interpreted and written as a two's complement signed integer.

MJS
CJS

M buf.writeInt32LE(value[, offset])

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as little-endian. The value must be a valid signed 32-bit integer. Behavior is undefined when value is anything other than a signed 32-bit integer.

The value is interpreted and written as a two's complement signed integer.

MJS
CJS

M buf.writeIntBE(value, offset, byteLength)

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.
  • byteLength integer Number of bytes to write. Must satisfy 0 < byteLength <= 6.
  • Returns: integer offset plus the number of bytes written.

Writes byteLength bytes of value to buf at the specified offset as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than a signed integer.

MJS
CJS

M buf.writeIntLE(value, offset, byteLength)

历史
版本历史变更
v10.0.0Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore.
v0.11.15自 v0.11.15 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.
  • byteLength integer Number of bytes to write. Must satisfy 0 < byteLength <= 6.
  • Returns: integer offset plus the number of bytes written.

Writes byteLength bytes of value to buf at the specified offset as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than a signed integer.

MJS
CJS

M buf.writeUInt8(value[, offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.writeUint8()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.0自 v0.5.0 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset. value must be a valid unsigned 8-bit integer. Behavior is undefined when value is anything other than an unsigned 8-bit integer.

This function is also available under the writeUint8 alias.

MJS
CJS

M buf.writeUInt16BE(value[, offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.writeUint16BE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as big-endian. The value must be a valid unsigned 16-bit integer. Behavior is undefined when value is anything other than an unsigned 16-bit integer.

This function is also available under the writeUint16BE alias.

MJS
CJS

M buf.writeUInt16LE(value[, offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.writeUint16LE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as little-endian. The value must be a valid unsigned 16-bit integer. Behavior is undefined when value is anything other than an unsigned 16-bit integer.

This function is also available under the writeUint16LE alias.

MJS
CJS

M buf.writeUInt32BE(value[, offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.writeUint32BE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as big-endian. The value must be a valid unsigned 32-bit integer. Behavior is undefined when value is anything other than an unsigned 32-bit integer.

This function is also available under the writeUint32BE alias.

MJS
CJS

M buf.writeUInt32LE(value[, offset])

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.writeUint32LE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
  • Returns: integer offset plus the number of bytes written.

Writes value to buf at the specified offset as little-endian. The value must be a valid unsigned 32-bit integer. Behavior is undefined when value is anything other than an unsigned 32-bit integer.

This function is also available under the writeUint32LE alias.

MJS
CJS

M buf.writeUIntBE(value, offset, byteLength)

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.writeUintBE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.
  • byteLength integer Number of bytes to write. Must satisfy 0 < byteLength <= 6.
  • Returns: integer offset plus the number of bytes written.

Writes byteLength bytes of value to buf at the specified offset as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than an unsigned integer.

This function is also available under the writeUintBE alias.

MJS
CJS

M buf.writeUIntLE(value, offset, byteLength)

历史
版本历史变更
v14.9.0, v12.19.0This function is also available as `buf.writeUintLE()`.
v10.0.0Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore.
v0.5.5自 v0.5.5 版本开始新增
  • value integer Number to be written to buf.
  • offset integer Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.
  • byteLength integer Number of bytes to write. Must satisfy 0 < byteLength <= 6.
  • Returns: integer offset plus the number of bytes written.

Writes byteLength bytes of value to buf at the specified offset as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than an unsigned integer.

This function is also available under the writeUintLE alias.

MJS
CJS

M new Buffer(array)

历史
版本历史变更
v10.0.0Calling this constructor emits a deprecation warning when run from code outside the `node_modules` directory.
v7.2.1Calling this constructor no longer emits a deprecation warning.
v7.0.0Calling this constructor emits a deprecation warning now.
v6.0.0自 v6.0.0 版本开始新增
稳定级别:0 - Deprecated: Use `Buffer.from(array)` instead.
  • array integer[] An array of bytes to copy from.

See Buffer.from(array).

M new Buffer(arrayBuffer[, byteOffset[, length]])

历史
版本历史变更
v10.0.0Calling this constructor emits a deprecation warning when run from code outside the `node_modules` directory.
v7.2.1Calling this constructor no longer emits a deprecation warning.
v7.0.0Calling this constructor emits a deprecation warning now.
v6.0.0The `byteOffset` and `length` parameters are supported now.
v6.0.0自 v6.0.0 版本开始新增
稳定级别:0 - Deprecated: Use [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`] > instead.

See Buffer.from(arrayBuffer[, byteOffset[, length]]).

M new Buffer(buffer)

历史
版本历史变更
v10.0.0Calling this constructor emits a deprecation warning when run from code outside the `node_modules` directory.
v7.2.1Calling this constructor no longer emits a deprecation warning.
v7.0.0Calling this constructor emits a deprecation warning now.
v6.0.0自 v6.0.0 版本开始新增
稳定级别:0 - Deprecated: Use `Buffer.from(buffer)` instead.

See Buffer.from(buffer).

M new Buffer(size)

历史
版本历史变更
v10.0.0Calling this constructor emits a deprecation warning when run from code outside the `node_modules` directory.
v8.0.0The `new Buffer(size)` will return zero-filled memory by default.
v7.2.1Calling this constructor no longer emits a deprecation warning.
v7.0.0Calling this constructor emits a deprecation warning now.
v6.0.0自 v6.0.0 版本开始新增
稳定级别:0 - Deprecated: Use `Buffer.alloc()`][] instead (also see [`Buffer.allocUnsafe()`).
  • size integer The desired length of the new Buffer.

See Buffer.alloc() and Buffer.allocUnsafe(). This variant of the constructor is equivalent to Buffer.alloc().

M new Buffer(string[, encoding])

历史
版本历史变更
v10.0.0Calling this constructor emits a deprecation warning when run from code outside the `node_modules` directory.
v7.2.1Calling this constructor no longer emits a deprecation warning.
v7.0.0Calling this constructor emits a deprecation warning now.
v6.0.0自 v6.0.0 版本开始新增
稳定级别:0 - Deprecated: Use [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] instead.
  • string string String to encode.
  • encoding string The encoding of string. Default: 'utf8'.

See Buffer.from(string[, encoding]).

M node:buffer module APIs

While, the Buffer object is available as a global, there are additional Buffer-related APIs that are available only via the node:buffer module accessed using require('node:buffer').

M buffer.atob(data)

自 v15.13.0 版本开始新增

稳定级别:3 - Legacy. Use `Buffer.from(data, 'base64')` instead.
  • data any The Base64-encoded input string.

Decodes a string of Base64-encoded data into bytes, and encodes those bytes into a string using Latin-1 (ISO-8859-1).

The data may be any JavaScript-value that can be coerced into a string.

This function is only provided for compatibility with legacy web platform APIs and should never be used in new code, because they use strings to represent binary data and predate the introduction of typed arrays in JavaScript. For code running using Node.js APIs, converting between base64-encoded strings and binary data should be performed using Buffer.from(str, 'base64') and buf.toString('base64').

M buffer.btoa(data)

自 v15.13.0 版本开始新增

稳定级别:3 - Legacy. Use `buf.toString('base64')` instead.
  • data any An ASCII (Latin1) string.

Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes into a string using Base64.

The data may be any JavaScript-value that can be coerced into a string.

This function is only provided for compatibility with legacy web platform APIs and should never be used in new code, because they use strings to represent binary data and predate the introduction of typed arrays in JavaScript. For code running using Node.js APIs, converting between base64-encoded strings and binary data should be performed using Buffer.from(str, 'base64') and buf.toString('base64').

M buffer.INSPECT_MAX_BYTES

自 v0.5.4 版本开始新增

Returns the maximum number of bytes that will be returned when buf.inspect() is called. This can be overridden by user modules. See util.inspect() for more details on buf.inspect() behavior.

M buffer.kMaxLength

自 v3.0.0 版本开始新增

  • integer The largest size allowed for a single Buffer instance.

An alias for buffer.constants.MAX_LENGTH.

M buffer.kStringMaxLength

自 v3.0.0 版本开始新增

  • integer The largest length allowed for a single string instance.

An alias for buffer.constants.MAX_STRING_LENGTH.

M buffer.resolveObjectURL(id)

自 v16.7.0 版本开始新增

稳定级别:1 - Experimental
  • id string A 'blob:nodedata:... URL string returned by a prior call to URL.createObjectURL().
  • Returns: Blob

Resolves a 'blob:nodedata:...' an associated Blob object registered using a prior call to URL.createObjectURL().

M buffer.transcode(source, fromEnc, toEnc)

历史
版本历史变更
v8.0.0The `source` parameter can now be a `Uint8Array`.
v7.1.0自 v7.1.0 版本开始新增

Re-encodes the given Buffer or Uint8Array instance from one character encoding to another. Returns a new Buffer instance.

Throws if the fromEnc or toEnc specify invalid character encodings or if conversion from fromEnc to toEnc is not permitted.

Encodings supported by buffer.transcode() are: 'ascii', 'utf8', 'utf16le', 'ucs2', 'latin1', and 'binary'.

The transcoding process will use substitution characters if a given byte sequence cannot be adequately represented in the target encoding. For instance:

MJS
CJS

Because the Euro () sign is not representable in US-ASCII, it is replaced with ? in the transcoded Buffer.

C SlowBuffer

自 v6.0.0 版本开始弃用

稳定级别:0 - Deprecated: Use `Buffer.allocUnsafeSlow()` instead.

See Buffer.allocUnsafeSlow(). This was never a class in the sense that the constructor always returned a Buffer instance, rather than a SlowBuffer instance.

M new SlowBuffer(size)

自 v6.0.0 版本开始弃用

稳定级别:0 - Deprecated: Use `Buffer.allocUnsafeSlow()` instead.
  • size integer The desired length of the new SlowBuffer.

See Buffer.allocUnsafeSlow().

Buffer constants

自 v8.2.0 版本开始新增

M buffer.constants.MAX_LENGTH
历史
版本历史变更
v15.0.0Value is changed to 2<sup>32</sup> on 64-bit architectures.
v14.0.0Value is changed from 2<sup>31</sup> - 1 to 2<sup>32</sup> - 1 on 64-bit architectures.
v8.2.0自 v8.2.0 版本开始新增
  • integer The largest size allowed for a single Buffer instance.

On 32-bit architectures, this value currently is 230 - 1 (about 1 GiB).

On 64-bit architectures, this value currently is 232 (about 4 GiB).

It reflects v8::TypedArray::kMaxLength under the hood.

This value is also available as buffer.kMaxLength.

M buffer.constants.MAX_STRING_LENGTH

自 v8.2.0 版本开始新增

  • integer The largest length allowed for a single string instance.

Represents the largest length that a string primitive can have, counted in UTF-16 code units.

This value may depend on the JS engine that is being used.

M Buffer.from(), Buffer.alloc(), and Buffer.allocUnsafe()

In versions of Node.js prior to 6.0.0, Buffer instances were created using the Buffer constructor function, which allocates the returned Buffer differently based on what arguments are provided:

  • Passing a number as the first argument to Buffer() (e.g. new Buffer(10)) allocates a new Buffer object of the specified size. Prior to Node.js 8.0.0, the memory allocated for such Buffer instances is not initialized and can contain sensitive data. Such Buffer instances must be subsequently initialized by using either buf.fill(0) or by writing to the entire Buffer before reading data from the Buffer. While this behavior is intentional to improve performance, development experience has demonstrated that a more explicit distinction is required between creating a fast-but-uninitialized Buffer versus creating a slower-but-safer Buffer. Since Node.js 8.0.0, Buffer(num) and new Buffer(num) return a Buffer with initialized memory.
  • Passing a string, array, or Buffer as the first argument copies the passed object's data into the Buffer.
  • Passing an ArrayBuffer or a SharedArrayBuffer returns a Buffer that shares allocated memory with the given array buffer.

Because the behavior of new Buffer() is different depending on the type of the first argument, security and reliability issues can be inadvertently introduced into applications when argument validation or Buffer initialization is not performed.

For example, if an attacker can cause an application to receive a number where a string is expected, the application may call new Buffer(100) instead of new Buffer("100"), leading it to allocate a 100 byte buffer instead of allocating a 3 byte buffer with content "100". This is commonly possible using JSON API calls. Since JSON distinguishes between numeric and string types, it allows injection of numbers where a naively written application that does not validate its input sufficiently might expect to always receive a string. Before Node.js 8.0.0, the 100 byte buffer might contain arbitrary pre-existing in-memory data, so may be used to expose in-memory secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot occur because the data is zero-filled. However, other attacks are still possible, such as causing very large buffers to be allocated by the server, leading to performance degradation or crashing on memory exhaustion.

To make the creation of Buffer instances more reliable and less error-prone, the various forms of the new Buffer() constructor have been deprecated and replaced by separate Buffer.from(), Buffer.alloc(), and Buffer.allocUnsafe() methods.

Developers should migrate all existing uses of the new Buffer() constructors to one of these new APIs.

Buffer instances returned by Buffer.allocUnsafe() and Buffer.from(array) may be allocated off a shared internal memory pool if size is less than or equal to half Buffer.poolSize. Instances returned by Buffer.allocUnsafeSlow() never use the shared internal memory pool.

The --zero-fill-buffers command-line option

自 v5.10.0 版本开始新增

Node.js can be started using the --zero-fill-buffers command-line option to cause all newly-allocated Buffer instances to be zero-filled upon creation by default. Without the option, buffers created with Buffer.allocUnsafe(), Buffer.allocUnsafeSlow(), and new SlowBuffer(size) are not zero-filled. Use of this flag can have a measurable negative impact on performance. Use the --zero-fill-buffers option only when necessary to enforce that newly allocated Buffer instances cannot contain old data that is potentially sensitive.

BASH

What makes Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() "unsafe"?

When calling Buffer.allocUnsafe() and Buffer.allocUnsafeSlow(), the segment of allocated memory is uninitialized (it is not zeroed-out). While this design makes the allocation of memory quite fast, the allocated segment of memory might contain old data that is potentially sensitive. Using a Buffer created by Buffer.allocUnsafe() without completely overwriting the memory can allow this old data to be leaked when the Buffer memory is read.

While there are clear performance advantages to using Buffer.allocUnsafe(), extra care must be taken in order to avoid introducing security vulnerabilities into an application.