• A Complete Guide of Node.js Buffer
  • Harsh Patel
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Hoarfroster
  • Proofreader: Flashhu, Regon-Cao

This article has been reprinted and modified with permission from the original author

A binary stream is a large collection of binary data. Because binary streams are usually quite large, they are not shipped together, but are cut into small pieces and sent one by one before shipping.

When the data processing unit temporarily stops receiving other data streams, the remaining data is held in the cache until the data processing unit is ready to receive more data.

Node.js servers typically need to read and write from the file system, and files are binary streams at the storage level. In addition, Node.js can be used in conjunction with TCP streams to provide reliable end-to-end byte streams for guaranteed communication over unreliable Internet networks.

The flow of data sent to the receiver is buffered until the receiver is ready to receive more data to process. That’s what the temporary data part of Node.js is all about — managing and storing binary data outside of the V8 engine.

Let’s dive into the various ways buffers are used, learn more about them, and learn how to use them in Node.js programs.

Node.js Buffer method

The biggest advantage of the Node.js buffer module is that it is built into Node.js, so we can use it wherever we want.

Let’s take a look at some important node.js buffering methods.

Buffer.alloc()

This method creates a new buffer, but the allocated size is not fixed. When we call this method, we allocate the size (in bytes) ourselves.

const buf = Buffer.alloc(6)  // This creates a 6-byte buffer

console.log(buf) // <Buffer 00 00 00 00 00 00>
Copy the code

Buffer.byteLength()

If we want to get the length of the Buffer, we simply call buffer.bytelength ().

var buf = Buffer.alloc(10)
var buffLen = Buffer.byteLength(buf) // Check the buffer length

console.log(buffLen) / / 10
Copy the code

Buffer.compare()

We can compare two buffers by using Buffer.compare(), which returns one of -1, 0, 1.

Buf.com pare(otherBuffer); This call returns a number – 1,0,1, which corresponds to buf before, after, or the same as otherBuffer.

var buf1 = Buffer.from('Harsh')
var buf2 = Buffer.from('Harsg')
var a = Buffer.compare(buf1, buf2)
console.log(a) // This prints 0

var buf1 = Buffer.from('a')
var buf2 = Buffer.from('b')
var a = Buffer.compare(buf1, buf2)
console.log(a) // This will print -1


var buf1 = Buffer.from('b')
var buf2 = Buffer.from('a')
var a = Buffer.compare(buf1, buf2)
console.log(a) // This will print 1
Copy the code

Buffer.concat()

As the name implies, we can use this function to join two buffers. Of course, just like strings, we can concatenate more than two buffers.

var buffer1 = Buffer.from('x')
var buffer2 = Buffer.from('y')
var buffer3 = Buffer.from('z')
var arr = [buffer1, buffer2, buffer3]

console.log(arr)
/* buffer, ! concat [ 
      
       , 
       
        , 
        
          ] */
        
       
      

// Connect two buffers using the buffer. concat method
var buf = Buffer.concat(arr)

console.log(buf)
// <Buffer 78 79 7a> concat successful
Copy the code

Buffer.entries()

Buffer.entries() creates and returns an iterator of the form [index, byte] from the contents of this Buffer.

var buf = Buffer.from('xyz')

for (a of buf.entries()) {
    console.log(a)
    /* This outputs on the console an array of bytes with buffer positions and contents [0, 120][1, 121][2, 122] */
}
Copy the code

Buffer.fill()

We can use the buffer.fill () function to insert or fill data into the Buffer. See below for more information.

const b = Buffer.alloc(10).fill('a')

console.log(b.toString())
// aaaaaaaaaa
Copy the code

Buffer.includes()

Like a string, it will confirm that the buffer has the value. We can do this using the buffer.includes () method, given that the method returns a Boolean value, true or false, based on the search.

const buf = Buffer.from('this is a buffer')
console.log(buf.includes('this'))
// true

console.log(buf.includes(Buffer.from('a buffer example')))
// false
Copy the code

Buffer.isEncoding()

We probably know that binaries must be encoded, so what if we want to check if the data type supports character encoding? We can verify this using the buffer.isencoding () method. If supported, it will return true.

console.log(Buffer.isEncoding('hex'))
// true

console.log(Buffer.isEncoding('utf-8'))
// true

console.log(Buffer.isEncoding('utf/8'))
// false

console.log(Buffer.isEncoding('hey'))
// false
Copy the code

Buffer.slice()

Buf.slice () will be used to create a new buffer with the selected elements of the buffer — when the buffer is sliced, a new buffer is created that contains a list of items to be found in the new buffer slice.

var a = Buffer.from('uvwxyz');
var b = a.slice(2.5);

console.log(b.toString());
// wxy
Copy the code

Buffer.swapX()

Buffer.swapx () is used to swap the byte order of buffers. Use buffer.swapx () (where X can be 16, 32, 64) to swap the byte order of 16-bit, 32-bit, and 64-bit Buffer objects.

const buf1 = Buffer.from([0x1.0x2.0x3.0x4.0x5.0x6.0x7.0x8])
console.log(buf1)
// <Buffer 01 02 03 04 05 06 07 08>

// Swap 16-bit byte order
buf1.swap16()
console.log(buf1)
// <Buffer 02 01 04 03 06 05 08 07>

// Swap 32-bit byte order
buf1.swap32()
console.log(buf1)
// <Buffer 03 04 01 02 07 08 05 06>

// Swap 64-bit byte order
buf1.swap64()
console.log(buf1)
// <Buffer 06 05 08 07 02 01 04 03>
Copy the code

Buffer.json()

It helps us create a JSON object from a buffer, and this method will return a JSON buffer object,

const buf = Buffer.from([0x1.0x2.0x3.0x4.0x5.0x6.0x7.0x8]);

console.log(buf.toJSON());
// {"type":"Buffer", data:[1, 2, 3, 4, 5, 6, 7, 8]}
Copy the code

conclusion

If we need to learn more about and use Node.js buffers, we need to have a more solid basic knowledge of buffers and how Node.js buffers work. We should also understand why we need to use node.js buffers and the use of various Node.js buffer methods.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.