• Node.js Video Tutorials

Node.js - Buffer.keys() Method



The NodeJS buffer.keys() method will return an iterator object. When looped through that object , it will give the key for each byte in the buffer object.

Syntax

Following is the syntax of the NodeJS keys() method −

buffer.keys()

Parameters

The method buffer.keys() does not have any parameters.

Return value

The method buffer.keys() returns an iterator object that has the keys (index value) for each byte in the buffer object.

Example

The buffer is created using NodeJS Buffer.from(), the string used is Hello. The length of the string is 5 and so 5 bytes will be reserved when the buffer is created.

Now to get the keys i.e the index value for each of the characters you can make use of NodeJS Buffer.keys() method. Since the method returns an iterator we can loop it using for-of loop as shown in the example.

const buffer = Buffer.from('Hello');
for (let i of buffer.keys()) {
   console.log(i);
}

Output

The output when executed is as follows −

0
1
2
3
4

Example

In this example will access the iterator from buffer.keys using next() method.

const buffer1 = Buffer.from('HELLO');
const bufferiterator = buffer1.keys();
let myitr = bufferiterator.next();
while(!myitr.done){
   console.log(myitr.value);
   myitr = bufferiterator.next();
}

Output

An iterator is looped by continuously calling the next() method until the value of the done key in the iterator comes to true. Having the done: true indicates that we have reached the end of the iterator.

0
1
2
3
4

Example

We can also copy the contents of buffer1 to another buffer using Buffer.keys() method.

const buffer1 = Buffer.from("HELLO");
const buffer2 = Buffer.alloc(buffer1.length);

for (const a of buffer1.keys()) {
   buffer2[a] = buffer1[a];
}
console.log("The string in buffer2 is "+buffer2.toString());

Output

In the example above we have created a buffer using string: HELLO, the same length of bytes is allocated for buffer2. Later we have looped the iterator for buffer1 and updated the buffer2 by using the index as shown in the example.

The string in buffer2 is HELLO

Example

In the example we are using the hex key code for string: Hello.

const buffer1 = Buffer.from('48656c6c6f', 'hex');
for (let i of buffer1.keys()) {
   console.log(i);
}   
console.log("the string is "+buffer1.toString());

Output

If you see the keys printed they are the same as the number of characters in string Hello.

0
1
2
3
4
the string is Hello
nodejs_buffer_module.htm
Advertisements