Node.js – Convert Array to Buffer

Node.js – Convert Array to Buffer : To convert array (octet array/ number array/ binary array) to buffer, use Buffer.from(array) method.

In this tutorial, we will learn how to convert array to buffer using Buffer.from() method, with some examples.

Syntax – Buffer.from()

The syntax of from() method is

</>
Copy
Buffer.from(array)

Buffer.from method reads octets from array and returns a buffer initialized with those read bytes.

Example 1 – Read an octet array to buffer

In the following example, an octet array is read to a buffer.

array-to-buffer.js

</>
Copy
var arr = [0x74, 0x32, 0x91];
const buf = Buffer.from(arr);

for(const byt of buf.values()){
	console.log(byt);
}

Output

$ node array-to-buffer.js 
116
50
145

We have logged data in each byte as a number.

0x74 = 0111 0100 = 116
0x32 = 0011 0010 = 50
0x91 = 1001 0001 = 145

Example 2 – Read a number array to buffer

In the following example, a number array is read to a buffer.

array-to-buffer.js

</>
Copy
var arr = [74, 32, 91];
const buf = Buffer.from(arr);

for(const byt of buf.values()){
	console.log(byt);
}

Output

$ node array-to-buffer.js 
74
32
91

We have logged data in each byte as a number.

Example 3 – Read boolean array to buffer

In the following example, an octet array is read to a buffer.

array-to-buffer.js

</>
Copy
var arr = [true, true, false];
const buf = Buffer.from(arr);

for(const byt of buf.values()){
	console.log(byt);
}

Output

$ node array-to-buffer.js 
1
1
0

true is 1, while false is 0.

Conclusion

In this Node.js TutorialNode.js Convert Array to Buffer, we have learnt how to convert octet array, number array and boolean array to Node.js buffers.