Node.js Buffer


The JavaScript language itself only has string data types, not binary data types.

But when dealing with TCP streams or file streams, binary data must be used. Therefore, in Node.js, a Buffer class is defined, which is used to create a buffer area specifically for storing binary data.

In Node.js, the Buffer class is a core library released with the Node kernel. The Buffer library brings a method of storing raw data to Node.js, allowing Node.js to process binary data. Whenever you need to process data moved during I/O operations in Node.js, it is possible to use the Buffer library. . Raw data is stored in instances of the Buffer class. A Buffer is similar to an integer array, but it corresponds to a piece of raw memory outside of the V8 heap memory.


Creating the Buffer class

The Node Buffer class can be created in a variety of ways.

Method 1

Create a Buffer instance with a length of 10 bytes:

var buf = new Buffer(10);

Method 2

Create a Buffer instance from the given array:

var buf = new Buffer([10, 20, 30, 40, 50]);

Method 3

Create a Buffer instance through a string:

var buf = new Buffer("www.php.cn", "utf-8");

utf-8 is the default encoding, and it also supports the following encodings: "ascii", " utf8", "utf16le", "ucs2", "base64" and "hex".


Write buffer

Syntax

The syntax for writing Node buffer is as follows:

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

Parameters

The parameters are described as follows:

  • #string - The string written to the buffer.

  • offset - The index value at which the buffer starts to be written, default is 0.

  • length - Number of bytes written, default is buffer.length

  • encoding - The encoding to use. Defaults to 'utf8' .

Return value

Returns the actual written size. If there is insufficient buffer space, only part of the string will be written.

Example

buf = new Buffer(256);
len = buf.write("www.php.cn");

console.log("写入字节数 : "+  len);

Execute the above code, the output result is:

$node main.js
写入字节数 : 14

Read data from the buffer

Syntax

The syntax for reading Node buffer data is as follows:

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

Parameters

The parameters are described as follows:

  • encoding - The encoding used. Defaults to 'utf8' .

  • #start - Specifies the index position to start reading, default is 0.

  • #end - End position, defaults to the end of the buffer.

Return Value

Decode the buffer data and return a string using the specified encoding.

Example

buf = new Buffer(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));   // 输出: abcde
console.log( buf.toString('utf8',0,5));    // 输出: abcde
console.log( buf.toString(undefined,0,5)); // 使用 'utf8' 编码, 并输出: abcde

Execute the above code, the output result is:

$ node main.js
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde

Convert Buffer to JSON object

Syntax

The function syntax format for converting Node Buffer to JSON object is as follows:

buf.toJSON()

Return value

Returns JSON object.

Example

var buf = new Buffer('www.php.cn');
var json = buf.toJSON(buf);

console.log(json);

Execute the above code, the output result is:

[ 119, 119, 119, 46, 114, 117, 110, 111, 111, 98, 46, 99, 111, 109 ]

Buffer merge

Syntax

Node buffer The syntax of zone merging is as follows:

Buffer.concat(list[, totalLength])

Parameters

The parameters are described as follows:

  • list - Array list of Buffer objects used for merging.

  • totalLength - Specifies the total length of the merged Buffer object.

Return value

Returns a new Buffer object that combines multiple members.

Example

var buffer1 = new Buffer('php中文网 ');
var buffer2 = new Buffer('www.php.cn');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 内容: " + buffer3.toString());

Execute the above code, the output result is:

buffer3 内容: php中文网 www.php.cn

Buffer comparison

Syntax

Node Buffer The function syntax for comparison 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 compared to the buf object.

Return value

Returns a number indicating that buf is before, after, or the same as otherBuffer.

Example

var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('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 + "之后");
}

Execute the above code, the output result is:

ABC在ABCD之前

Copy buffer

Syntax

Node buffer The area copy syntax is as follows:

buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])

Parameters

The parameters are described as follows:

  • targetBuffer - The Buffer object to be copied .

  • targetStart - number, optional, default: 0

  • ##sourceStart - number, Optional, default: 0

  • sourceEnd - Number, optional, default: buffer.length

Return value

No return value.

Example

var buffer1 = new Buffer('ABC');
// 拷贝一个缓冲区
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());

Execute the above code, the output result is:

buffer2 content: ABC


Buffer clipping

Node buffer clipping syntax 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

Return a new Buffer, which points to the same memory as the old buffer, but is cut from index start to end.

Example

var buffer1 = new Buffer('php');
// 剪切缓冲区
var buffer2 = buffer1.slice(0,2);
console.log("buffer2 content: " + buffer2.toString());

Execute the above code, the output result is:

buffer2 content: ru


Buffer length

Syntax

Node buffer The area length calculation syntax is as follows:

buf.length;

Return value

Returns the memory length occupied by the Buffer object.

Example

var buffer = new Buffer('www.php.cn');
//  缓冲区长度
console.log("buffer length: " + buffer.length);

Execute the above code, the output result is:

buffer length: 14


Method Reference Manual

The Node.js Buffer module is listed below Commonly used methods (note that some methods are not available in older versions):

##414243
Serial numberMethod & Description
1new Buffer(size)
Allocate a new size buffer whose size unit is 8-bit bytes. Note, size must be less than kMaxLength, otherwise, the RangeError exception will be thrown.
2new Buffer(buffer)
Copy the data of parameter buffer to the Buffer instance.
3new Buffer(str[, encoding])
Allocate a new buffer, which contains the incoming str string. encoding encoding defaults to 'utf8'.
4buf.length
Returns the number of bytes of this buffer. Note that this is not necessarily the size of the contents of the buffer. length is the amount of memory allocated by the buffer object, and it will not change as the contents of the buffer object change.
5buf.write(string[, offset[, length]][, encoding])
According to the offset parameter Shift and specified encoding encoding method, write the parameter string data into the buffer. The default offset value is 0, and the encoding encoding method is utf8 by default. length is the size in bytes of the string to be written. Returns a number type indicating how many 8-bit byte streams were written. If the buffer does not have enough space to hold the entire string, it will only write part of the string. length defaults to buffer.length - offset. This method will not write partial characters.
6buf.writeUIntLE(value, offset, byteLength[, noAssert])
Write value into buffer, It is determined by offset and byteLength and supports 48-bit calculations, for example:
var b = new Buffer(6);
b.writeUIntBE(0x1234567890ab, 0, 6);
// <Buffer 12 34 56 78 90 ab>
noAssert When the value is true, the validity of value and offset is no longer verified. The default is false.
7buf.writeUIntBE(value, offset, byteLength[, noAssert])
Write value into buffer, It is determined by offset and byteLength and supports 48-bit calculations. When the noAssert value is true, the validity of value and offset is no longer verified. The default is false.
8buf.writeIntLE(value, offset, byteLength[, noAssert])
Write value into buffer, It is determined by offset and byteLength and supports 48-bit calculations. When the noAssert value is true, the validity of value and offset is no longer verified. The default is false.
9buf.writeIntBE(value, offset, byteLength[, noAssert])
Write value into buffer, It is determined by offset and byteLength and supports 48-bit calculations. When the noAssert value is true, the validity of value and offset is no longer verified. The default is false.
10buf.readUIntLE(offset, byteLength[, noAssert])
Supports reading numbers below 48 digits. When the noAssert value is true, offset no longer verifies whether it exceeds the length of the buffer. The default is false.
11buf.readUIntBE(offset, byteLength[, noAssert])
Supports reading numbers below 48 digits. When the noAssert value is true, offset no longer verifies whether it exceeds the length of the buffer. The default is false.
12buf.readIntLE(offset, byteLength[, noAssert])
Supports reading numbers below 48 digits. When the noAssert value is true, offset no longer verifies whether it exceeds the length of the buffer. The default is false.
13buf.readIntBE(offset, byteLength[, noAssert])
Supports reading numbers below 48 digits. When the noAssert value is true, offset no longer verifies whether it exceeds the length of the buffer. The default is false.
14buf.toString([encoding[, start[, end]]])
According to the encoding parameter (default is 'utf8') returns a decoded string type. It will also use the passed parameters start (default is 0) and end (default is buffer.length) as the value range.
15buf.toJSON()
Convert a Buffer instance to a JSON object.
16buf[index]
Gets or sets the specified byte. The return value represents a byte, so the legal range of the return value is 0x00 to 0xFF in hexadecimal or 0 to 255 in decimal.
17buf.equals(otherBuffer)
Compares whether the two buffers are equal, if so, returns true, otherwise returns false .
18buf.compare(otherBuffer)
Compares two Buffer objects and returns a number, indicating that buf is before otherBuffer. After or the same.
19buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])
buffer copy, source and target can be the same. targetStart target start offset and sourceStart source start offset are both 0 by default. sourceEnd The source end position offset defaults to the length of the source buffer.length.
20buf.slice([start[, end]])
Cut the Buffer object according to start (default is 0 ) and end (default is buffer.length ) offset and clip the index. Negative indices are calculated from the end of the buffer.
21buf.readUInt8(offset[, noAssert])
Read a signed value based on the specified offset 8-bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. In this case the offset may extend beyond the end of the buffer. The default is false.
22buf.readUInt16LE(offset[, noAssert])
Use special endian words based on the specified offset Sequential format reads a signed 16-bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that offset may extend beyond the end of buffer. The default is false.
23buf.readUInt16BE(offset[, noAssert])
Reads a signed 16-bit integer using the special endian byte order format at the specified offset. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that offset may extend beyond the end of buffer. The default is false.
24buf.readUInt32LE(offset[, noAssert])
Use the specified endian word based on the specified offset Sequential format reads a signed 32-bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that the offset may extend beyond the end of the buffer. The default is false.
25buf.readUInt32BE(offset[, noAssert])
Use the specified endian word based on the specified offset Sequential format reads a signed 32-bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that the offset may extend beyond the end of the buffer. The default is false.
26buf.readInt8(offset[, noAssert])
Read a signed 8 based on the specified offset bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that offset may extend beyond the end of buffer. The default is false.
27buf.readInt16LE(offset[, noAssert])
Use special endian format based on the specified offset Read a signed 16-bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that offset may extend beyond the end of buffer. The default is false.
28buf.readInt16BE(offset[, noAssert])
Use the special endian format based on the specified offset Read a signed 16-bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that offset may extend beyond the end of buffer. The default is false.
29buf.readInt32LE(offset[, noAssert])
Use the specified endian word based on the specified offset Sequential format reads a signed 32-bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that the offset may extend beyond the end of the buffer. The default is false.
30buf.readInt32BE(offset[, noAssert])
Use the specified endian word based on the specified offset Sequential format reads a signed 32-bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that the offset may extend beyond the end of the buffer. The default is false.
31buf.readFloatLE(offset[, noAssert])
Use the specified endian word based on the specified offset Sequential format reads a 32-bit floating point number. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that the offset may extend beyond the end of the buffer. The default is false.
32buf.readFloatBE(offset[, noAssert])
Reads a 32-bit floating-point number using the specified endian byte order format at the specified offset. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that the offset may extend beyond the end of the buffer. The default is false.
33buf.readDoubleLE(offset[, noAssert])
Use the specified endian word based on the specified offset Sequential format reads a 64-bit double. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that the offset may extend beyond the end of the buffer. The default is false.
34buf.readDoubleBE(offset[, noAssert])
Use the specified endian word based on the specified offset Sequential format reads a 64-bit double. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that the offset may extend beyond the end of the buffer. The default is false.
35buf.writeUInt8(value, offset[, noAssert])
Convert value according to the incoming offset offset Write to buffer. Note: value must be a legal signed 8-bit integer. If the parameter noAssert is true, the offset offset parameter will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Don't use it unless you are very confident about this parameter. The default is false.
36buf.writeUInt16LE(value, offset[, noAssert])
According to the incoming offset offset and specification Write value to buffer in endian format. Note: value must be a legal signed 16-bit integer. If the parameter noAssert is true, the value and offset offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
37buf.writeUInt16BE(value, offset[, noAssert])
According to the incoming offset offset and specification Write value to buffer in endian format. Note: value must be a legal signed 16-bit integer. If the parameter noAssert is true, the value and offset offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
38buf.writeUInt32LE(value, offset[, noAssert])
Write value to the buffer according to the passed offset offset and the specified endian format. Note: value must be a legal signed 32-bit integer. If the parameter noAssert is true, the value and offset offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
39buf.writeUInt32BE(value, offset[, noAssert])
According to the incoming offset offset and specification Write value to buffer in endian format. Note: value must be a legal signed 32-bit integer. If the parameter noAssert is true, the value and offset offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
40buf.writeInt8(value, offset[, noAssert])<brOffset based on the incoming offset="" Amount will be written="" value="" to="" buffer="". Note: value="" must be a legal="" signed="" 8="" digit integer. ="" If parameter="" noassert="" is ="" true="" the ="" and ="" offset parameters will not be validated. ="" This means that ="" may be too large, or ="" may extend beyond the end of ="" causing ="" to be discarded. ="" Unless you are very sure about this parameter, try not to use it. Default is="" false. <="" td="">
buf.writeInt16LE(value, offset[, noAssert])Write the value into the buffer according to the incoming offset 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 offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. Default is false .
buf.writeInt16BE(value, offset[, noAssert])According to the incoming offset offset and specification Write value to buffer in endian format. Note: value must be a valid signed 16-bit integer. If the parameter noAssert is true, the value and offset offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. Default is false .
buf.writeInt32LE(value, offset[, noAssert])Writes value to the buffer based on the passed offset 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 offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
44buf.writeInt32BE(value, offset[, noAssert])
According to the incoming offset offset and specification Write value to buffer in endian format. Note: value must be a valid signed 32-bit integer. If the parameter noAssert is true, the value and offset offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
45buf.writeFloatLE(value, offset[, noAssert])
According to the incoming offset offset and specification Write value to buffer in 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 offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
46buf.writeFloatBE(value, offset[, noAssert])
According to the incoming offset offset and specification Write value to buffer in 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 offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
47buf.writeDoubleLE(value, offset[, noAssert])
According to the incoming offset offset and specification Write value to buffer in endian format. Note: value must be a valid 64-bit double value. If the parameter noAssert is true, the value and offset offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
48buf.writeDoubleBE(value, offset[, noAssert])
Writes value to the buffer based on the passed offset 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 offset parameters will not be verified. This means that the value may be too large, or the offset may exceed the end of the buffer causing the value to be discarded. Unless you are very sure about this parameter, try not to use it. The default is false.
49buf.fill(value[, offset][, end])
Use the specified value to fill this buffer . If offset (default is 0) and end (default is buffer.length) are not specified, the entire buffer will be filled.