In this tutorial we will learn how to convert an integer array to a Node.js Buffer.
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.
You should get an output like figure 1. As can be seen, we have correctly obtained our Buffer from the array, as expected.
Note that instances of the Buffer class represent binary data and thus can only contain values from 0 to 255 . So, if we pass an array with values outside this range, they are converted to it with the & 255 operation .
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.