Node.js Buffer(Buffer)
The JavaScript language itself only has a string data type and no binary data type.
The Buffer class in Node.js is a core tool for handling binary data, providing efficient operations on binary data.
The Buffer class is particularly useful in scenarios such as file operations, network communication, and image processing.
Characteristics:
- Binary Data:
Bufferobject is a fixed-size array containing raw binary data. Each element occupies one byte (8 bits), soBufferis suitable for handling binary data, such as file contents, network packets, and so on. - Immutability: Although
BufferThe content of an object can be modified after creation, but its length is fixed and cannot be changed dynamically.
Buffer and Character Encoding
Buffer instances are generally used to represent sequences of encoded characters, such as UTF-8, UCS2, Base64, or hexadecimal encoded data. By using an explicit character encoding, you can convert back and forth between Buffer instances and ordinary JavaScript strings.
Example
const
buf
=
Buffer.
from
(
'runoob'
,
'ascii'
)
;
// Output 72756e6f6f62
console.
log
(
buf.
toString
(
'hex'
)
)
;
// Output cnVub29i
console.
log
(
buf.
toString
(
'base64'
)
)
;
The character encodings currently supported by Node.js include:
-
ascii - Supports only 7-bit ASCII data. This encoding is very fast if the high bit is set to be stripped.
-
utf8 - Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8.
-
utf16le - 2- or 4-byte, little-endian encoded Unicode characters. Supports surrogate pairs (U+10000 to U+10FFFF).
-
ucs2 - utf16le is an alias of.
-
base64 - Base64 encoding.
-
latin1 - A way of encoding Buffer into a one-byte-encoded string.
-
binary - latin1 is an alias of.
-
hex - Encode each byte as two hexadecimal characters.
Creating a Buffer Class
Buffer provides the following APIs to create a Buffer class:
- Buffer.alloc(size[, fill[, encoding]]): Creates a Buffer of length size bytes, equivalent to allocating size bytes of memory space, with each byte having the value 0.
- Buffer.allocUnsafe(size): Creates a Buffer of length size bytes, but the Buffer may contain old data that could affect execution results, hence it is called unsafe.
- **Buffer.allocUnsafeSlow(size):** Used to allocate a new Buffer instance of the given size, but without initializing it.
- Buffer.from(array): Returns a new Buffer instance initialized with the values of array (the elements of the passed array can only be numbers; otherwise they will automatically be overwritten with 0)
- Buffer.from(arrayBuffer[, byteOffset[, length]]): Returns a newly created Buffer that shares the same memory as the given ArrayBuffer.
- Buffer.from(buffer): Copies the data of the passed-in Buffer instance and returns a new Buffer instance
- Buffer.from(string[, encoding]): Create a Buffer from a string; you can specify the encoding, which defaults to UTF-8.
Example
// Create a Buffer of length 10 filled with 0.
const
buf1
=
Buffer.
alloc
(
10
)
;
// Create a Buffer of length 10 filled with 0x1.
const
buf2
=
Buffer.
alloc
(
10
,
1
)
;
// Create a Buffer of length 10 that is uninitialized.
// This method is faster than calling Buffer.alloc(),
// but the returned Buffer instance may contain old data,
// so you need to overwrite it using fill() or write().
const
buf3
=
Buffer.
allocUnsafe
(
10
)
;
// Create a Buffer containing [0x1, 0x2, 0x3].
const
buf4
=
Buffer.
from
(
[
1
,
2
,
3
]
)
;
// Create a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74].
const
buf5
=
Buffer.
from
(
'tést'
)
;
// Create a Buffer containing Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const
buf6
=
Buffer.
from
(
'tést'
,
'latin1'
)
;
Writing to a Buffer
Syntax
The syntax for writing to a Node Buffer is as follows:
buf.write(string[, offset[, length]][, encoding])
Parameters
The parameters are described as follows:
-
string - The string to write to the buffer.
-
offset - The index value at which writing to the buffer begins, defaulting to 0.
-
length - The number of bytes to write, defaulting to buffer.length
-
encoding - The encoding to use. Defaults to 'utf8'.
Write string to buf at the offset position according to the encoding character encoding. The length parameter is the number of bytes to write. If buf does not have enough space to hold the entire string, only part of string will be written. Partially decoded characters will not be written.
Return Value
Returns the actual size written. If there is insufficient space in the buffer, only part of the string will be written.
Example
buf = Buffer.alloc(256);
len = buf.write("www.runoob.com");
console.log("写入字节数 : "+ len);
The output of the code above is:
$node main.js
写入字节数 : 14
Reading Data from a Buffer
Syntax
The syntax for reading data from a Node Buffer is as follows:
buf.toString([encoding[, start[, end]]])
Parameters
The parameters are described as follows:
-
encoding - The encoding to use. Defaults to 'utf8'.
-
start - The index position at which to start reading, defaulting to 0.
-
end - The end position, defaulting to the end of the buffer.
Return Value
Decode the buffer data and return a string using the specified encoding.
Example
buf = Buffer.alloc(26);
for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97;
}
console.log( buf.toString('ascii')); // 输出: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5)); //使用 'ascii' 编码, 并输出: abcde
console.log( buf.toString('utf8',0,5)); // 使用 'utf8' 编码, 并输出: abcde
console.log( buf.toString(undefined,0,5)); // 使用默认的 'utf8' 编码, 并输出: abcde
The output of the code above is:
$ node main.js
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde
Converting a Buffer to a JSON Object
Syntax
The syntax of the function for converting a Node Buffer to a JSON object is as follows:
buf.toJSON()
When stringifying a Buffer instance,JSON.stringify() toJSON() is called implicitly.
Return Value
Returns a JSON object.
Example
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);
// 输出: {"type":"Buffer","data":[1,2,3,4,5]}
console.log(json);
const copy = JSON.parse(json, (key, value) => {
return value && value.type === 'Buffer' ?
Buffer.from(value.data) :
value;
});
// 输出:
console.log(copy);
The output of the code above is:
{"type":"Buffer","data":[1,2,3,4,5]}
Buffer Concatenation
Syntax
The syntax for Node buffer concatenation is as follows:
Buffer.concat(list[, totalLength])
Parameters
The parameters are described as follows:
-
list - An array list of Buffer objects to concatenate.
-
totalLength - Specifies the total length of the concatenated Buffer object.
Return Value
Returns a new Buffer object formed by concatenating multiple members.
Example
var buffer1 = Buffer.from(('Runoob Tutorial'));
var buffer2 = Buffer.from(('www.runoob.com'));
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 内容: " + buffer3.toString());
The output of the code above is:
buffer3 内容: Runoob Tutorialwww.runoob.com
Buffer Comparison
Syntax
The syntax of the Node Buffer comparison function is as follows; this method was introduced in Node.js v0.12.2:
buf.compare(otherBuffer);
Parameters
The parameters are described as follows:
-
otherBuffer - Another Buffer object to compare with buf the object.
Return Value
Returns a number indicating whether buf in otherBuffer comes before, after, or is the same as
Example
var buffer1 = Buffer.from('ABC');
var buffer2 = Buffer.from('ABCD');
var result = buffer1.compare(buffer2);
if(result < 0) {
console.log(buffer1 + " 在 " + buffer2 + "之前");
}else if(result == 0){
console.log(buffer1 + " 与 " + buffer2 + "相同");
}else {
console.log(buffer1 + " 在 " + buffer2 + "之后");
}
The output of the code above is:
ABC在ABCD之前
Copying a Buffer
Syntax
The syntax for Node buffer copying is as follows:
buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])
Parameters
The parameters are described as follows:
-
targetBuffer - The Buffer object to copy.
-
targetStart - Number, optional, default: 0
-
sourceStart - Number, optional, default: 0
-
sourceEnd - Number, optional, default: buffer.length
Return Value
No value is returned.
Example
var buf1 = Buffer.from('abcdefghijkl');
var buf2 = Buffer.from('RUNOOB');
//Insert buf2 into buf1 at the specified position
buf2.copy(buf1, 2);
console.log(buf1.toString());
The output of the code above is:
abRUNOOBijkl
Buffer Slicing
The syntax for Node buffer slicing is as follows:
buf.slice([start[, end]])
Parameters
The parameters are described as follows:
-
start - Number, optional, default: 0
-
end - Number, optional, default: buffer.length
Return Value
Returns a new buffer that points to the same memory as the old buffer, but sliced from index start to end.
Example
var buffer1 = Buffer.from('runoob');
// Clip buffer
var buffer2 = buffer1.slice(0,2);
console.log("buffer2 content: " + buffer2.toString());
The output of the code above is:
buffer2 content: ru
Buffer Length
Syntax
The syntax for Node buffer length calculation is as follows:
buf.length;
Return Value
Returns the length of memory occupied by the Buffer object.
Example
var buffer = Buffer.from('www.runoob.com');
// Buffer length
console.log("buffer length: " + buffer.length);
The output of the code above is:
buffer length: 14
Method Reference Manual
The following lists the commonly used methods of the Node.js Buffer module (note that some methods are not available in older versions):
| No. | Method & Description |
|---|---|
| 1 | new Buffer(size) |
| Allocate a new buffer of size with units of 8-bit bytes. Note that size must be less than kMaxLength; otherwise, a RangeError will be thrown. Deprecated: use Buffer.alloc() instead (or Buffer.allocUnsafe()). | |
| 2 | new Buffer(buffer) |
| Copy the data of the parameter buffer to the Buffer instance. Deprecated: use Buffer.from(buffer) instead. | |
| 3 | new Buffer(str[, encoding]) |
| Allocate a new buffer containing the passed-in str string. The encoding defaults to 'utf8'. Deprecated: use Buffer.from(string[, encoding]) instead. | |
| 4 | buf.length |
| Returns the number of bytes of this buffer. Note that this is not necessarily the size of the content inside the buffer. length is the amount of memory allocated by the buffer object, and it does not change as the content of the buffer object changes. | |
| 5 | buf.write(string[, offset[, length]][, encoding]) |
| Write the parameter string data to the buffer according to the offset parameter and the specified encoding. The offset defaults to 0, and the encoding defaults to utf8. The length is the byte size of the string to be written. Returns a number indicating how many 8-bit byte streams were written. If the buffer does not have enough space to hold the entire string, only part of the string will be written. length defaults to buffer.length - offset. This method does not write partial characters. | |
| 6 | buf.writeUIntLE(value, offset, byteLength[, noAssert]) |
将 value 写入到 buffer 里, 它由 offset 和 byteLength 决定,最高支持 48 位无符号整数,小端对齐,例如:
const buf = Buffer.allocUnsafe(6);
buf.writeUIntLE(0x1234567890ab, 0, 6);
// Output:
Write value to the buffer, determined by offset and byteLength, supporting up to 48-bit unsigned integers, big-endian. When noAssert is true, the validity of value and offset is no longer checked. Defaults to false.
const buf = Buffer.allocUnsafe(6);| | 8 | buf.writeIntLE(value, offset, byteLength[, noAssert])buf.writeUIntBE(0x1234567890ab, 0, 6);
// 输出:
console.log(buf);
Write value to the buffer, determined by offset and byteLength, supporting up to 48-bit signed integers, little-endian. When noAssert is true, the validity of value and offset is no longer checked. Defaults to false. | | 9 | buf.writeIntBE(value, offset, byteLength[, noAssert])
Write value to the buffer, determined by offset and byteLength, supporting up to 48-bit signed integers, big-endian. When noAssert is true, the validity of value and offset is no longer checked. Defaults to false. | | 10 | buf.readUIntLE(offset, byteLength[, noAssert])
Supports reading unsigned numbers below 48 bits, little-endian aligned. When noAssert is true, offset no longer validates whether it exceeds the buffer length, default is false. | | 11 | buf.readUIntBE(offset, byteLength[, noAssert])
Supports reading unsigned numbers below 48 bits, big-endian aligned. When noAssert is true, offset no longer validates whether it exceeds the buffer length, default is false. | | 12 | buf.readIntLE(offset, byteLength[, noAssert])
Supports reading signed numbers below 48 bits, little-endian aligned. When noAssert is true, offset no longer validates whether it exceeds the buffer length, default is false. | | 13 | buf.readIntBE(offset, byteLength[, noAssert])
Supports reading signed numbers below 48 bits, big-endian aligned. When noAssert is true, offset no longer validates whether it exceeds the buffer length, default is false. | | 14 | buf.toString([encoding[, start[, end]]])
Returns a decoded string type based on the encoding parameter (default is 'utf8'). It also uses the passed parameters start (default is 0) and end (default is buffer.length) as the value range. | | 15 | buf.toJSON()
Convert a Buffer instance to a JSON object. | | 16 | buf[index]
Gets or sets the specified byte. The return value represents a byte, so the valid range of the return value is hexadecimal 0x00 to 0xFF or decimal 0 to 255. | | 17 | buf.equals(otherBuffer)
Compares whether two buffers are equal, returning true if so, otherwise returning false. | | 18 | buf.compare(otherBuffer)
Compares two Buffer objects and returns a number indicating whether buf comes before, after, or is the same as otherBuffer. | | 19 | buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])
buffer copy, the source and destination can be the same. targetStart destination start offset and sourceStart source start offset both default to 0. sourceEnd source end position offset defaults to the source length buffer.length. | | 20 | buf.slice([start[, end]])
Slice the Buffer object, offsetting and trimming the index according to start (default 0) and end (default buffer.length). Negative indexes are counted from the end of the buffer. | | 21 | buf.readUInt8(offset[, noAssert])
Reads an unsigned 8-bit integer from the specified offset. If the parameter noAssert is true, the offset parameter will not be verified. If so, offset may go beyond the end of the buffer. Default is false. | | 22 | buf.readUInt16LE(offset[, noAssert])
Reads an unsigned 16-bit integer from the specified offset using a special endian byte order format. If the parameter noAssert is true, the offset parameter will not be verified. This means offset may go beyond the end of the buffer. Default is false. | | 23 | buf.readUInt16BE(offset[, noAssert])
Reads an unsigned 16-bit integer from the specified offset using a special endian byte order format, big-endian aligned. If the parameter noAssert is true, the offset parameter will not be verified. This means offset may go beyond the end of the buffer. Default is false. | | 24 | buf.readUInt32LE(offset[, noAssert])
Reads an unsigned 32-bit integer at the specified offset using the specified endian byte order format, little-endian aligned. If the parameter noAssert is true, the offset parameter will not be validated. This means offset may exceed the end of the buffer. Default is false. | | 25 | buf.readUInt32BE(offset[, noAssert])
Reads an unsigned 32-bit integer at the specified offset using the specified endian byte order format, big-endian aligned. If the parameter noAssert is true, the offset parameter will not be validated. This means offset may exceed the end of the buffer. Default is false. | | 26 | buf.readInt8(offset[, noAssert])
Reads a signed 8-bit integer from the specified offset. If the parameter noAssert is true, the offset parameter will not be verified. This means offset may go beyond the end of the buffer. Default is false. | | 27 | buf.readInt16LE(offset[, noAssert])
Reads a signed 16-bit integer from the specified offset using a special endian format, little-endian aligned. If the parameter noAssert is true, the offset parameter will not be verified. This means offset may go beyond the end of the buffer. Default is false. | | 28 | buf.readInt16BE(offset[, noAssert])
Reads a signed 16-bit integer from the specified offset using a special endian format, big-endian aligned. If the parameter noAssert is true, the offset parameter will not be verified. This means offset may go beyond the end of the buffer. Default is false. | | 29 | buf.readInt32LE(offset[, noAssert])
Reads a signed 32-bit integer at the specified offset using the specified endian byte order format, little-endian aligned. If the parameter noAssert is true, the offset parameter will not be validated. This means offset may exceed the end of the buffer. Default is false. | | 30 | buf.readInt32BE(offset[, noAssert])
Reads a signed 32-bit integer at the specified offset using the specified endian byte order format, big-endian aligned. If the parameter noAssert is true, the offset parameter will not be validated. This means offset may exceed the end of the buffer. Default is false. | | 31 | buf.readFloatLE(offset[, noAssert])
Reads a 32-bit double-precision floating-point number at the specified offset using the specified endian byte order format, little-endian aligned. If the parameter noAssert is true, the offset parameter will not be validated. This means offset may exceed the end of the buffer. Default is false. | | 32 | buf.readFloatBE(offset[, noAssert])
Reads a 32-bit double-precision floating-point number at the specified offset using the specified endian byte order format, big-endian aligned. If the parameter noAssert is true, the offset parameter will not be validated. This means offset may exceed the end of the buffer. Default is false. | | 33 | buf.readDoubleLE(offset[, noAssert])
Reads a 64-bit double from the specified offset using the specified endian byte order format, little-endian aligned. If the parameter noAssert is true, the offset parameter will not be verified. This means offset may go beyond the end of the buffer. Default is false. | | 34 | buf.readDoubleBE(offset[, noAssert])
Reads a 64-bit double from the specified offset using the specified endian byte order format, big-endian aligned. If the parameter noAssert is true, the offset parameter will not be verified. This means offset may go beyond the end of the buffer. Default is false. | | 35 | buf.writeUInt8(value, offset[, noAssert])
Writes value to the buffer based on the passed offset. Note: value must be a valid unsigned 8-bit integer. If the parameter noAssert is true, the offset parameter will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, do not use it. Default is false. | | 36 | buf.writeUInt16LE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: value must be a valid unsigned 16-bit integer, little-endian aligned. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 37 | buf.writeUInt16BE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: value must be a valid unsigned 16-bit integer, big-endian aligned. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 38 | buf.writeUInt32LE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format (LITTLE-ENDIAN: little-endian byte order). Note: value must be a valid unsigned 32-bit integer, little-endian aligned. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 39 | buf.writeUInt32BE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format (Big-Endian: big-endian byte order). Note: value must be a valid signed 32-bit integer. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 40 | buf.writeInt8(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: value must be a valid signed 16-bit integer. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 42 | buf.writeInt16BE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: value must be a valid signed 16-bit integer. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 43 | buf.writeInt32LE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: value must be a valid signed 32-bit integer. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 44 | buf.writeInt32BE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: value must be a valid signed 32-bit integer. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 45 | buf.writeFloatLE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: when value is not a 32-bit floating-point value, the result will be undefined. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 46 | buf.writeFloatBE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: when value is not a 32-bit floating-point value, the result will be undefined. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 47 | buf.writeDoubleLE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: value must be a valid 64-bit double value. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 48 | buf.writeDoubleBE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset and the specified endian format. Note: value must be a valid 64-bit double value. If the parameter noAssert is true, the value and offset parameters will not be validated. This means value may be too large, or offset may exceed the end of the buffer, causing value to be discarded. Unless you are very confident about this parameter, try not to use it. Default is false. | | 49 | buf.fill(value[, offset][, end])
Fill this buffer with the specified value. If offset (default 0) and end (default buffer.length) are not specified, the entire buffer will be filled. |