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 Buffer object in Node.js

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how to use the Buffer object in Node.js. I hope you will get something after reading this article. Let's discuss it together.

Buffer is the built-in type of Node.js, which is used to represent an area of memory to hold binary data, which can be thought of as a binary array.

Buffer can be used to represent binary data such as pictures and videos. In addition, what we read from the file is also Buffer type data, and the data received from the network is also Buffer type data, so it is necessary to learn Buffer.

Buffer is in the global scope, so there is no need to introduce Buffer through require ('buffer').

Create a Buffer object alloc

We can allocate a size byte of memory through Buffer.alloc (size, [fill], [encoding]) and receive two optional parameters

Fill: use fill to populate every byte in Buffer

Encoding: if fill is a string, use encoding to encode the string to binary

When the fill parameter is not specified, the default is filled with 0.

Const buf1 = Buffer.alloc (5); console.log (buf1); / / const buf2 = Buffer.alloc (10,1); console.log (buf2); / / const buf3 = Buffer.alloc (12, "hello world!", "utf-8"); console.log (buf3); / /

We can also use allocUnsafe (size) to allocate a specified size of memory, but it will not be populated with 0 by default, and the contents are uncertain.

Const buf = Buffer.allocUnsafe (5); console.log (buf); / /

We can populate the specified value for the Buffer object through the fill (fill, encoding) method

Const buf = Buffer.allocUnsafe (5); buf.fill (0); console.log (buf); / / from

We can also use the Buffer.from () method to create a Buffer object, and the parameters that the from method can receive include arrays, strings, Buffer objects, objects, and so on.

Receive an integer array whose integers should be between 0,255 and truncated.

Const buf = Buffer.from ([1,2,3,4,5]); console.log (buf); / /

We can also pass in a string and specify an encoding, which encodes the string into binary using the specified encoding, which defaults to utf-8 if no encoding is specified

Const buf = Buffer.from ("hello", "utf-8"); console.log (buf); / /

The from method can also receive a Buffer object, which copies the data from the incoming Buffer object into the new Buffer object

Const buf1 = Buffer.from ("hello", "utf-8"); const buf2 = Buffer.from (buf1); console.log (buf1 = buf2); / / falseconsole.log (buf2.toString ()); / / hello

The from method can also receive an object. When an object is passed in, the object is first converted to the original value, and then to the corresponding binary array according to the original value.

Let obj = {[Symbol.toPrimitive] (hint) {return "a";},},}; const buf = Buffer.from (obj); console.log (buf.toString ()); / / property length of the aBuffer object

You can know the length of the Buffer array through the length attribute

Const buf = Buffer.from ("Hello World!"); console.log (buf.length); / / 12buffer

What actually stores data inside the Buffer object is an ArrayBuffer object, which can be obtained through the buffer property.

Const buf = Buffer.alloc (5); console.log (buf.buffer); / / ArrayBuffer {[Uint8Contents]:, byteLength: 5} read Buffer object

This section describes how to access the contents of the Buffer object.

Subscript

As mentioned at the beginning of the article, we can think of the Buffer object as a binary array, and since it is an array, we can access the contents of the array in the form of subscripts.

Const buf = Buffer.from ([1,2,3,4,5]); console.log (buf [0]); / / 1console.log (buf [5]); / / undefined

They parse the bytes in the form of complements and return the corresponding numbers.

ReadXxx

We can also access the contents of the Buffer object through methods such as buf.readInt8 () buf.readInt16 () buf.readUint8 () buf.readUint16 ().

Const buf = Buffer.from ([1, 2, 3, 4, 5]); console.log (buf.readInt8 (2)); / / 3According to content out of range, RangeErrorconsole.log (buf.readInt8 (5)) is thrown; / / RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. Iterator

The iterator of the Buffer object is the same as that of the array, and there are also three iterators, which are

Entries

Keys

Values

We access the contents of the Buffer object by traversing the iterator.

Const buf = Buffer.from ([3,4,2]); one element of the for (let entry of buf.entries ()) {/ / array is the subscript, and the second element is the element console.log (entry) corresponding to the subscript / / [0,3] / / [1,4] / / [2,2]} for (let key of buf.keys ()) {console.log (key); / / 0 / / 1 / / 2} for (let value of buf.values ()) {console.log (value) / / 3 / / 4 / / 2} write Buffer object

This section explains how to write to a Buffer object.

Subscript

We can change the contents of the Buffer object directly through the subscript

Const buf = Buffer.from ([1,2,3]); / / set the value buf [0] = 4 position console.log (buf) through the subscript; / / write

We can write a string to Buffer through the write (string, [offset], [length], [encoding]) method:

String: represents the string to write

Offset: offset, that is, skipping offset bytes to start writing. Default is 0.

Length: the maximum number of bytes to be written, which does not exceed buf.length-offset. The default is buf.length-offset.

