Node uses buffer operations to encode and decode binary data.

Source: Internet
Author: User
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 ');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.