Open In App

Node.js Buffer.keys() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The Buffer.keys() method is used to return an iterator object, containing the key of every byte in a buffer object. 

Syntax:

Buffer.keys()

Parameters: This method does not accept any parameters. 

Return Value: It returns an iterator object having the keys of the buffer. 

Example 1: In this example, we will use the Buffer.keys() method

JavaScript




// Node.js program to demonstrate the
// Buffer.keys() method
const buf = Buffer.from('Hello World');
 
// Read in the iterator object
// and return the key number
for (index of buf.keys()) {
    console.log(index);
}


Output:

0
1
2
3
4
5
6
7
8
9 

Example 2: In this example, we will use the Buffer.keys() method

Javascript




// Node.js program to demonstrate the
// Buffer.keys() method
const buf1 = Buffer.from('abc');
const buf2 = Buffer.from('1');
 
// Read in the first iterator object
// and return the key number
for (index of buf1.keys()) {
    console.log(index);
}
 
// Read in the first iterator object
// and return the key number
for (index of buf2.keys()) {
    console.log(index)
}


Output:

0
1
2
0

Note: The above program will compile and run by using the node index.js command. 

Reference: https://nodejs.org/api/buffer.html#buffer_buf_keys


Last Updated : 11 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads