What is the Node.js Buffer.entries() method?

The Buffer.entries() method is included in the Buffer class of Node.js. It creates and provides an iterator of [index, byte] pairs from the buffer object.

We can use the returned iterator to loop through the buffer object.

Syntax

Buffer.entries()

Parameter

This method does not accept any parameters.

Return value

This method returns an iterator object that contains [index, byte] pairs that are created from the contents of the buffer to iterate over the buffer object.

Code

Example 1

In the example below we have:

  • Constructed a buffer object buf from abcdef, using the Buffer.from() method.
  • In line 3, we use the for loop to iterate over the object returned from the buf.entries() method.
  • In line 4, we print the index and Byte values to the console, which is obtained from the entry object.
//construcing buffer obect
const buf = Buffer.from('abcdef');
//looping through iterator
for (entry of buf.entries()) {
//printing the pairs to console.
console.log(`Index: ${entry[0]}, Byte: ${entry[1]}`);
}

Example 2

In the following example, we have:

  • Constructed a buffer object buf from abcdef, using the Buffer.from() method.
  • In line 2, we assign the buf.entries() iterator to the variable it.
  • Since it is an iterator, we can access the next() method on the iterator to get the elements.
  • In line 3, we assign it.next() to itr.
  • In lines 5 to 8, we use the while loop to get all the elements and print them to the console.
//construcing buffer obect
const buf = Buffer.from('abcdef');
//buffer iterator
const it = buf.entries();
//pointer that pointing to element in iterator using nex()
let itr = it.next();
//using while loop to access all elements
while(!itr.done){
//printing value to console
console.log(itr.value);
//pointing pointer to next element
itr = it.next();
}

Free Resources