How to Create a Buffer from an Array in JavaScript?

Estimated read time 1 min read

You can create a Buffer from an array in JavaScript using the Buffer.from() method. The Buffer.from() method creates a new buffer object from an array of octets (integers in the range 0-255).

Here’s an example of how to create a Buffer from an array in JavaScript:

const myArray = [0x48, 0x65, 0x6c, 0x6c, 0x6f];
const myBuffer = Buffer.from(myArray);

console.log(myBuffer.toString()); // outputs "Hello"

In this example, an array myArray is created with the values representing the ASCII codes for the letters in the word “Hello”. The Buffer.from() method is then used to create a new Buffer object from the array. The toString() method is used to convert the buffer to a string, which is then logged to the console.

This will create a Buffer object from an array and convert it to a string, allowing you to manipulate binary data in JavaScript.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply