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
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 clippingNode buffer clipping syntax is as follows:
buf.slice([start[, end]])ParametersThe parameters are described as follows:
start - number, optional, default: 0
end - number, optional, default: buffer.length
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 lengthSyntaxNode buffer The area length calculation syntax is as follows:
buf.length;Return valueReturns 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 ManualThe Node.js Buffer module is listed below Commonly used methods (note that some methods are not available in older versions):
Serial number | Method & Description |
---|---|
1 | new 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. |
2 | new Buffer(buffer) Copy the data of parameter buffer to the Buffer instance. |
3 | new Buffer(str[, encoding]) Allocate a new buffer, which contains the incoming str string. encoding encoding defaults to 'utf8'. |
4 | buf.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. |
5 | buf.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. |
6 | buf.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. |
7 | buf.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. |
8 | buf.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. |
9 | buf.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. |
10 | buf.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. |
11 | buf.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. |
12 | buf.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. |
13 | buf.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. |
14 | buf.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. |
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 legal range of the return value is 0x00 to 0xFF in hexadecimal or 0 to 255 in decimal. |
17 | buf.equals(otherBuffer) Compares whether the two buffers are equal, if so, returns true, otherwise returns false . |
18 | buf.compare(otherBuffer) Compares two Buffer objects and returns a number, indicating that buf is before otherBuffer. After or the same. |
19 | buf.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. |
20 | buf.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. |
21 | buf.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. |
22 | buf.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. |
23 | buf.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. |
24 | buf.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. |
25 | buf.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. |
26 | buf.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. |
27 | buf.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. |
28 | buf.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. |
29 | buf.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. |
30 | buf.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. |
31 | buf.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. |
32 | buf.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. |
33 | buf.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. |
34 | buf.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. |
35 | buf.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. |
36 | buf.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. |
37 | buf.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. |
38 | buf.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. |
39 | buf.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. |
40 | buf.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. | |
44 | buf.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. |
45 | buf.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. |
46 | buf.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. |
47 | buf.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. |
48 | buf.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. |
49 | buf.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. |