node. js buffer (buffer)

Source: Internet
Author: User
Tags tojson

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.

Create a Buffer class

The Node Buffer class can be created in several ways.

Method 1

Create a Buffer instance with a length of 10 bytes:

var=newBuffer(ten);     
Method 2

Creates a Buffer instance from the given array:

var=newBuffer([ten, +, +, +]);   
Method 3

Create a Buffer instance with a string:

var=newBuffer("aaaaaa","Utf-8");       

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

Write buffer syntax

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

BUF.  Write(string[, offset[, length]][, encoding])   
Parameters

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 '.

return value

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

Instance
=NewBuffer(n);  = buf.  Write("aaaaaaa");  Console.  Log("number of bytes written:"+ len);            

Execute the above code and the output is:

$node main.  JS Write bytes  : 7
Read data syntax from buffer

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

BUF.  ToString([encoding[, start[,end]])      
Parameters

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 a string using the specified encoding.

Instance
Buf= New Buffer(26);For (VarI= 0 ;I< 26 ;I++) {Buf[I] =I+ 97;}Console.Log(Buf.Tostring(' ASCII ')); Output: ABCDEFGHIJKLMNOPQRSTUVWXYZConsole.Log(Buf.Tostring(' ASCII ',0,5)); //output: Abcdeconsole. ( Buf. Tostring ( ' UTF8 ' ,0,< Span class= "lit" >5 //output: Abcdeconsole. ( Buf. Tostring (undefined,0 , 5 //using ' UTF8 ' encoding and output: ABCDE          

Execute the above code and the output is:

$ node main.  JSABCDEFGHIJKLMNOPQRSTUVWXYZABCDEABCDEABCDE 
Convert Buffer to JSON object syntax

The function syntax for converting Node Buffer to a JSON object is formatted as follows:

BUF.  ToJSON()  
return value

Returns a JSON object.

Instance
var=newBuffer(' node. js ');  var= buf.  ToJSON(buf);  Console.  Log(json);                

Execute the above code, the output is? You can try the results.

Buffer Merge Syntax

The syntax for the Node buffer merge is as follows:

Buffer.  Concat(list[, totallength])      
Parameters

The parameters are described as follows:

    • List-the array of Buffer objects used for merging.

    • totallength -Specifies the total length of the merged buffer object.

return value

Returns a new Buffer object with multiple members merged.

Instance
VarBuffer1= New Buffer(' Node Tutorial ');var Buffer2 = new buffer ( ' AAAAA ' var Buffer3 = buffer< Span class= "pun". concat ([buffer1, Buffer2console. +. Tostring              

Execute the above code and the output is:

Content: node tutorial aaaaa  
Buffer comparison Syntax

The function syntax for node Buffer comparison is shown below, which was introduced in the node. JS v0.12.2 Version:

BUF.  Compare(otherbuffer);    
Parameters

The parameters are described as follows:

    • Otherbuffer -another Buffer object compared to the buf object.

return value

Returns a number that represents buf before, after, or the same as Otherbuffer .

Instance
VarBuffer1= New Buffer(' ABC ');VarBuffer2= New Buffer(' ABCD ');VarResult=Buffer1.Compare(Buffer2);If(Result< 0) {Console.Log(Buffer1+ In +Buffer2+ Before);}Else If(Result== 0){Consolelog (buffer1 +  + Buffer2 +   "Same" }else { Consolelog (buffer1 +  " + Buffer2 +   "               /span>                

Execute the above code and the output is:

ABC   before ABCD 
Copy buffer syntax

The Node buffer copy syntax is as follows:

BUF.  Copy(targetbuffer[, targetstart[, sourcestart[, sourceend]]) 
Parameters

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.

Instance
VarBuffer1= New buffer ( ' ABC ' //copy a buffer var Buffer2 =  new buffer ( 3); buffer1.buffer2. Log ( "Buffer2 content:"  +  Buffer2.              

Execute the above code and the output is:

Buffer2 content: ABC 
Buffer clipping

The Node buffer clipping syntax is as follows:

BUF.  Slice([start[,end]])      
Parameters

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.

Instance
Var Buffer1 = new buffer ( ' Runoob ' //cut buffer var Buffer2 =< Span class= "PLN" > Buffer1.0,2. Log ( "Buffer2 content:"  +  Buffer2.              

Execute the above code and the output is:

Buffer2 content: ru 
Buffer length Syntax

The Node buffer length calculation syntax is as follows:

BUF.  Length;  
return value

Returns the memory length occupied by the Buffer object.

Instance
var=newBuffer(' aaaaaa ');  Buffer length console.  Log("buffer length:"+ buffer. ) Length);                

Execute the above code and the output is:

Buffer length: 6

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.