Node.js: Converting Array to Buffer

In this tutorial we will learn how to convert an integer array to a Node.js Buffer.

Introduction

In this tutorial we will learn how to convert an integer array to a Node.js Buffer. The code shown below was tested using Visual Studio Code with the Code Runner extension.

The code

We will start by defining the array of integers we want to convert to a Buffer.

const testArray = [1, 2, 3, 4, 5];

Then, to convert the array to a Buffer, we simply need to call the from class method, passing as input our array.

const buffer = Buffer.from(testArray);

After this we will print our buffer with a simple console log.

console.log(buffer);

You should get an output like figure 1. As can be seen, we have correctly obtained our Buffer from the array, as expected.

Printing the buffer to the console.
Figure 1 – Printing the buffer to the console.

Note that instances of the Buffer class represent binary data and thus can only contain values from 0 to 255 [1]. So, if we pass an array with values outside this range, they are converted to it with the & 255 operation [1].

You can check this with the following code:

const testArray = [254, 255, 256, 257, 258];
  
const buffer = Buffer.from(testArray);
 
console.log(buffer);

The output is shown in figure 2. As can be seen, the values 256, 257 and 258 are converted to 0, 1 and 2, respectively.

Converting an integer array with values outside the byte range.
Figure 2 – Converting an integer array with values outside the byte range.

References

[1] https://nodejs.org/api/buffer.html

Leave a Reply