Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js
communitycreator

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

Gutha Vamsi Krishna

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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();
}

RELATED TAGS

node.js
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring