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
buffromabcdef, using theBuffer.from()method. - In line 3, we use the
forloop to iterate over the object returned from thebuf.entries()method. - In line 4, we print the
indexandBytevalues to the console, which is obtained from theentryobject.
//construcing buffer obectconst buf = Buffer.from('abcdef');//looping through iteratorfor (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
buffromabcdef, using theBuffer.from()method. - In line 2, we assign the
buf.entries()iterator to the variableit. - Since
itis an iterator, we can access thenext()method on the iterator to get the elements. - In line 3, we assign
it.next()toitr. - In lines 5 to 8, we use the
whileloop to get all the elements and print them to the console.
//construcing buffer obectconst buf = Buffer.from('abcdef');//buffer iteratorconst it = buf.entries();//pointer that pointing to element in iterator using nex()let itr = it.next();//using while loop to access all elementswhile(!itr.done){//printing value to consoleconsole.log(itr.value);//pointing pointer to next elementitr = it.next();}