This article will take you through the usage of the Buffer module in Nodejs, and introduce the method of Buffer encoding and decoding binary data packets. I hope it will be helpful to everyone!
Today, we will learn about the use of Nodejs's Buffer module, as well as the currently commonly used buffer npm package. [Recommended study: "nodejs Tutorial"]
First, attach the document address of nodejs buffer: https://nodejs.org/dist/latest-v16.x/docs/api/ buffer.html
There are two commonly used methods to create a buffer:
1, Buffer.alloc(size): Create a buffer of specified length
console.log(Buffer.alloc(20));
Result:
2. Buffer.from(): Create a buffer## from an existing structure #
console.log(Buffer.from("fsfdfafd")); console.log(Buffer.from([1, 2, 3, 4]));
let buffer1 = Buffer.from("fsfdfafd"); console.log(buffer1); buffer1.writeInt8(127, 1); console.log(buffer1);
offset positionis
big endian
let buffer1 = Buffer.from("fsfdfafd"); console.log(buffer1); buffer1.`writeInt16BE`(127, 1); console.log(buffer1);
offset positionis
little endian
let buffer1 = Buffer.from("fsfdfafd"); console.log(buffer1); buffer1.`writeInt16LE`(127, 1); console.log(buffer1);
The npm package we want to introduce here about node buffer is
protocol-buffers. This is its npm address: https://www.npmjs.com/package/protocol-buffers
Programming Video! !
The above is the detailed content of A brief discussion on the usage of the Buffer module in Nodejs and see how to encode and decode binary data packets. For more information, please follow other related articles on the PHP Chinese website!