• Node.js Video Tutorials

Node.js - Buffer.values() Method



The NodeJS Buffer.values() method returns an iterator object that has details of all the bytes present in the buffer. You can make use of for…of loop to iterate over iterator objects.

Syntax

Following is the syntax of the Node.JS Buffer.values() Method

buf.values()

Parameters

There are no parameters for this method.

Return value

The method buffer.values() returns an iterator object.

Example

To create a buffer, we are going to make use of NodeJS Buffer.from() method −

const buffer = Buffer.from("Hello");
console.log(buffer);
for (const val of buffer.values()) {
   console.log(val);
}

Output

We have used the string "hello" to create a buffer. Using Buffer.values() will get the bytes from the buffer created. On executing the above program, it will generate the following output −

<Buffer 48 65 6c 6c 6f>
72
101
108
108
111

Example

In the below example we have used the buffer.values() method to get the bytes from the buffer created. We can also iterate directly over the buffer to get the same result.

const buffer = Buffer.from("Hello");
console.log(buffer);
for (const val of buffer.values()) {
   console.log(val);
}
console.log("\n");
for (const val of buffer) {
   console.log(val);
}

Output

We have used the string "hello" to create a buffer. To get the bytes we have iterated over Buffer.values() and later directly on Buffer.from() output. On executing the above program, it will generate the following output −

<Buffer 48 65 6c 6c 6f>
72 
101
108
108
111
   
   
72 
101
108
108
111

Example

In the example we have used Buffer.alloc() to allocate memory for the buffer. Later buffer.fill() method is used to fill the buffer with a value. Buffer.values() is used to see the bytes in the buffer created.

const buffer = Buffer.alloc(5);
buffer.fill("h");
console.log(buffer);
for (const val of buffer.values()) {
   console.log(val);
}

Output

<Buffer 68 68 68 68 68>
104
104
104
104
104
nodejs_buffer_module.htm
Advertisements