The JavaScript language itself has only a string data type and no binary data type.
However, when processing a TCP stream or file stream, you must use the binary data. Therefore, in node. js, a buffer class is defined that is used to create a buffer that is dedicated to storing the binary data .
In node. js, the Buffer class is the core library that is published with the Node kernel. The buffer library provides a way for node. JS to store the raw data, allowing node. js to process the binary data, possibly using the buffer library whenever data moved in the I/O operation needs to be handled in node. js. The raw data is stored in an instance of the Buffer class. A Buffer is similar to an array of integers, but it corresponds to a piece of raw memory outside of the V8 heap memory.
Creating a Buffer object before v6.0 directly uses the new buffer () constructor to create an object instance, but Buffer has a large amount of memory permission operations and can capture some sensitive information directly, so after v6.0, the official document is recommended to use buffer.from () interface to create a Buffer object .
one, Buffer and character encoding
A Buffer instance is typically used to represent a sequence of encoded characters, such as UTF-8, UCS2, Base64, or hexadecimal encoded data. By using an explicit character encoding, you can convert a Buffer instance to a normal JavaScript string.
const BUF = Buffer. from ('runoob'ascii'); // output cnvub29iconsole.log (buf.tostring ('base64'));
Second, create the Buffer class
Buffer provides the following APIs to create the buffer class:
Buffer.alloc (size[, fill[, encoding]): Returns a Buffer instance of the specified size, and if no fill is set, the default fills 0
Buffer.allocunsafe (size): Returns a Buffer instance of the specified size, but it is not initialized, so it may contain sensitive data
Buffer.allocunsafeslow (size)
Buffer.from (Array): Returns a new Buffer instance initialized with the value of array (the element of the incoming array can only be a number, or it will be automatically overwritten by 0)
Buffer.from (arraybuffer[, byteoffset[, length]): Returns a new Buffer that shares the same memory as the given ArrayBuffer.
Buffer.from (buffer): Copies the data of the incoming buffer instance and returns a new buffer instance
Buffer.from (string[, encoding]): Returns a new Buffer instance initialized with the value of string
//Create a Buffer with a length of 10 and a 0 fill. ConstBUF1 = Buffer.alloc (Ten);//creates a Buffer with a length of 10 and is populated with 0x1. ConstBuf2 = Buffer.alloc (Ten,1);//creates a Buffer with a length of 10 and is not initialized. //This method is faster than calling Buffer.alloc (),//However, the returned Buffer instance may contain old data,//Therefore, you need to use fill () or write () overrides. ConstBUF3 = Buffer.allocunsafe (Ten);//Create a Buffer containing [0x1, 0x2, 0x3]. ConstBUF4 = Buffer. from([1,2,3]);//Create a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74]. ConstBuf5 = Buffer. from('Tést');//Create a Buffer that contains Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. ConstBUF6 = Buffer. from('Tést','latin1');
third, write buffer
The syntax for writing to the Node buffer is as follows:buf. Write(string[, offset[, length]][, encoding])
The parameters are described as follows:
String-Writes the buffer to the strings.
Offset-the index value at which the buffer begins writing, by default, 0.
Length-the number of bytes written, default is Buffer.length
Encoding-the encoding used. The default is ' UTF8 '.
Writes the offset position in string to BUF based on the character encoding of the encoding. The length parameter is the number of bytes written. If BUF does not have enough space to hold the entire string, it is only written as part of the string. Only partially decoded characters are not written.
return Value: returns the actual write size. If the buffer space is insufficient, only a partial string is written.
BUF = Buffer.alloc (buf.write ("www.runoob.com"); Console.log (""+ len); // number of bytes written:
iv. reading data from a buffer
The syntax for reading the Node buffer data is as follows:buf. ToString([encoding[, start[, end]])
The parameters are described as follows:
Encoding-the encoding used. The default is ' UTF8 '.
Start-Specifies the index position at which to start reading, which defaults to 0.
End-the ending position, which defaults to the end of the buffer.
return value: decodes the buffer data and returns the string using the specified encoding.
BUF = Buffer.alloc ( -); for(vari =0; I < -; i++) {Buf[i]= i + the;} Console.log (Buf.tostring ('ASCII'));//Output: abcdefghijklmnopqrstuvwxyzConsole.log (Buf.tostring ('ASCII',0,5));//Output: ABCDEConsole.log (Buf.tostring ('UTF8',0,5));//Output: ABCDEConsole.log (buf.tostring (Undefined,0,5));//use ' UTF8 ' encoding, and output: ABCDE
v. Convert Buffer to a JSON object
The function syntax for converting Node Buffer to a JSON object is formatted as follows:buf. ToJSON()
When a Buffer instance is serialized, Json.stringify () implicitly invokes the ToJSON ().
Return value: Returns the JSON object.
ConstBUF = Buffer. from([0x1,0x2,0x3,0x4,0x5]);ConstJSON =json.stringify (BUF);//output: {"type": "Buffer", "Data": [1,2,3,4,5]}Console.log (JSON);Constcopy = Json.parse (JSON, (key, value) = = { returnValue && Value.Type = = ='Buffer'?Buffer. from(Value.data): value;});//output: <buffer 05>Console.log (copy);
vi. consolidation of buffers
The syntax for Node buffer merging is as follows:buffer. Concat(list[, totallength])
The parameters are described as follows:
return value: Returns a new Buffer object with multiple members merged.
var buffer1 = Buffer. From ( " Baidu " var buffer2 = Buffer. from (( " www.baidu.com ' var buffer3 = Buffer.concat ([Buffer1,buffer2]); Console.log ( " buffer3 content: " + buffer3.tostring ()); // buffer3 content: Baidu www.baidu.com
Seven, buffer comparison
The function syntax for node Buffer comparison is shown below, introduced in the node. js v0.12.2 version:buf. Compare(otherbuffer);
The parameters are described as follows:
Return value: Returns a number that represents buf before, after, or the same as Otherbuffer.
varBuffer1 = Buffer. from('ABC');varBuffer2 = Buffer. from('ABCD');var result=Buffer1.compare (buffer2);if(Result <0) {Console.log (Buffer1+"in the"+ Buffer2 +"before");}Else if(Result = =0) {Console.log (Buffer1+"with the"+ Buffer2 +"same");}Else{console.log (buffer1+"in the"+ Buffer2 +"after");}
Eight, copy buffer
The Node buffer copy syntax is as follows:buf. Copy(targetbuffer[, targetstart[, sourcestart[, sourceend]])
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 return value.
var buf1 = Buffer. from ('abcdefghijkl'); var buf2 = Buffer. from ('runoob'); // inserts the BUF2 into the buf1 specified position 2 ); Console.log (buf1.tostring ()); // abrunoobijkl, inserting starting at index 2
Nine, buffer clipping
The Node buffer clipping syntax is as follows:buf. Slice([start[, end]])
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 piece of memory as the old buffer, but cuts from the index start to end.
var buffer1 = Buffer. from ('runoob'); // clipping buffers var buffer2 = Buffer1.slice (0,2); Console.log (" " + buffer2.tostring ()); // buffer2 Content:ru
10. Buffer length
The Node buffer length calculation syntax is as follows:buf. Length;
Return value: Returns the memory length occupied by the Buffer object.
var buffer = buffer. from ('www.baidu.com'); // buffer length--13console.log ("" + buffer.length);
Node.js:Buffer (buffer) Introduction and common methods