Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Buffer object in Node.js and how to create it?

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What is the Buffer object in Node.js and how to create it? in view of this question, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

What is Buffer?

The js language itself has only string data types, not binary data types, and when dealing with TCP and file streams, it must deal with binary data.

Node.js provides a Buffer object to provide operations on binary data.

The Buffer class is a global variable in Node.js and can be used directly without introducing a module.

An instance of the Buffer class is similar to an array of integers, but the size of the Buffer is fixed and physical memory is allocated outside the V8 heap. The size of the Buffer is determined when it is created and cannot be resized.

Note that all binary data is stored in Buffer, but it is displayed in hexadecimal when displayed.

The range of each element in Buffer ranges from (00-ff) to (0255).

Let str = 'Hello word'let buf = Buffer.from (str); / / Save the string to Buffer console.log (buf) / / Buffer.length indicates the amount of memory consumed

Because Chinese characters occupy 3 bytes, buf.length prints out 12, while the length of the string is 8.

Let str = 'Hello Little Xuan' let buf = Buffer.from (str); console.log (str.length); / / 8console.log (buf.length); / / 12Buffer will be displayed in decimal mode when printing numbers

We create a 5-length Buffer object and add characters and numbers to it as follows. When we print characters and numbers respectively, we will find that the numbers will be displayed in decimal system.

Let buf = Buffer.alloc (5); buf [0] = "a"; buf [1] = 10 ETBUF [2] = 15 BUF [3] = 20 BUF [4] = 25 console.log (buf [1]) / / 10console.log (buf [2]); / / the creation method of the 15Buffer is through the constructor of Buffer, but is not recommended

Such as creating a Buffer of a specified size

Let buf = new Buffer (10); console.log (buf); / /

We opened the official document of node.js Chinese website and found that all the construction methods of Buffer have been abandoned, so I won't focus on this part.

Through the allocUnsafe method

Syntax:

Buffer.allocUnsafe (size)

Size: required parameter, length required for Buffer.

The underlying memory of Buffer instances created in this manner is not initialized. The content of the newly created Buffer is unknown and may contain sensitive data. If the allocUnsafe method is used, he does not clean up the data when allocating memory, and if there is data in the allocated memory, it will cause a data leak. But its performance is better than that of alloc method.

Let buf = Buffer.allocUnsafe (10); console.log (buf); / / through the alloc method

Syntax:

Buffer.alloc (size [, fill [, encoding]])

Size: required parameter, length required for Buffer.

Fill: optional parameter, which is used to pre-fill the value of the new Buffer. Default value: 0.

Encoding: optional parameter, if fill is a string, then this is its encoding. Default value: 'utf8'.

Creates a Buffer object with a specified size of 10.

If you pass in the required parameter 10, then its default fill is undefined, and Buffer will be populated with zero.

If the optional parameter fill is 1, fill it with 1.

Finally, you can pass in the encoding format of fill, indicating how fill will be encoded.

Let buf = Buffer.alloc (10); console.log (buf); / / let buf1 = Buffer.alloc (10Magne1) console.log (buf1); / / let buf2 = Buffer.alloc (10Mae 1, "utf8") console.log (buf2); / /

The alloc method initializes the Buffer cache, which ensures that the contents of the newly created Buffer instance never contain sensitive data from previous allocations, including data that may not have been assigned to the Buffer.

Through the Buffer.from () method

1. Create through an array

Syntax:

Buffer.from (array)

Array: a required parameter that allocates a new Buffer with byte array in the range of 0-255. Array entries outside the range will be truncated to match it.

By creating it, we find that the range of face values in the array is 00-FF, and it cannot be a value of character type.

Const buf = Buffer.from ([1Jing 3jue 5je 7jue 4]); console.log (buf) / / const buf1 = Buffer.from (["a", "b", "c"]); console.log (buf1) / /

2. Create through string

Syntax:

Buffer.from (string [, encoding])

String: the string to be encoded by the required parameter.

Encoding: the encoding of the optional parameter string. Default value: 'utf8'.

Const buf1 = Buffer.from ('this is an example'); console.log (buf1); / convert it to a string console.log (buf1.toString ()) / / this is an example write buffer through the ToString method

Syntax:

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

String: required parameter, the string written to the buffer.

Offset: optional parameter. The index value that the buffer begins to write. The default is 0.

Length: optional parameter, number of bytes written. Default is buffer.length.

Encoding: optional parameter, encoding used. The default is' utf8'.

Return value: returns the actual write size. If there is not enough buffer space, only part of the string will be written.

Const buf = Buffer.alloc; const len = buf.write ("this is an example"); console.log ("bytes written:" + len); / / 17 read data from buffer

Syntax:

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

Encoding: optional parameter, encoding used. The default is' utf8'.

Start: optional parameter that specifies the location of the index to start reading. The default is 0.

End: optional parameter, end position, default to the end of the buffer.

Return value: decodes the buffer data and returns the string using the specified encoding.

Buf = Buffer.alloc (26); for (let I = 0; I < 26; iTunes +) {buf [I] = I + 65;} console.log (buf.toString ('ascii')); / / output: ABCDEFGHIJKLMNOPQRSTUVWXYZconsole.log (buf.toString (' ascii',0,10)); / / use 'ascii' encoding and output: ABCDEFGHIJconsole.log (buf.toString (' utf8',10,15)) / / use 'utf8' encoding and output: KLMNOconsole.log (buf.toString (undefined,15,26)); / / use the default' utf8' encoding, and output: PQRSTUVWXYZ converts Buffer to JSON object

Syntax:

Buf.toJSON ()

Return value: the JSON object is returned.

Const buf = Buffer.from ([0x1, 0x2, 0x3, 0x4, 0x5]); const json = JSON.stringify (buf); console.log (json) / / {"type": "Buffer", "data": [1, 2, 4, 5]} copy buffer

Syntax:

Buf.copy (targetBuffer [, targetStart [, sourceStart [, sourceEnd]])

TargetBuffer-required parameter, the Buffer object to copy.

TargetStart-numeric, optional, default: 0

SourceStart-numeric, optional, default: 0

SourceEnd-numeric, optional, default: buffer.length

Var buf1 = Buffer.from ('ABCDEFGHIJKLMNOP'); var buf2 = Buffer.from (' UVWXYZ'); / / insert buf2 into the location specified by buf1 buf2.copy (buf1, 2); console.log (buf1.toString ()); buffer and iterator

You can use for... Of syntax iteration Buffer example:

It is displayed in decimal after iteration.

Const buf = Buffer.from ([oxc,2,3,4,5]); console.log (buf) / / for (const b of buf) {console.log (b);} / 12max / 2max / 3pm / 4max / 5const buf = Buffer.from ('string'); console.log (buf) / / for (const b of buf) {console.log (b); / 115lash / 116max / 114max / 105p / 110x summary

1. The Buffer object is an interface for Node to process binary data. It is a global object natively provided by Node and can be used directly.

2. The requests and responses of the network layer to different resources interact with each other in binary form. Strings in javascript are stored in utf-8 format, and the ability to handle binaries is weak, so you need to use Buffer to deal with binary data.

This is the answer to the question about the Buffer object in Node.js and how to create it. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report