Creates a zero-length Buffer.
Creates a new Buffer with length bytes. The contents are initialized to 0.
The desired length of the new Buffer.
Creates a new Buffer copied from arrayLike. TypedArray will be treated as an Array.
An array of bytes in the range 0 – 255. Array entries outside that range will be truncated to fit into it.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.of(21, 31)
console.log(buf1.toString('hex')) // Prints: 151f
const buf2 = new Buffer(new Uint16Array([0x1234, 0x5678]))
console.log(buf2.toString('hex')) // Prints: 3478
const buf3 = Buffer.from('0102', 'hex')
const buf4 = new Buffer(buf3)
buf3[0] = 0x03
console.log(buf3.toString('hex')) // Prints: 0302
console.log(buf4.toString('hex')) // Prints: 0102
})()
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.
An ArrayBuffer or SharedArrayBuffer, for example the .buffer property of a TypedArray.
OptionalbyteOffset: numberIndex of first byte to expose. Default: 0.
Optionallength: numberNumber of bytes to expose. Default: arrayBuffer.byteLength - byteOffset.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const uint16 = new Uint16Array([5000, 4000])
const buf = Buffer.from(uint16.buffer) // Shares memory with `uint16`.
console.log(buf.toString('hex')) // Prints: 8813a00f
uint16[1] = 6000
console.log(buf.toString('hex')) // Prints: 88137017
})()
StaticofThe static method creates a new Buffer from a variable number of arguments.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.of(1)
console.log(buf1.toString('hex')) // Prints: 01
const buf2 = Buffer.of("1", "2", "3")
console.log(buf2.toString('hex')) // Prints: 010203
const buf3 = Buffer.of(undefined)
console.log(buf3.toString('hex')) // Prints: 00
})()
StaticallocAllocates a new Buffer of size bytes. If fill is undefined, the Buffer will be zero-filled.
The desired length of the new Buffer.
Optionalfill: number | Buffer | Uint8Array<ArrayBufferLike>A value to pre-fill the new Buffer with. Default: 0.
Allocates a new Buffer of size bytes. If fill is undefined, the Buffer will be zero-filled.
The desired length of the new Buffer.
A value to pre-fill the new Buffer with. Default: 0.
Optionalencoding: The encoding of fill. Default: 'utf8'.
If fill is specified, the allocated Buffer will be initialized by calling buf.fill(fill).
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.alloc(5, 'a')
console.log(buf.toString('hex')) // Prints: 6161616161
})()
If both fill and encoding are specified, the allocated Buffer will be initialized by calling buf.fill(fill, encoding).
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64')
console.log(buf.toString('hex')) // Prints: 68656c6c6f20776f726c64
})()
StaticallocAllocates a new Buffer of size bytes. The contents are initialized to 0. This is equivalent to calling new Buffer(size).
The desired length of the new Buffer.
StaticallocAllocates a new Buffer of size bytes. The contents are initialized to 0. This is equivalent to calling new Buffer(size).
The desired length of the new Buffer.
StaticbyteReturns .byteLength if value is a Buffer/DataView/TypedArray/ArrayBuffer/SharedArrayBuffer.
A value to calculate the length of bytes.
The number of bytes contained within value.
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 method assumes value is valid. 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.
A value to calculate the length of bytes.
Optionalencoding: The encoding of string. Default: 'utf8'.
The number of bytes contained within string.
StaticcompareCompares buf1 to buf2, typically for the purpose of sorting arrays of Buffer instances. This is equivalent to calling Buffer#compare.
Either -1, 0, or 1, depending on the result of the comparison. See Buffer#compare for details.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('1234')
const buf2 = Buffer.from('0123')
console.log([buf1, buf2].sort(Buffer.compare).map(buf => buf.toString('hex')))
// Prints: ['30313233', '31323334']
// (This result is equal to: [buf2, buf1].)
console.log([buf2, buf1].sort(Buffer.compare).map(buf => buf.toString('hex')))
// Prints: ['30313233', '31323334']
})()
StaticconcatReturns 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.
List of Buffer or Uint8Array instances to concatenate.
OptionaltotalLength: numberTotal length of the Buffer instances in list when concatenated.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.alloc(4)
const buf2 = Buffer.alloc(5)
const buf3 = Buffer.alloc(6)
const totalLength = buf1.length + buf2.length + buf3.length
console.log(totalLength) // Prints: 15
const bufA = Buffer.concat([buf1, buf2, buf3], totalLength)
console.log(bufA.toString('hex'))
// Prints: 000000000000000000000000000000
console.log(bufA.length) // Prints: 15
})()
StaticcopyCopies the underlying memory of view into a new Buffer.
The TypedArray to copy.
The starting offset within view. Default: 0.
Optionallength: numberThe number of elements from view to copy. Default: view.length - offset.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const u16 = new Uint16Array([0, 0xffff])
const buf = Buffer.copyBytesFrom(u16, 1, 1)
u16[1] = 0
console.log(buf.length) // Prints: 2
console.log(buf.toString('hex')) // Prints: ffff
})()
Staticequalsture if buf1 and buf2 have the same byte length and contents, or false otherwise.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
console.log(Buffer.equals(Buffer.of(1, 2), Buffer.from('0102', 'hex'))) // true
console.log(Buffer.equals(Buffer.from(Uint8Array.of(1, 2)), Buffer.from('0102', 'hex'))) // true
console.log(Buffer.equals(Uint8Array.of(1, 2), Buffer.from('0102', 'hex'))) // false
console.log(Buffer.equals(1, Uint8Array.of(1, 2))) // false
console.log(Buffer.equals('', new Buffer(2))) // false
})()
StaticfromAllocates 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 an Array. To create a Buffer from the bytes backing a TypedArray, use Buffer.copyBytesFrom.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])
console.log(buf1.toString('hex')) // Prints: 627566666572
const u16 = new Uint16Array([0x0001, 0x0002])
const buf2 = Buffer.from(u16)
console.log(buf2.toString('hex')) // Prints: 0102
})()
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.
The optional byteOffset and length arguments specify a memory range within the arrayBuffer that will be shared by the Buffer.
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:
An ArrayBuffer, SharedArrayBuffer, for example the .buffer property of a TypedArray.
OptionalbyteOffset: numberIndex of first byte to expose. Default: 0.
Optionallength: numberNumber of bytes to expose. Default: arrayBuffer.byteLength - byteOffset.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const arr = new Uint16Array(2)
arr[0] = 5000
arr[1] = 4000
const buf = Buffer.from(arr.buffer) // Shares memory with `arr`
console.log(buf.toString('hex')) // Prints: 8813a00f
// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000
console.log(buf.toString('hex')) // Prints: 88137017
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const ab = new ArrayBuffer(10)
const buf = Buffer.from(ab, 0, 2)
console.log(buf.length) // Prints: 2
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]) // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2) // 2 elements
console.log(arrA.buffer === arrB.buffer) // true
const buf = Buffer.from(arrB.buffer)
console.log(buf.toString('hex')) // Prints: 63646566
})()
Copies the passed buffer data onto a new Buffer instance.
An existing Buffer or Uint8Array from which to copy data.
Restore a Buffer in the format returned from Buffer#toJSON.
A JSON object returned from Buffer#toJSON.
Creates a new Buffer containing string. The encoding parameter identifies the character encoding to be used when converting string into bytes.
A string to encode.
Optionalencoding: The encoding of string. Default: 'utf8'.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('this is a tést')
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex')
console.log(buf1.toString()) // Prints: this is a tést
console.log(buf2.toString()) // Prints: this is a tést
console.log(buf1.toString('latin1')) // Prints: this is a tést
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.from(new String('this is a test'))
console.log(buf.toString('hex')) // Prints: 7468697320697320612074657374
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
class Foo {
[Symbol.toPrimitive]() {
return 'this is a test';
}
}
const buf = Buffer.from(new Foo(), 'utf8')
console.log(buf.toString('hex')) // Prints: 7468697320697320612074657374
})()
StaticfromCreates a new Buffer that encoded from the provided base64 using 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.
A string to encode.
StaticfromCreates a new Buffer that encoded from the provided base64 using base64url encoding. 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.
A string to encode.
StaticfromCreates a new Buffer that encoded from the provided hex using hexadecimal encoding. Data truncation may occur when encode strings that do not exclusively consist of an even number of hexadecimal characters.
A string to encode.
StaticfromCreates a new Buffer that encoded from the provided latin1 using Latin-1 encoding. 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.
A string to encode.
StaticfromCreates a new Buffer that encoded from the provided string. The encoding parameter identifies the character encoding to be used when converting string into bytes.
A string to encode.
The encoding of string. Default: 'utf8'.
StaticfromCreates a new Buffer that encoded from the provided ucs2 using UCS-2 encoding. 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.
A string to encode.
StaticfromCreates a new Buffer that encoded from the provided utf8 using UTF-8 encoding. Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8. This is the default character encoding.
A string to encode.
This method based on the TextEncoder API.
StaticfromCreates a Buffer from view without copying the underlying memory.
The ArrayBufferView to create a Buffer from.
Optionaloffset: numberThe starting offset within view. Default: 0.
Optionallength: numberThe number of elements from view to copy. Default: view.length - offset.
Staticistrue if obj is a Buffer, false otherwise.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
console.log(Buffer.isBuffer(Buffer.alloc(10))) // true
console.log(Buffer.isBuffer(Buffer.from('foo'))) // true
console.log(Buffer.isBuffer('a string')) // false
console.log(Buffer.isBuffer([])) // false
console.log(Buffer.isBuffer(new Uint8Array(1024))) // false
})()
StaticisA character encoding name to check.
true if encoding is the name of a supported character encoding, or false otherwise.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
console.log(Buffer.isEncoding('utf8')) // true
console.log(Buffer.isEncoding('hex')) // true
console.log(Buffer.isEncoding('utf/8')) // false
console.log(Buffer.isEncoding('')) // false
})()
StaticiterIteratively unpack from the buf according to the format string format. This method returns an iterator which will read equally sized chunks from the buf until remaining contents smaller then the size required by the format, as reflected by Buffer.packCalcSize.
A Buffer to unpack from.
A format string. Please refer to Buffer.packParseFormat for more information.
StaticpackCreates a new Buffer containing the vals packed according to the format string format. The arguments must match the vals required by the format exactly.
A format string. Please refer to Buffer.packParseFormat for more information.
Values to pack.
Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.
Please refer to Python struct — Interpret bytes as packed binary data for more information.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
console.log(Buffer.pack('>h', 1023).toString('hex')) // Prints: 03ff
console.log(Buffer.pack('<h', 1023).toString('hex')) // Prints: ff03
console.log(Buffer.pack('>bhl', 1, 2, 3).toString('hex')) // Prints: 01000200000003
})()
Pack vals into buf according to the format string format. The arguments must match the vals required by the format exactly. The buf’s size in bytes must larger then the size required by the format, as reflected by Buffer.packCalcSize.
A Buffer to pack into.
A format string. Please refer to Buffer.packParseFormat for more information.
Values to pack.
Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.alloc(3)
Buffer.pack(buf1, '>h', 0x0102)
console.log(buf1.toString('hex')) // Prints: 010200
const buf2 = Buffer.alloc(3)
Buffer.pack(buf2.subarray(1), '>h', 0x0102) // struct.pack_into
console.log(buf2.toString('hex')) // Prints: 000102
})()
StaticpackReturn the required size corresponding to the format string formatOrItems.
A format string or parsed items return by items of Buffer.packParseFormat.
Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
console.log(Buffer.packCalcSize('>bhl')) // Prints: 7
console.log(Buffer.packCalcSize('>ci')) // Prints: 5
console.log(Buffer.packCalcSize('>ic')) // Prints: 5
console.log(Buffer.packCalcSize('>lhl')) // Prints: 10
console.log(Buffer.packCalcSize('>llh')) // Prints: 10
console.log(Buffer.packCalcSize('>llh0l')) // Prints: 10
console.log(Buffer.packCalcSize('<qh6xq')) // Prints: 24
console.log(Buffer.packCalcSize('<qqh6x')) // Prints: 24
})()
StaticpackParse a format string format. This is a internal method used by Buffer.packCalcSize, Buffer.pack, Buffer.unpack and Buffer.iterUnpack.
A format string.
The first character of the format string can be used to indicate the byte order, size and alignment of the packed data, according to the following table:
| Character | Byte order | Size | Alignment |
|---|---|---|---|
@ |
native | standard | none |
= |
native | standard | none |
< |
little-endian | standard | none |
> |
big-endian | standard | none |
! |
big-endian | standard | none |
If the first character is not one of these, @ is assumed.
Format characters have the following meaning; the conversion between C and Python values should be obvious given their types. The ‘Size’ column refers to the size of the packed value in bytes.
| Format | C Type | JavaScript Type | Size | Notes |
|---|---|---|---|---|
x |
pad byte | no value | 1 | (1) |
c |
char |
Buffer of length 1 | 1 | |
b |
signed char |
number | 1 | |
B |
unsigned char |
number | 1 | |
? |
_Bool |
boolean | 1 | (2) |
h |
short |
number | 2 | |
H |
unsigned short |
number | 2 | |
i |
int |
number | 4 | |
I |
unsigned int |
number | 4 | |
l |
long |
number | 4 | |
L |
unsigned long |
number | 4 | |
q |
long long |
BigInt of 64 bits | 8 | |
Q |
unsigned long long |
BigInt of 64 bits | 8 | |
e |
(3) | number | 2 | (4) |
f |
float |
number | 4 | (4) |
d |
double |
number | 8 | (4) |
s |
char[] |
Buffer | (5) | |
p |
char[] |
Buffer | (6) |
Notes:
x inserts one NUL byte (0x00).? conversion code corresponds to the _Bool type defined by C standards since C99. It is represented by one byte.6.1e-05 and 6.5e+04 at full precision. This type is not widely supported by C compilers: on a typical machine, an unsigned short can be used for storage, but not for math operations. See the Wikipedia page on the half-precision floating-point format for more information.f, d and e conversion codes, the packed representation uses the IEEE 754 binary32, binary64 or binary16 format (for f, d or e respectively), regardless of the floating-point format used by the platform.s format character, the count is interpreted as the length of the bytes, not a repeat count like for the other format characters; for example, 10s means a single 10-byte Buffer mapping to or from a single Buffer, while 10c means 10 separate one byte character elements (e.g., cccccccccc) mapping to or from ten different Buffer. (See Examples for a concrete demonstration of the difference.) If a count is not given, it defaults to 1. For packing, the Buffer is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting Buffer always has exactly the specified number of bytes. As a special case, 0s means a single, empty Buffer.p format character encodes a "Pascal string", meaning a short variable-length string stored in a fixed number of bytes, given by the count. The first byte stored is the length of the string, or 255, whichever is smaller. The bytes of the string follow. If the string passed in to pack() is too long (longer than the count minus 1), only the leading count-1 bytes of the string are stored. If the string is shorter than count-1, it is padded with null bytes so that exactly count bytes in all are used. Note that for unpack(), the p format character consumes count bytes, but that the string returned can never contain more than 255 bytes.A format character may be preceded by an integral repeat count. For example, the format string 4h means exactly the same as hhhh.
For the ? format character, the return value is either true or false. When packing, the truth value of the argument object is used. Either 0 or 1 in the bool representation will be packed, and any non-zero value will be true when unpacking.
StatictoDecodes buf to a string according to the Base64 character encoding.
The buffer to decode.
StatictoDecodes buf to a string according to the Base64 URL character encoding.
The buffer to decode.
StatictoDecodes buf to a string according to the hexadecimal character encoding.
The buffer to decode.
StatictoDecodes buf to a string according to the Latin1 character encoding. 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.
The buffer to decode.
StatictoDecodes buf to a string according to the UCS-2 character encoding.
The buffer to decode.
StatictoDecodes buf to a string according to the UTF-8 character encoding.
The buffer to decode.
This method based on the TextDecoder API.
StaticunpackUnpack from the buf (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buf’s size in bytes must larger then the size required by the format, as reflected by Buffer.packCalcSize.
A Buffer to unpack from.
A format string. Please refer to Buffer.packParseFormat for more information.
Implements the iterable protocol and allows Buffer to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns an array iterator object that yields the value of each index in the Buffer.
A new iterable iterator object that yields the value of each index in the Buffer.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.of(10, 20, 30, 40, 50)
for (const n of buf1) console.log(n)
const values = buf1[Symbol.iterator]()
console.log(values.next().value) // Expected output: 10
console.log(values.next().value) // Expected output: 20
console.log(values.next().value) // Expected output: 30
console.log(values.next().value) // Expected output: 40
console.log(values.next().value) // Expected output: 50
})()
Takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the Buffer.
Zero-based index of the Buffer element to be returned, converted to an integer. Negative index counts back from the end of the Buffer — if index < 0, index + array.length is accessed.
The element in the Buffer matching the given index. Always returns undefined if index < -array.length or index >= array.length without attempting to access the corresponding property.
The method shallow copies part of this Buffer to another location in the same Buffer and returns this Buffer without modifying its length.
Zero-based index at which to copy the sequence to. This corresponds to where the element at start will be copied to, and all elements between start and end are copied to succeeding indices.
Zero-based index at which to start copying elements from.
Optionalend: numberZero-based index at which to end copying elements from. This method copies up to but not including end.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = new Buffer(8)
buf.set([1, 2, 3])
console.log(buf.toString('hex')) // Prints: 0102030000000000
buf.copyWithin(3, 0, 3)
console.log(buf.toString('hex')) // Prints: 0102030102030000
})()
Returns a new array iterator object that contains the key/value pairs for each index in the Buffer.
A new iterable iterator object.
Tests whether all elements in the Buffer pass the test implemented by the provided function.
A function to execute for each element in the Buffer. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:
value: The current element being processed in the Buffer.index: The index of the current element being processed in the Buffer.array: The Buffer every() was called upon.OptionalthisArg: anyA value to use as this when executing callbackFn.
true unless callbackFn returns a falsy value for a Buffer element, in which case false is immediately returned.
Creates a copy of a portion of a given Buffer, filtered down to just the elements from the given Buffer that pass the test implemented by the provided function.
A function to execute for each element in the Buffer. It should return a truthy value to keep the element in the resulting Buffer, and a falsy value otherwise. The function is called with the following arguments:
value: The current element being processed in the Buffer.index: The index of the current element being processed in the Buffer.array: The Buffer filter() was called upon.OptionalthisArg: anyA value to use as this when executing callbackFn.
A copy of the given Buffer containing just the elements that pass the test. If no elements pass the test, an empty Buffer is returned.
Returns the first element in the provided Buffer that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
A function to execute for each element in the Buffer. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
value: The current element being processed in the Buffer.index: The index of the current element being processed in the Buffer.array: The Buffer find() was called upon.OptionalthisArg: anyA value to use as this when executing callbackFn.
The first element in the Buffer that satisfies the provided testing function. Otherwise, undefined is returned.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
const buf = Buffer.of(4, 5, 8, 12)
console.log(buf.find(isPrime)) // Expected output: 5
})()
Returns the index of the first element in the Buffer that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
A function to execute for each element in the Buffer. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
value: The current element being processed in the Buffer.index: The index of the current element being processed in the Buffer.array: The Buffer findIndex() was called upon.OptionalthisArg: anyA value to use as this when executing callbackFn.
The index of the first element in the Buffer that passes the test. Otherwise, -1.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log(Buffer.of(4, 6, 8, 12).findIndex(isPrime)) // Expected output: -1
console.log(Buffer.of(4, 6, 7, 12).findIndex(isPrime)) // Expected output: 2
})()
Iterates the Buffer in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.
A function to execute for each element in the Buffer. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
value: The current element being processed in the Buffer.index: The index of the current element being processed in the Buffer.array: The Buffer find() was called upon.OptionalthisArg: anyA value to use as this when executing callbackFn.
The last (highest-index) element in the Buffer that satisfies the provided testing function; undefined if no matching element is found.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
const buf1 = Buffer.of(4, 6, 8, 12)
console.log(buf1.findLast(isPrime)) // Expected output: undefined
const buf2 = Buffer.of(4, 5, 7, 8, 9, 11, 12)
console.log(buf2.findLast(isPrime)) // Expected output: 11
})()
Iterates the Buffer in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
A function to execute for each element in the Buffer. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
value: The current element being processed in the Buffer.index: The index of the current element being processed in the Buffer.array: The Buffer findIndex() was called upon.OptionalthisArg: anyA value to use as this when executing callbackFn.
The index of the last (highest-index) element in the Buffer that passes the test. Otherwise -1 if no matching element is found.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log(Buffer.of(4, 6, 8, 12).findLastIndex(isPrime)) // Expected output: -1
console.log(Buffer.of(4, 5, 7, 8, 9, 11, 12).findLastIndex(isPrime)) // Expected output: 5
})()
Executes a provided function once for each Buffer element.
A function to execute for each element in the Buffer. Its return value is discarded. The function is called with the following arguments:
value: The current element being processed in the Buffer.index: The index of the current element being processed in the Buffer.array: The Buffer forEach() was called upon.OptionalthisArg: anyA value to use as this when executing callbackfn.
Creates and returns a new string by concatenating all of the elements in this Buffer, separated by commas or a specified separator string. If the Buffer has only one item, then that item will be returned without using the separator.
Optionalseparator: stringA string to separate each pair of adjacent elements of the Buffer. If omitted, the Buffer elements are separated with a comma ",".
A string with all Buffer elements joined. If buf.length is 0, the empty string is returned.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.of(1, 2, 3)
console.log(buf.join()) // Expected output: "1,2,3"
console.log(buf.join(" / ")) // Expected output: "1 / 2 / 3"
console.log(buf.join('')) // Expected output: "123"
})()
Returns a new array iterator object that contains the keys for each index in the Buffer.
A new iterable iterator object.
Creates a new Buffer populated with the results of calling a provided function on every element in the calling Buffer.
A function to execute for each element in the Buffer. Its return value is added as a single element in the new Buffer. The function is called with the following arguments:
value: The current element being processed in the Buffer.index: The index of the current element being processed in the Buffer.array: The Buffer map() was called upon.OptionalthisArg: anyA value to use as this when executing callbackfn.
A new Buffer with each element being the result of the callback function.
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
OptionalinitialValue: TIf initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
A function that accepts up to four arguments. The reduceRight method calls
the callbackfn function one time for each element in the array.
OptionalinitialValue: TIf initialValue is specified, it is used as the initial value to start
the accumulation. The first call to the callbackfn function provides this value as an argument
instead of an array value.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.of(10, 20, 30)
const result = buf.reduceRight((accumulator, currentValue) => `${accumulator}, ${currentValue}`)
console.log(result) // Expected output: "30, 20, 10"
})()
The method reverses a Buffer in place and returns the reference to the same Buffer, the first element now becoming the last, and the last element becoming the first. In other words, elements order in the Buffer will be turned towards the direction opposite to that previously stated.
Stores multiple values in the Buffer, reading input values from a specified array.
The array from which to copy values. All values from the source array are copied into the Buffer, unless the length of the source array plus the target offset exceeds the length of the Buffer, in which case an exception is thrown. If the source array is a Buffer, the two arrays may share the same underlying ArrayBuffer; the JavaScript engine will intelligently copy the source range of the buffer to the destination range.
Optionaloffset: numberThe offset into the Buffer at which to begin writing values from the source array. If this value is omitted, 0 is assumed (that is, the source array will overwrite values in the Buffer starting at index 0).
Returns a copy of a portion of a Buffer into a new Buffer object selected from start to end (end not included) where start and end represent the index of items in that buf. The original Buffer will not be modified.
Optionalstart: numberWhere the new Buffer will start. Default: 0.
Optionalend: numberWhere the new Buffer will end (not inclusive). Default: buf.length.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('1020304050', 'hex')
const buf2 = buf1.slice(1, 3)
buf1[1] = 0x60
console.log(buf1.toString('hex')) // Prints: 1060304050
console.log(buf2.toString('hex')) // Prints: 2030
})()
Tests whether at least one element in the Buffer passes the test implemented by the provided function. It returns true if, in the Buffer, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the Buffer.
A function to execute for each element in the Buffer. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:
value: The current element being processed in the Buffer.index: The index of the current element being processed in the Buffer.array: The Buffer some() was called upon.OptionalthisArg: anyA value to use as this when executing callbackFn.
false unless callbackFn returns a truthy value for a Buffer element, in which case true is immediately returned.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const isBiggerThan10 = (value, index, array) => value > 10
console.log(Buffer.of(2, 5, 8, 1, 4).some(isBiggerThan10)) // Expected output: false
console.log(Buffer.of(12, 5, 8, 1, 4).some(isBiggerThan10)) // Expected output: true
})()
The method sorts the elements of a Buffer in place and returns the reference to the same Buffer, now sorted.
OptionalcompareFn: (a: number, b: number) => anyA function that determines the order of the elements. The function is called with the following arguments:
a: The first element for comparison.b: The second element for comparison.
It should return a number where:a should come before b.a should come after b.NaN indicates that a and b are considered equal.
To memorize this, remember that (a, b) => a - b sorts numbers in ascending order. If omitted, the elements are sorted according to numeric value.The reference to the original Buffer, now sorted. Note that the Buffer is sorted in place, and no copy is made.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('03010204', 'hex')
buf1.sort()
console.log(buf1.toString('hex')) // Prints: 01020304
buf1.sort((a, b) => b - a)
console.log(buf1.toString('hex')) // Prints: 04030201
})()
Returns a new Buffer that references the same memory as the original, but offset and cropped by the start and end indexes.
Specifying end greater than buf.length will return the same result as that of end equal to buf.length.
Modifying the new Buffer slice will modify the memory in the original Buffer because the allocated memory of the two objects overlap.
Specifying negative indexes causes the slice to be generated relative to the end of buf rather than the beginning.
Optionalstart: numberWhere the new Buffer will start. Default: 0.
Optionalend: numberWhere the new Buffer will end (not inclusive). Default: buf.length.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.allocUnsafe(26)
for (let i = 0; i < 26; i++) buf1[i] = i + 97
const buf2 = buf1.subarray(0, 3)
console.log(buf2.toString('ascii', 0, buf2.length)) // Prints: abc
buf1[0] = 33
console.log(buf2.toString('ascii', 0, buf2.length)) // Prints: !bc
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.allocUnsafe(26)
for (let i = 0; i < 26; i++) buf1[i] = i + 97
const buf2 = buf1.subarray(0, 3)
console.log(buf2.toString('ascii', 0, buf2.length)) // Prints: abc
buf1[0] = 33
console.log(buf2.toString('ascii', 0, buf2.length)) // Prints: !bc
})()
Returns a string representing the elements of the Buffer. The elements are converted to strings using their toLocaleString methods and these strings are separated by a locale-specific string (such as a comma ",").
Optionallocales: string | string[]A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.
Optionaloptions: NumberFormatOptionsAn object with configuration properties. See Number.prototype.toLocaleString().
A string representing the elements of the Buffer.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.of(200, 50, 81, 12, 42)
console.log(buf.toLocaleString()) // Expected output: "200,50,81,12,42"
console.log(buf.toLocaleString('en-US')) // Expected output: "200,50,81,12,42"
console.log(buf.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' })) // Expected output: "¥200,¥50,¥81,¥12,¥42"
})()
Returns a new array iterator object that iterates the value of each item in the Buffer.
A new iterable iterator object.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.of(10, 20, 30, 40, 50)
for (const n of buf1.values()) console.log(n)
const values = buf1.values()
console.log(values.next().value) // Expected output: 10
console.log(values.next().value) // Expected output: 20
console.log(values.next().value) // Expected output: 30
console.log(values.next().value) // Expected output: 40
console.log(values.next().value) // Expected output: 50
})()
Calculates the Bitwise AND of all bytes in this. If this is empty, returns 0xFF. You can use Buffer#subarray to calculate the Bitwise AND of a subset of this.
The Bitwise AND of all bytes in buf.
The method Bitwise AND every bytes with other in place and returns this. If length of other is shorter than this, the remaining bytes in this will not be changed. If length of other is longer than this, the remaining bytes in other will be ignored.
A Buffer to Bitwise AND with.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('010203', 'hex')
const buf2 = Buffer.from('102030', 'hex')
console.log(buf1.and(buf2).toString('hex')) // Prints: 000000
console.log(buf1.toString('hex')) // Prints: 000000
})()
Creates an array of chunk Buffers which length is bytesPerChunk. If buf's contents can't be split evenly, the final chunk will be the remaining contents.
The length of each chunk
The new array of chunks.
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.
The optional targetStart, targetEnd, sourceStart, and sourceEnd arguments can be used to limit the comparison to specific ranges within target and buf respectively.
A Buffer or Uint8Array with which to compare buf.
The offset within target at which to begin comparison. Default: 0.
The offset within target at which to end comparison (not inclusive). Default: target.length.
The offset within buf at which to begin comparison. Default: 0.
The offset within buf at which to end comparison (not inclusive). Default: this.length.
0 is returned if target is the same as buf1 is returned if target should come before buf when sorted.-1 is returned if target should come after buf when sorted.;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('ABC')
const buf2 = Buffer.from('BCD')
const buf3 = Buffer.from('ABCD')
console.log(buf1.compare(buf1)) // Prints: 0
console.log(buf1.compare(buf2)) // Prints: -1
console.log(buf1.compare(buf3)) // Prints: -1
console.log(buf2.compare(buf1)) // Prints: 1
console.log(buf2.compare(buf3)) // Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare).map(buf => buf.toString()))
// Prints: ['ABC', 'ABCD', 'BCD']
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9])
const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4])
console.log(buf1.compare(buf2, 5, 9, 0, 4)) // Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4)) // Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5)) // Prints: 1
})()
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.
A Buffer or Uint8Array to copy into.
The offset within target at which to begin writing. Default: 0.
The offset within buf from which to begin copying. Default: 0.
The offset within buf at which to stop copying (not inclusive). Default: this.length.
The number of bytes copied.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.allocUnsafe(26)
const buf2 = Buffer.allocUnsafe(26).fill('!')
// 97 is the decimal ASCII value for 'a'.
for (let i = 0; i < 26; i++) buf1[i] = i + 97
// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
buf1.copy(buf2, 8, 16, 20)
// This is equivalent to:
// buf2.set(buf1.subarray(16, 20), 8)
console.log(buf2.toString('ascii', 0, 25))
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
// Create a `Buffer` and copy data from one region to an overlapping region within the same `Buffer`.
const buf = Buffer.allocUnsafe(26)
// 97 is the decimal ASCII value for 'a'.
for (let i = 0; i < 26; i++) buf[i] = i + 97
buf.copy(buf, 0, 4, 10)
console.log(buf.toString())
// Prints: efghijghijklmnopqrstuvwxyz
})()
A Buffer or Uint8Array with which to compare buf.
true if both buf and otherBuffer have exactly the same bytes, false otherwise. Equivalent to buf.compare(otherBuffer) === 0.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('ABC')
const buf2 = Buffer.from('414243', 'hex')
const buf3 = Buffer.from('ABCD')
console.log(buf1.equals(buf2)) // Prints: true
console.log(buf1.equals(buf3)) // Prints: false
})()
Fill the entire buf with the specified value.
The value with which to fill buf. Empty string is coerced to 0.
Optionalencoding: The encoding for value. Default: 'utf8'.
Fill the buf with the specified value start from offset.
The value with which to fill buf. Empty string is coerced to 0.
Number of bytes to skip before starting to fill buf. Default: 0.
Optionalencoding: The encoding for value. Default: 'utf8'.
Fill the buf with the specified value start from offset and stop before end.
The value with which to fill buf. Empty string is coerced to 0.
Number of bytes to skip before starting to fill buf. Default: 0.
Where to stop filling buf (not inclusive). Default: buf.length.
Optionalencoding: The encoding for value. Default: 'utf8'.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
// Fill a `Buffer` with the ASCII character 'h'.
const b = Buffer.allocUnsafe(10).fill('h')
console.log(b.toString()) // Prints: hhhhhhhhhh
// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('')
console.log(c.toString('hex')) // Prints: 0000000000
})()
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:
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
const b = Buffer.allocUnsafe(5).fill('\u0222')
console.log(b.toString('hex')) // Prints: c8a2c8a2c8
})()
If value contains invalid characters, it is truncated; if no valid fill data remains, an exception is thrown:
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.allocUnsafe(5)
console.log(buf.fill('a').toString('hex')) // Prints: 6161616161
console.log(buf.fill('aazz', 'hex').toString('hex')) // Prints: aaaaaaaaaa
console.log(buf.fill('zz', 'hex').toString('hex')) // Throws an exception.
})()
Fill buf with the specified value. If the offset and end are not given, the entire buf will be filled.
The value with which to fill buf. Empty value (Uint8Array, Buffer) is coerced to 0. 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.
Optionaloffset: numberNumber of bytes to skip before starting to fill buf. Default: 0.
Optionalend: numberWhere to stop filling buf (not inclusive). Default: buf.length.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
// Fill a `Buffer` with a Buffer
const buf1 = Buffer.allocUnsafe(10).fill(Buffer.of(65))
console.log(buf1.toString()) // Prints: AAAAAAAAAA
// Fill a `Buffer` with an Uint8Array
const buf2 = Buffer.allocUnsafe(10).fill(Uint8Array.of(65))
console.log(buf2.toString()) // Prints: AAAAAAAAAA
// Fill a `Buffer` with number
const buf3 = Buffer.allocUnsafe(10).fill(65)
console.log(buf3.toString()) // Prints: AAAAAAAAAA
})()
Alias of DataView.getBigInt64.
OptionallittleEndian: booleanAlias of DataView.getBigUint64.
OptionallittleEndian: booleanPolyfill of DataView.getFloat16.
Alias of DataView.getFloat32.
OptionallittleEndian: booleanAlias of DataView.getFloat64.
OptionallittleEndian: booleanAlias of DataView.getUint16.
OptionallittleEndian: booleanAlias of DataView.getUint32.
OptionallittleEndian: booleanEquivalent to buf.indexOf() !== -1.
What to search for.
Optionalencoding: The encoding of value. Default: 'utf8'.
true if value was found in buf, false otherwise.
Equivalent to buf.indexOf() !== -1.
What to search for.
Where to begin searching in buf. If negative, then offset is calculated from the end of buf. Default: 0.
Optionalencoding: The encoding of value. Default: 'utf8'.
true if value was found in buf, false otherwise.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.from('this is a buffer')
console.log(buf.includes('this')) // Prints: true
console.log(buf.includes('is')) // Prints: true
console.log(buf.includes('this', 4)) // Prints: false
})()
Equivalent to buf.indexOf() !== -1.
What to search for.
OptionalbyteOffset: numberWhere to begin searching in buf. If negative, then offset is calculated from the end of buf. Default: 0.
true if value was found in buf, false otherwise.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.from('this is a buffer')
console.log(buf.includes(Buffer.from('a buffer'))) // Prints: true
console.log(buf.includes(97)) // Prints: true (97 is the decimal ASCII value for 'a')
console.log(buf.includes(Uint8Array.of(97))) // Prints: true (97 is the decimal ASCII value for 'a')
console.log(buf.includes(Buffer.from('a buffer example'))) // Prints: false
console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))) // Prints: true
})()
What to search for.
value is a string, value is interpreted according to the character encoding in encoding.value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.value is an empty string or empty Buffer and byteOffset is less than buf.length, byteOffset will be returned.value is empty and byteOffset is at least buf.length, buf.length will be returned.Optionalencoding: The encoding of value. Default: 'utf8'.
value in buf-1 if buf does not contain value.What to search for.
value is a string, value is interpreted according to the character encoding in encoding.value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.value is an empty string or empty Buffer and byteOffset is less than buf.length, byteOffset will be returned.value is empty and byteOffset is at least buf.length, buf.length will be returned.Where to begin searching in buf. Default: 0.
buf._.toSafeInteger.Optionalencoding: The encoding of value. Default: 'utf8'.
value in buf-1 if buf does not contain value.;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.from('this is a buffer')
console.log(buf.indexOf('this')) // Prints: 0
console.log(buf.indexOf('is')) // Prints: 2
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le')
console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')) // Prints: 4
console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')) // Prints: 6
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const b = Buffer.from('abcdef')
// Passing a byteOffset that coerces to 0.
// Prints: 1, searching the whole buffer.
console.log(b.indexOf('b', undefined))
console.log(b.indexOf('b', {}))
console.log(b.indexOf('b', null))
console.log(b.indexOf('b', []))
})()
What to search for.
value is a string, value is interpreted according to the character encoding in encoding.value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.value is an empty string or empty Buffer and byteOffset is less than buf.length, byteOffset will be returned.value is empty and byteOffset is at least buf.length, buf.length will be returned.OptionalbyteOffset: numberWhere to begin searching in buf. Default: 0.
buf._.toSafeInteger.value in buf-1 if buf does not contain value.;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.from('this is a buffer')
console.log(buf.indexOf(Buffer.from('a buffer'))) // Prints: 8
console.log(buf.indexOf(97)) // Prints: 8 (97 is the decimal ASCII value for 'a')
console.log(buf.indexOf(Buffer.from('a buffer example'))) // Prints: -1
console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))) // Prints: 8
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const b = Buffer.from('abcdef')
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.indexOf(99.9))
console.log(b.indexOf(256 + 99))
})()
Iteratively unpack from the buf according to the format string format. This method returns an iterator which will read equally sized chunks from the buf until remaining contents smaller then the size required by the format, as reflected by Buffer.packCalcSize.
A format string. Please refer to Buffer.packParseFormat for more information.
Identical to Buffer#indexOf, except the last occurrence of value is found rather than the first occurrence.
What to search for.
value is a string, value is interpreted according to the character encoding in encoding.value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.value is an empty string or empty Buffer, byteOffset will be returned.Optionalencoding: The encoding of value. Default: 'utf8'.
value in buf-1 if buf does not contain value.Identical to Buffer#indexOf, except the last occurrence of value is found rather than the first occurrence.
What to search for.
value is a string, value is interpreted according to the character encoding in encoding.value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.value is an empty string or empty Buffer, byteOffset will be returned.Where to begin searching in buf. Default: buf.length - 1.
buf._.toSafeInteger.Optionalencoding: The encoding of value. Default: 'utf8'.
value in buf-1 if buf does not contain value.;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.from('this buffer is a buffer')
console.log(buf.lastIndexOf('this')) // Prints: 0
console.log(buf.lastIndexOf('buffer')) // Prints: 17
console.log(buf.lastIndexOf('buffer', 5)) // Prints: 5
console.log(buf.lastIndexOf('buffer', 4)) // Prints: -1
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le')
console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')) // Prints: 6
console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')) // Prints: 4
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const b = Buffer.from('abcdef')
// Passing a byteOffset that coerces to NaN.
// Prints: 1, searching the whole buffer.
console.log(b.lastIndexOf('b', undefined))
console.log(b.lastIndexOf('b', {}))
// Passing a byteOffset that coerces to 0.
// Prints: -1, equivalent to passing 0.
console.log(b.lastIndexOf('b', null))
console.log(b.lastIndexOf('b', []))
})()
Identical to Buffer#indexOf, except the last occurrence of value is found rather than the first occurrence.
What to search for.
value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.value is an empty string or empty Buffer, byteOffset will be returned.OptionalbyteOffset: numberWhere to begin searching in buf. Default: buf.length - 1.
buf._.toSafeInteger.value in buf-1 if buf does not contain value.;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.from('this buffer is a buffer')
console.log(buf.lastIndexOf(Buffer.from('buffer'))) // Prints: 17
console.log(buf.lastIndexOf(97)) // Prints: 15 (97 is the decimal ASCII value for 'a')
console.log(buf.lastIndexOf(Buffer.from('yolo'))) // Prints: -1
})()
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const b = Buffer.from('abcdef')
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.lastIndexOf(99.9))
console.log(b.lastIndexOf(256 + 99))
})()
The method Bitwise NOT every bytes in this in place and returns this.
Calculates the Bitwise OR of all bytes in buf. If buf is empty, returns 0. You can use Buffer#subarray to calculate the Bitwise OR of a subset of buf.
The Bitwise OR of all bytes in buf.
The method Bitwise OR every bytes with other in place and returns this. If length of other is shorter than this, the remaining bytes in this will not be changed. If length of other is longer than this, the remaining bytes in other will be ignored.
A Buffer to Bitwise OR with.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('010203', 'hex')
const buf2 = Buffer.from('102030', 'hex')
console.log(buf1.or(buf2).toString('hex')) // Prints: 112233
console.log(buf1.toString('hex')) // Prints: 112233
})()
Pack vals into buf according to the format string format. The arguments must match the vals required by the format exactly. The buf’s size in bytes must larger then the size required by the format, as reflected by Buffer.packCalcSize.
A format string. Please refer to Buffer.packParseFormat for more information.
Values to pack.
Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.alloc(3)
buf1.pack('>h', 0x0102)
console.log(buf1.toString('hex')) // Prints: 010200
const buf2 = Buffer.alloc(3)
buf2.subarray(1).pack('>h', 0x0102) // struct.pack_into
console.log(buf2.toString('hex')) // Prints: 000102
})()
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.
Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
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.
Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
Reads an unsigned, big-endian 64-bit integer from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
Reads an unsigned, little-endian 64-bit integer from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
Treat the buffer as a least significant bit array and read a bit at the specified bit offset.
bit offset to read from.
Treat buf as a most-significant bit array and read a bit at the specified bit offset.
bit offset to read from.
Reads a 64-bit, big-endian double from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 8. Default: 0.
Reads a 64-bit, little-endian double from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 8. Default: 0.
Reads a 16-bit, big-endian float from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
console.log(Buffer.from('0000', 'hex').readFloat16BE(0)) // Prints: 0
console.log(Buffer.from('8000', 'hex').readFloat16BE(0)) // Prints: -0
console.log(Buffer.from('3c00', 'hex').readFloat16BE(0)) // Prints: 1
console.log(Buffer.from('bc00', 'hex').readFloat16BE(0)) // Prints: -1
console.log(Buffer.from('7c00', 'hex').readFloat16BE(0)) // Prints: Infinity
console.log(Buffer.from('fc00', 'hex').readFloat16BE(0)) // Prints: -Infinity
console.log(Buffer.from('7e00', 'hex').readFloat16BE(0)) // Prints: NaN
console.log(Buffer.from('fe00', 'hex').readFloat16BE(0)) // Prints: NaN
})()
Reads a 16-bit, little-endian float from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
console.log(Buffer.from('0000', 'hex').readFloat16LE(0)) // Prints: 0
console.log(Buffer.from('0080', 'hex').readFloat16LE(0)) // Prints: -0
console.log(Buffer.from('003c', 'hex').readFloat16LE(0)) // Prints: 1
console.log(Buffer.from('00bc', 'hex').readFloat16LE(0)) // Prints: -1
console.log(Buffer.from('007c', 'hex').readFloat16LE(0)) // Prints: Infinity
console.log(Buffer.from('00fc', 'hex').readFloat16LE(0)) // Prints: -Infinity
console.log(Buffer.from('007e', 'hex').readFloat16LE(0)) // Prints: NaN
console.log(Buffer.from('00fe', 'hex').readFloat16LE(0)) // Prints: NaN
})()
Reads a 32-bit, big-endian float from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
Reads a 32-bit, little-endian float from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
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.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
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.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
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.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
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.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
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.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.
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.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.
Number of bytes to read. Must satisfy 1 <= byteLength <= 6.
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.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.
Number of bytes to read. Must satisfy 1 <= byteLength <= 6.
Reads an unsigned, big-endian 16-bit integer from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
Reads an unsigned, little-endian 16-bit integer from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
Reads an unsigned, big-endian 32-bit integer from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
Reads an unsigned, little-endian 32-bit integer from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
Reads an unsigned 8-bit integer from buf at the specified offset.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.
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.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.
Number of bytes to read. Must satisfy 0 < byteLength <= 6.
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.
Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.
Number of bytes to read. Must satisfy 0 < byteLength <= 6.
Alias of DataView.setBigInt64.
OptionallittleEndian: booleanAlias of DataView.setBigUint64.
OptionallittleEndian: booleanPolyfill of DataView.setFloat16.
Alias of DataView.setFloat32.
OptionallittleEndian: booleanAlias of DataView.setFloat64.
OptionallittleEndian: booleanAlias of DataView.setInt16.
OptionallittleEndian: booleanAlias of DataView.setInt32.
OptionallittleEndian: booleanAlias of DataView.setUint16.
OptionallittleEndian: booleanAlias of DataView.setUint32.
OptionallittleEndian: booleanInterprets buf as an array of unsigned 16-bit integers and swaps the byte order in-place.
A reference to buf.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('0102030405060708', 'hex')
console.log(buf1.toString('hex')) // Prints: 0102030405060708
buf1.swap16()
console.log(buf1.toString('hex')) // Prints: 0201040306050807
const utf16 = Buffer.from('This is little-endian UTF-16', 'utf16le')
utf16.swap16() // Convert to big-endian UTF-16 text.
})()
Interprets buf as an array of unsigned 32-bit integers and swaps the byte order in-place.
A reference to buf.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('0102030405060708', 'hex')
console.log(buf1.toString('hex')) // Prints: 0102030405060708
buf1.swap32()
console.log(buf1.toString('hex')) // Prints: 0403020108070605
})()
Interprets buf as an array of unsigned 64-bit integers and swaps the byte order in-place.
A reference to buf.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('0102030405060708', 'hex')
console.log(buf1.toString('hex')) // Prints: 0102030405060708
buf1.swap64()
console.log(buf1.toString('hex')) // Prints: 0807060504030201
})()
The method returns a new Buffer which is the Bitwise AND of this and other. If length of other is shorter than this, the remaining bytes in this will be copied to the new Buffer. If length of other is longer than this, the remaining bytes in other will be ignored.
A Buffer to Bitwise AND with.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('010203', 'hex')
const buf2 = Buffer.from('102030', 'hex')
console.log(buf1.toAnded(buf2).toString('hex')) // Prints: 000000
console.log(buf1.toString('hex')) // Prints: 010203
})()
JSON.stringify() implicitly calls this method 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).
a JSON representation of buf.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf = Buffer.from('0102030405', 'hex')
const json = JSON.stringify(buf)
console.log(json) // Prints: {"type":"Buffer","data":[1,2,3,4,5]}
const restored = JSON.parse(json, (key, value) => {
return value && value.type === 'Buffer' ? Buffer.from(value) : value
})
console.log(restored.toString('hex')) // Prints: 0102030405
})()
The method returns a new Buffer which is the Bitwise NOT of this.
The method returns a new Buffer which is the Bitwise OR of this and other. If length of other is shorter than this, the remaining bytes in this will be copied to the new Buffer. If length of other is longer than this, the remaining bytes in other will be ignored.
A Buffer to Bitwise OR with.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('010203', 'hex')
const buf2 = Buffer.from('102030', 'hex')
console.log(buf1.toOred(buf2).toString('hex')) // Prints: 112233
console.log(buf1.toString('hex')) // Prints: 010203
})()
The method is the copying counterpart of the reverse() method. It returns a new Buffer with the elements in reversed order.
A new Buffer containing the elements in reversed order.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('01020304', 'hex')
const buf2 = buf1.reverse()
console.log(buf1.toString('hex')) // Prints: 01020304
console.log(buf2.toString('hex')) // Prints: 04030201
})()
The method is the copying version of the sort() method. It returns a new Buffer with the elements sorted in ascending order.
OptionalcompareFn: (a: number, b: number) => anyA function that determines the order of the elements. The function is called with the following arguments:
a: The first element for comparison.b: The second element for comparison.
It should return a number where:a should come before b.a should come after b.NaN indicates that a and b are considered equal.
To memorize this, remember that (a, b) => a - b sorts numbers in ascending order. If omitted, the elements are sorted according to numeric value.A new Buffer with the elements sorted in ascending order.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('03010204', 'hex')
const buf2 = buf1.toSorted()
console.log(buf1.toString('hex')) // Prints: 03010204
console.log(buf2.toString('hex')) // Prints: 01020304
})()
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.
The character encoding to use. Default: 'utf8'.
The byte offset to start decoding at. Default: 0.
The byte offset to stop decoding at (not inclusive). Default: buf.length.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.allocUnsafe(26)
for (let i = 0; i < 26; i++) buf1[i] = i + 97 // 97 is the decimal ASCII value for 'a'.
console.log(buf1.toString('utf8')) // Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5)) // Prints: abcde
const buf2 = Buffer.from('tést')
console.log(buf2.toString('hex')) // Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3)) // Prints: té
console.log(buf2.toString(undefined, 0, 3)) // Prints: té
})()
The method returns a new Buffer which is the Bitwise XOR of this and other. If length of other is shorter than this, the remaining bytes in this will be copied to the new Buffer. If length of other is longer than this, the remaining bytes in other will be ignored.
A Buffer to Bitwise XOR with.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('010203', 'hex')
const buf2 = Buffer.from('102030', 'hex')
console.log(buf1.toXored(buf2).toString('hex')) // Prints: 112233
console.log(buf1.toString('hex')) // Prints: 010203
})()
Unpack from the buf (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buf’s size in bytes must larger then the size required by the format, as reflected by Buffer.packCalcSize.
A format string. Please refer to Buffer.packParseFormat for more information.
Returns the primitive value of the specified object.
The method is the copying version of using the bracket notation to change the value of a given index. It returns a new Buffer with the element at the given index replaced with the given value.
Zero-based index at which to change the Buffer, converted to an integer.
Any value to be assigned to the given index.
A new Buffer with the element at index replaced with value.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('0102030405', 'hex')
const buf2 = buf1.with(2, 6)
console.log(buf1.toString('hex')) // Prints: 0102030405
console.log(buf2.toString('hex')) // Prints: 0102060405
})()
Writes string to buf at offset according to the character encoding inencoding. 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.
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(256);
const len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾
const buffer = Buffer.alloc(10);
const length = buffer.write('abcd', 8);
console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : ab
String to write to buf.
Optionalencoding: The character encoding of string.
Number of bytes written.
Optionalencoding: 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.
String to write to buf.
Number of bytes to skip before starting to write string. Default: 0.
Maximum number of bytes to write (written bytes will not exceed buf.length - offset). Default: buf.length - offset.
Optionalencoding: The character encoding of string. Default: 'utf8'.
Number of bytes written.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.alloc(256)
const len1 = buf1.write('\u00bd + \u00bc = \u00be', 0)
console.log(`${len1} bytes: ${buf1.toString('utf8', 0, len1)}`)
// Prints: 12 bytes: ½ + ¼ = ¾
const buf2 = Buffer.alloc(10)
const len2 = buf2.write('abcd', 8)
console.log(`${len2} bytes: ${buf2.toString('utf8', 8, 10)}`)
// Prints: 2 bytes : ab
})()
Writes value to buf at the specified offset as big-endian. value is interpreted and written as a two's complement signed integer.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
Writes value to buf at the specified offset as little-endian. value is interpreted and written as a two's complement signed integer.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
Writes value to buf at the specified offset as big-endian.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
Writes value to buf at the specified offset as little-endian.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
Treats buf as a least significant bit array and write a bit at the specified bit offset.
Bit value to write.
bit offset to read from.
Treats buf as a most-significant bit array and write a bit at the specified bit offset.
Bit value to write.
bit offset to read from.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.
Writes a 16-bit float 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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 2. Default: 0.
Writes a 16-bit float 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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 2. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 4. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 4. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 2. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 2. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 4. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 4. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 1. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.
Number of bytes to write. Must satisfy 1 <= byteLength <= 6.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.
Number of bytes to write. Must satisfy 1 <= byteLength <= 6.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.
Number of bytes to write. Must satisfy 1 <= byteLength <= 6.
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.
Number to be written to buf.
Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.
Number of bytes to write. Must satisfy 1 <= byteLength <= 6.
Calculates the Bitwise XOR of all bytes in buf. If buf is empty, returns 0. You can use Buffer#subarray to calculate the Bitwise XOR of a subset of buf. Xor is usually used to calculate checksums in serial communication.
The Bitwise XOR of all bytes in buf.
The method Bitwise XOR every bytes with other in place and returns this. If length of other is shorter than this, the remaining bytes in this will not be changed. If length of other is longer than this, the remaining bytes in other will be ignored.
A Buffer to Bitwise XOR with.
;(async function () {
const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')
const buf1 = Buffer.from('010203', 'hex')
const buf2 = Buffer.from('102030', 'hex')
console.log(buf1.xor(buf2).toString('hex')) // Prints: 112233
console.log(buf1.toString('hex')) // Prints: 112233
})()
Alias of Buffer.readBigUInt64BE.
Alias of Buffer.readBigUInt64LE.
Alias of Buffer.readUInt16BE.
Alias of Buffer.readUInt16LE.
Alias of Buffer.readUInt32BE.
Alias of Buffer.readUInt32LE.
Alias of Buffer.readUInt8.
Alias of Buffer.readUIntBE.
Alias of Buffer.readUIntLE.
Alias of Buffer.writeBigUInt64BE.
Alias of Buffer.writeBigUInt64LE.
Alias of Buffer.writeUInt16BE.
Alias of Buffer.writeUInt16LE.
Alias of Buffer.writeUInt32BE.
Alias of Buffer.writeUInt32LE.
Alias of Buffer.writeUInt8.
Alias of Buffer.writeUIntBE.
Alias of Buffer.writeUIntLE.
ReadonlybufferThe underlying ArrayBuffer object based on which this Buffer object is created.
ReadonlybyteThe length in bytes of the array.
ReadonlybyteThe offset in bytes of the array.
ReadonlyBYTES_The size in bytes of each element in the array.
ReadonlylengthThe length of the array.
Static ReadonlyBYTES_The size in bytes of each element in the array.
The
Bufferclass is a cross platform alternative of Node buffer base onUInt8Array.See
See the Buffer | Node.js Documentation for more information.