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

How to use the buffer module in Nodejs

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "how to use the buffer module in Nodejs". In daily operation, I believe many people have doubts about how to use the buffer module in Nodejs. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the buffer module in Nodejs". Next, please follow the editor to study!

What is 1.buffer?

We know that JS has corresponding methods API to deal with strings, arrays, numbers, Boolean values, etc., but in Node, it also needs the ability of file operation, network communication, database operation, data transmission and so on. Files are expressed in binary form at the storage level, and the data transmission in the request and response of http is also in binary data transmission, so only the current JS capability is not enough, and the buffer module is provided in Node.

That is, NodeJS has the ability to manipulate binary data in the same way as strings. Buffer is also known as a temporary storage area, which is a piece of memory that temporarily stores input and output binary data.

In a previous article about the core module in Nodejs: the stream streaming module (see how to use it), we learned that when reading large files, they generally do not read them all into memory at once, but read a block of data in the form of a stream, and successive blocks form the concept of data flow. In the process of reading and writing to the data block, the data is first stored in the memory of the buffer (temporary storage area) to be processed.

1.1 understanding buffer memory allocation

The memory allocation of buffer objects is not in the V8 heap memory, but in the C++ level of Node. In order to use the requested memory efficiently, slab allocation mechanism (a dynamic memory management mechanism) is adopted in Node.

The overall situation of 1. 2 buffer

Node buffer has been installed into memory when the process is started and put into the global object, which can be used without require introduction, but it is officially recommended to refer to it explicitly through import or require statements.

two。 Create Buffer

Buffer instances can be created manually, in addition to file reads and http requests.

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

Parameters:

Size: buffer length

Fill: pre-filled value. Default: 0

Encoding: if fill is a string, it is the encoding of the string. Default: utf-8.

Import {Buffer} from 'buffer';const buf = Buffer.alloc (8); console.log (buf); / /

2.2 Buffer.allocUnsafe (size)

Parameters:

Size: the length required for the new 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.

Import {Buffer} from 'buffer';const buf = Buffer.allocUnsafe (8); console.log (buf); / /

2.3 Buffer.from (string [, encoding])

Create a new buffer with incoming string

Parameters:

String: string

Encoding: encoding. Default value: utf-8

Import {Buffer} from 'buffer';const buf = Buffer.from (' hello buffer'); console.log (buf); / /

2.4 Buffer.from (array)

Use byte array in the range of 0-255to allocate a new Buffer.

Import {Buffer} from 'buffer';const array = [0x62, 0x78, 0x84]; const buf = Buffer.from (array); console.log (buf); / / 3. Copy Buffer

3.1 Buffer.from (buffer)

Parameters:

Buffer, the buffer instance to be replicated

Import {Buffer} from 'buffer';// New const buf1 = Buffer.alloc (10,2); / / copy const buf2 = Buffer.from (buf1); console.log (buf1); / / console.log (buf2); / /

3.2 buf.copy (target [, targetStart [, sourceStart [, sourceEnd])

Copy the buf instance to the target destination

Import {Buffer} from 'buffer';const buf1 = Buffer.alloc (10,2); const buf2 = Buffer.allocUnsafe (10) / / copy buf1 to buf2buf1.copy (buf2); console.log (buf1); / / console.log (buf2); / / 4. Splicing Buffer

4.1 Buffer.concat (list [, totalLength])

Returns the new buffer where all the buffer instances in the list are connected

Parameters:

List: |

TotalLength: total length of the connection.

Note:

If the list has no entries, or if totalLength is 0, a new zero-length Buffer is returned.

If totalLength is not provided, it is calculated from the Buffer instance in list by adding its length.

Import {Buffer} from 'buffer';const buf1 = Buffer.alloc (4,2); const buf2 = Buffer.alloc (4,3); const buf3 = Buffer.concat ([buf1, buf2]); console.log (buf1); / / console.log (buf2); / / console.log (buf3); / / 5. Intercept Buffer

5.1 buf.slice ([start [, end]])

If a new Buffer instance is returned from the buf instance, the new Buffer instance returned is only a reference to the source buf instance, that is, modifications to the newly returned instance will affect the original Buffer instance.

Parameters:

Start: start position, default 0

End: end position, default buf.length

Import {Buffer} from 'buffer';const buf1 = Buffer.alloc (10, 2); / intercept const buf2 = buf1.slice (1Magne4); / / modify buf2 [0] = 0x63 position console.log (buf1); / / console.log (buf2); / / 6. Populate Buffer

6.1 buf.fill (value [, offset [, end]] [, encoding])

Parameters:

Value, fill valu

Offset: the number of bytes to skip before starting to populate buf. The default is 0.

End: where to end filling buf (not included). Default is buf.length.

Encoding. String encoding if the value value is a string. Default is utf-8.

Import {Buffer} from 'buffer';const buf1 = Buffer.allocUnsafe (8) .fill (2); console.log (buf1); / /

6.2 buf.write (string [, offset [, length]] [, encoding])

Writes the string to the offset of the buf based on the character encoding in encoding.

Note: the length parameter is the number of bytes to write. If the buf does not have enough space to hold the entire string, only part of the string will be written

Parameters:

String: string value written

Offset: the number of bytes to skip before starting writing to string. The default is 0.

Length: maximum number of bytes written. Default is buf.length-offset.

Encoding: encoding, default utf-8

Import {Buffer} from 'buffer';// buf1 length is 12const buf1 = Buffer.alloc (12,3); / / write offset is greater than buf1.length, write invalid buf1.write (' hello', 12); console.log (buf1); / / partially write buf1.write ('hello', 10); / / 7. Buffer tool method

7.1 Buffer.isBuffer (obj)

Verify whether the incoming obj is buffer

Import {Buffer} from 'buffer';const buf1 = Buffer.alloc (12,3); console.log (Buffer.isBuffer (buf1)); / / true

7.2 Buffer.isEncoding (encoding)

Check whether the passed encoding name is supported by Buffer

Import {Buffer} from 'buffer';console.log (Buffer.isEncoding (' utf-8')) / / true8. Conversion between Buffer and String

Buffer to String

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

Parameters:

Encoding: string encoding used, default utf-8

Start, start position, default 0

End, end position, default buf.length

Import {Buffer} from 'buffer';const buf1 = Buffer.allocUnsafe (26) for (let I = 0; I < 26; iTunes +) {/ / 97 is the decimal ASCII value of' a'. Buf1 [I] = I + 97;} console.log (buf1.toString ()) / / abcdefghijklmnopqrstuvwxyz

String to Buffer

8.2 Buffer.from (string [, encoding])

Parameters:

String: string

Encoding: encoding. Default value: utf-8

Import {Buffer} from 'buffer';const buf = Buffer.from (' hello buffer'); console.log (buf); / / 9. Comparison between Buffer and Array

9.1 similar to Array

You can use the subscript to get the value of the specified location

You can use the length property to get the Buffer size

You can use for...of to traverse

9.2 what is different from Array

It stores two digits in hexadecimal.

Value is 0-255

Support multiple encoding formats

Memory is not allocated in the V8 heap

The bottom layer is implemented by C++, and the upper layer is controlled by js.

At this point, the study on "how to use the buffer module in Nodejs" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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