Methods for processing binary data using the buffer class in Node.js _node.js

Source: Internet
Author: User
Tags json

Objective

In Node.js, a buffer class is defined, which is used to create a buffer that stores binary data specifically. This article introduced in detail the Node.js in the Buffer class processing binary data method, the following words do not say more, to see the detailed introduction.

Create a Buffer object

First: Use an array directly to initialize the buffer

var arr = [0,1,2]
var buf = new Buffer (arr)
Console.log (BUF)

Execution effect:


The second type: use a string directly to initialize the buffer

var str = ' Hello '
var buf = new Buffer (str)
Console.log (BUF)

Execution effect:


In Node.js, the encoding and decoding of the input and output of the string is performed automatically, and the UTF8 encoding is used by default.

Conversion between a buffer object and a String object

(1) toString

You can use the ToString method of the buffer object to convert the data stored in the buffer object to a string, using the following method:

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

Optional parameter 1: Specifies the text encoding format saved in the buffer object, and the default parameter is UTF8.

Optional parameter 2: Specifies the starting position, in bytes, of the converted data.

Optional Parameter 3: Specifies the ending location, in bytes, of the converted data.

The sample code is as follows:

var buf = new Buffer (' Why don't you wind up ')
Console.log (BUF)
console.log (buf.tostring (' UTF8 ', 9,12))
Console.log ( Buf.tostring (' UTF8 ', 12,buf.length))

The effect is as follows:

Control Desk

(2) Write

Sometimes we need to write a string to the buffer object we've created, and then we can use the Write method of the buffer object.

Buf.write (String,[offset],[length],[encodign])

Must be parameter 1: Specifies the string to write

Optional parameter 2-3: Specifies the write location after the string is converted to byte data, and the writing position of the byte data is from the first 1+offset byte to the offset+length byte.

Optional parameter 4: encoding format, default UTF8

The code is as follows:

var buf = new Buffer (' Why don't you go with the Wind ')
buf.write (' Soar thousands of Miles ', 0,buf.length)
Console.log (buf.tostring ())

The operation effect is as follows:


Control Desk

(3) Stringdecoder Object

In Node.js, you can also use the Stringdecoder object to convert data in a buffer object to a string that acts the same as the ToString method of the buffer object, but provides better support for strings that are encoded in UTF8 format.

When using the Stringdecoder object, you first need to load the String_decoder module in Node.js, as follows:

var Stringdecoder = require (' String_decoder '). Stringdecoder

After loading the String_decoder module, you can create a Stringdecoder object as follows:

var decoder = new Stringdecoder ([encoding])

When you need to convert data from a buffer object to a string, you can use the Write method of the Stringdecoder object, which can use a parameter to specify the buffer object that needs to be converted, and the method returns the converted string, as follows:

Decoder.write (buffer)

Okay, let's compare the buffer object's ToString method with the Stringdecoder write method who actually supports the UTF8 better.

The ToString method of buffer is as follows:

Converts 1 words to multiple bytes in the UTF-8 encoding format
var buf = new Buffer (' Why don't you go with the Wind ')
Console.log (BUF)

//0x is I manually added
var str1 = new Buffer ([0xe9, 0x98, 0x81, 0xe4, 0xb8, 0x8b, 0xe4, 0xbd])
Console.log (str1.tostring ())

var str2 = new buffer ([0x95 , 0xe4, 0xb8, 0x8d, 0xe9, 0x9a, 0x8f, 0xe9, 0xa3, 0x8e, 0xe8, 0xb5, 0xb7])
Console.log (str2.tostring ())

The operation effect is as follows:


Control Desk

Of course, you can also use the following method to connect the two buffer objects and then using the ToString method to convert the data into a string, but when the length of the buffer object is larger, the performance of this operation will become more underground.

Buffer.concat ([STR1,STR2]). ToString ()

The Write method for Stringdecoder is as follows:

Converts 1 words to multiple bytes in the UTF-8 encoding format
var buf = new Buffer (' Why don't you go with the Wind ')
Console.log (buf)

//stringdecoder
var Stringdecoder = require (' String_decoder '). Stringdecoder
var decoder = new Stringdecoder ()

//0x is my manually added
var str1 = new Buffer ([0xe9, 0x98, 0x81, 0xe4, 0xb8 , 0x8b, 0xe4, 0xbd])
Console.log (Decoder.write (str1))

var str2 = new Buffer ([0x95, 0xe4, 0xb8, 0x8d, 0xe9, 0x9a, 0 x8f, 0xe9, 0xa3, 0x8e, 0xe8, 0xb5, 0xb7])
Console.log (Decoder.write (STR2))

The operation effect is as follows:


Control Desk

Who supports a better glance can be seen.

Conversion between a buffer object and a JSON object

In Node.js, you can use the Json.stringify method to convert the data saved in a buffer object to a string, or you can use the Json.parse method to restore a converted string to an array.

Replicating cached data

When you need to copy binary data stored in a buffer object to another buffer object, you can use the Copy method of the buffer object, and the Copy method is used as follows:

Buf.copy (Targetbuffer,[targetstart],[sourcestart],[sourceend])

Must be parameter 1: Specifies the target buffer object for the replication

Optional Parameter 2: Specifies that data is written from the first byte in the target buffer object

Optional Parameter 3: Specifies the start position when fetching data from the copy source buffer object, default 0

Optional parameter 4: Specifies the end position when fetching data from the copy source buffer object, the default value being the length of the copied source object

The sample code is as follows:

Objective: To copy the contents of the BUF1 buffer object to the BUF2 buffer object
///Copy the target starting position of the Buf2 buffer object at 11th byte (11th byte out start write)
var buf1 = new Buffer (' Why don't you go with the Wind ')
Console.log (buf1)
var buf2 = new Buffer (128)
Buf2.fill (0)
console.log (BUF2)

Critical Code
buf1.copy (buf2,10)

/output buf2
console.log (BUF2)//

print as a string buf2
var Stringdecoder = require (' String_decoder '). Stringdecoder
var decoder = new Stringdecoder ()
Console.log (Decoder.write (BUF2))

The operation effect is as follows:


Control Desk

class method of Buffer class

(1) Isbuffer method

Used to determine whether an object is a buffer object, using the following methods:

Buffer.isbuffer (OBJC)

The sample code is as follows:

var a = ' abcde '
var b = new Buffer (a

) Console.log (typeof a)
Console.log (typeof b)
Console.log ('--- I am a wonderful separator----')
Console.log (Buffer.isbuffer (a))
Console.log (Buffer.isbuffer (b))

Run Result:


Control Desk

(2) ByteLength method

You can use the ByteLength method to calculate the number of bytes in a specified string, using the following method:

Buffer.bytelength (string,[encoding])

Must be parameter 1: Specifies a string to count the number of bytes

Optional parameter 2: encoding format, default UTF8

The sample code is as follows:

var str = ' Why don't you go with the Wind '
console.log (str.length)
console.log (buffer.bytelength (str, ' UTF8 '))
Console.log ( Buffer.bytelength (str, ' base64 '))
Console.log (buffer.bytelength (str, ' Utf16le '))

The results of the operation are as follows:


Control Desk

(3) Isencoding method

The Isencoding method is used to detect whether a string is a valid encoded format string. Use the following methods:

Buffer.isencoding (encoding)

In the Isencoding method, a parameter is used to specify the string to be instrumented, and if the string is a valid encoded format string, the method returns true and False if the string is not a valid encoded format string.

The sample code is as follows:

var str1 = ' UTF8 '
console.log (buffer.isencoding (str1))
var str2 = ' Utf16le '
console.log ( Buffer.isencoding (str2))
var str3= ' utf16e '
console.log (buffer.isencoding)

The operation effect is as follows:


Control Desk

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.

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.