SoFunction
Updated on 2025-03-03

Analysis of Buffer module functions and common methods

This article describes the functions and common methods of the Buffer module. Share it for your reference, as follows:

Buffer module

alloc() method

alloc(size,fill,encoding)You can allocate a newly created Buffer of size bytes, and the default size is 0.

var buf = (10);

The parameter fill is filled data, and it will be called as long as fill is specified.(fill)Initialize this Buffer object

var buf = (10,0xff);// Can be hexadecimal data

allocUnsafe() method

Unsafe(size)As the name suggests, it is an insecure method because the underlying memory of the Buffer instance created in this way is uninitialized. It may even contain sensitive data, sofill()Method helps initialize

buf = (10);
(0);

allocUnsafeSlow() method

allocUnsafeSlow()It means that it is not allocated from the buffer buffer, but is directly allocated from the operating system. Slow means that it is not efficiently allocated from the buffer pool.

buf = (10);

from() method

from()The method can allocate a buffer object to store the binary object of this string, so the content of the buffer can be accessed through []

buf = ("HelloWorld!");//from(array)
(buf);
buf = ([123,22,24,36]);
(buf);
//Rebuild a buffer and copy the original Buffer data to the new bufferbuf2 = (buf);
(buf2);
//buf[index] index value range [0,len-1](buf[0],buf[1]);

Large-tail and small-tail writing to storage

writeInt32BE(value,offset)The first parameter is the written data, and the second parameter starts to be written from where it means it is written in the form of a large tail (big endian).
writeInt32LE(value,offset)Write data in small-tail (little-endian) form

//Storage in large tail form, 4 byte integerbuf.writeInt32BE(65535,0);
(buf);
//Write in small tailbuf.writeInt32LE(65535,0);
(buf);

Read data in large-tail small-tail form

readInt32LE(offset)It means reading data in small-tail integer form
readFloatLE(offset)It means reading data in small-tail floating point form

var value = buf.readInt32LE(0);
(value);
(3.16,0);
((0));

Various ways to read data

//Read lengthvar len = ("HelloWorld");
(len);
buf = (4*4);
buf.writeInt32LE(65535,0);
buf.writeInt32LE(65535,4);
buf.writeInt32LE(65535,8);
buf.writeInt32LE(65535,12);
(buf);
buf.swap32();
(buf);
//Read in high-level mode(buf.readInt32BE(0));
(buf.readInt32BE(4));
(buf.readInt32BE(8));
(buf.readInt32BE(12));
for (var i of ()) {
  (i);
}

Convert

//Convert to string in binary(('hex'));
(());
('A');
(buf);
(('utf8'));

I hope this article will be helpful to everyone's nodejs programming.