Encoding: specifies the encoding. Default is utf-8.

This method returns the number of bytes written.

Const buf = Buffer.from ([1,2,3,4]); / / skip 1 byte to start writing, 1hi4buf.write ("hi", 1); console.log (buf); / / writeXxx

Like readXxx, we can write data to buf through the writeInt8 () method, which receives two parameters:

Value: the value to write

Offset: offset. Default is 0.

Const buf = Buffer.alloc (5); buf.writeInt8 (1,0); buf.writeInt8 (3,1); console.log (buf); / /

Trample: there is no writeInt16 (), but there are writeInt16BE () and writeInt16LE (), which represent writing in large end order and small end order, respectively.

Other methods isBuffer

This method receives an object to determine whether the object is a Buffer object or not

Let obj1 = {}; let obj2 = Buffer.alloc (3); console.log (Buffer.isBuffer (obj1)); / / falseconsole.log (Buffer.isBuffer (obj2)); / / trueisEncoding

This method receives a string representing the encoding, returns whether Buffer supports the encoding, and returns true if it is supported, or false otherwise

Console.log (Buffer.isEncoding ("utf-8")); / / trueconsole.log (Buffer.isEncoding ("utf8")); / / trueconsole.log (Buffer.isEncoding ("hex")); / / trueconsole.log (Buffer.isEncoding ("latin")); / / falseconsole.log (Buffer.isEncoding ("gbk")); / / falseslice

Slice (start, end) can trim the original Buffer object and return a new Buffer object, where start and end represent the start and end positions of the trimming, left closed and right open [start, end). These two parameters are optional. Start defaults to 0 and defaults to buf.length. The returned Buffer object refers to the same block of memory as the previous object, that is, their buffer property is the same.

Const buffer = Buffer.from ("hello world!"); const newBuffer = buffer.slice (6); / / trim the content after 6 to the new array console.log (newBuffer.toString ()); / / worldworldconsole.log (buffer.buffer = newBuffer.buffer); / / truesubarray

Subarray (start, end) can almost be regarded as equivalent to the slice method. The semantics of the two methods are different, but the behavior is indeed consistent. The semantic representation of subarray returns a range of subarrays of the original array, while the semantic representation of slice is trimmed. Similarly, subarray returns a new Buffer object, and the buffer of the returned Buffer object is the same as the buffer property of the original Buffer object.

Const buffer = Buffer.from ("hello world!"); const newBuffer = buffer.subarray (6); console.log (newBuffer.toString ()); / / worldworldconsole.log (buffer.buffer = newBuffer.buffer); / / truecopy

The copy (target, [targetStart], [sourceStart], [sourceEnd]) method is to copy the contents of source from sourceStart to sourceEnd to the location of target slave targetStart, as shown in the following image.

Except for target, the other three parameters are optional. The default values for targetStart and sourceStart are 0, and the default values for sourceEnd are buf.length.

Const buf1 = Buffer.from ("HelloWorld"); const buf2 = Buffer.alloc (8); buf1.copy (buf2, 0,1,9); console.log (buf2.toString ()); / / elloWorlincludes

The function of the buf.includes (value, [offset], [encoding]) method is to determine whether the value is in the buf.

Value can be a string, a Buffer object, or an integer; offset is used to specify the scope of search, indicating that the search starts at offset. The default is 0, which indicates coding, and defaults to utf-8.

Const buf = Buffer.from ("HelloWorld"); / / search console.log (buf.includes ("H")) from 0 by default; / / true// starts at 1 and does not include Hconsole.log (buf.includes ("H", 1)); / / falseconsole.log (buf.includes (Buffer.from ("Hello"); / / true// H corresponds to utf-8 code 72console.log (buf.includes (72)); / / trueindexOf

Buf.indexOf (value, [offset], [encoding]) is used to find the subscript of value in buf. The meaning of the parameter is the same as that of the includes method. If value is not found in buf, it returns-1, so the includes (value) method is actually equivalent to indexOf (value)! =-1

Const buf = Buffer.from ("HelloWorld"); console.log (buf.indexOf ("H")); / / 0console.log (buf.indexOf ("H", 1)); / /-1console.log (buf.indexOf (Buffer.from ("World"); / / 5console.log (buf.indexOf (72)); / / 0equals

Buf.equals (otherBuffer) is to compare whether the bytes of two Buffer objects are exactly the same. If so, return true, otherwise return false.

Const buf1 = Buffer.alloc (5); const buf2 = Buffer.alloc (5); const buf3 = Buffer.allocUnsafe (5); console.log (buf1.equals (buf2)); / / trueconsole.log (buf1.equals (buf3)); / / false has finished reading this article, I believe you have some understanding of "how to use Buffer objects in Node.js". If you want to know more about it, welcome to follow the industry information channel. Thank you for reading!

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: 246

*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