Node uses buffer operations to encode and decode binary data.
1. Create a buffer
Create a buffer using a UTF-8 encoded string:
VaR Buf = new buffer ('Hello world! ');
You can also create a buffer using another encoded string, as long as the second input is passed in, that is, the encoding type.
VaR Buf = new buffer ('8b76fde713ce ', 'base64 ');
Three encoding methods are available: ASCII, utf8, and base64.
If you do not input any strings to create a buffer, you must input a length value, that is, the size of the buffer to be created:
VaR Buf = new buffer (1024); // creating a 1024 byte Buffer
After the buffer is created, you may need to assign a value to the buffer:
VaR Buf = new buffer ('My buffer content ');
// Access the value of 10 on the Buf
Console. Log (BUF [10]); //-> 99
You can easily modify its value:
Buf [99] = 125;
You can easily get the Buf length:
Console. Log (BUF. Length); //-> 100
Like other languages, there are also slice methods to cut the buffer for you.
1 var buffer = new Buffer("this is the content of my buffer");2 var smallerBuffer = buffer.slice(8, 19);3 console.log(smallerBuffer.toString()); // -> "the content"
Copy Buffer:
1 var buffer1 = new buffer ("this is the content of my buffer"); 2 var buffer2 = new buffer (11); 3 var targetstart = 0; 4 var sourcestart = 8; 5 var sourceend = 19; 6 buffer1.copy (buffer2, targetstart, sourcestart, sourceend); // copy the content of buffer1 to the 7 console of buffer2. log (buffer2.tostring (); //-> "the content"
Buffer can be converted to utf8 encoding by using the tostring () method:
VaR STR = Buf. tostring ();
Of course, you can also specify other encoding formats:
VaR b64str = Buf. tostring ("base64 ");
As follows, you can convert UTF-8 encoded strings to base64 encoded strings:
VaR utf8string = 'my string ';
VaR Buf = new buffer (utf8string );
VaR base64string = Buf. tostring ('base64 ');