' node. js ' buffer (buffer)

Source: Internet
Author: User

In node. js, a buffer class is defined that is used to create a buffer that is dedicated to storing the binary data.

Create a Buffer class

The Node Buffer class can be created in several ways.

1. Create a Buffer instance with a length of 10 bytes:

var New Buffer (10);

2. Create a Buffer instance from the given array:

var New Buffer ([10, 20, 30, 40, 50]);

3. Create a Buffer instance with a string:

var New Buffer ("www.runoob.com", "utf-8");

Utf-8 is the default encoding method, and it also supports the following encodings: "ASCII", "UTF8", "Utf16le", "UCS2", "base64" and "hex".

Write buffers

The syntax for writing to the Node buffer is as follows:

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

Returns the actual write size. If the buffer space is insufficient, only a partial string is written.

New Buffer (= Buf.write ("www.runoob.com"); Console.log ("bytes written:" +  len);

Reading data from a buffer

The syntax for reading the Node buffer data is as follows:

Buf.tostring ([encoding[, start[, end]])

Decodes the buffer data and returns a string using the specified encoding.

New Buffer (+);  for (var i = 0; i <; i++) {  = i + +;} Console.log (buf.tostring (' ASCII '));       // output: abcdefghijklmnopqrstuvwxyzconsole.log (buf.tostring (' ASCII ', 0,5));   // output: ABCDEconsole.log (buf.tostring (' UTF8 ', 0,5));    // Output: ABCDE // use ' UTF8 ' encoding, and output: ABCDE

Convert Buffer to JSON object

Buf.tojson ()

Buffer Merge

Buffer.concat (list[, Totallength])

Buffer comparison

Buf.compare (Otherbuffer);

Copy buffer

Buf.copy (targetbuffer[, targetstart[, sourcestart[, Sourceend]])

Buffer clipping

Buf.slice ([start[, end]])

Buffer length

Buf.length;

' node. js ' buffer (buffer)

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.