English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Other

Node.js Convert Array to Buffer

Node.js – Convert Array to BufferTo convert an array (8-byte array) to a buffer, use/Numeric Array/To convert a binary array (8-byte array) to a buffer, use Buffer.from(array)Method.

Syntax

Buffer.from(array)

The Buffer.from method reads an 8-byte array from the array and returns a buffer initialized with these read bytes.

Example – Reading an 8-byte Array into a Buffer

In the following example, an 8-byte array is read into the buffer.

var arr = [0x74, 0x32, 0x91]; 
 
const buf = Buffer.from(arr); 
 
for(const byt of buf.values()){ 
    console.log(byt); 
 }

Output Result

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

We have recorded the data in each byte as a number.

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

Example – Reading a Numeric Array into a Buffer

In the following example, a numeric array is read into the buffer.

var arr = [74, 32, 91]; 
 
const buf = Buffer.from(arr); 
 
for(const byt of buf.values()){ 
    console.log(byt); 
 }

Output Result

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

We have recorded the data in each byte as a number.

Example – Reading a Boolean Array into a Buffer

In the following example, an 8-byte array is read into the buffer.

var arr = [true, true, false]; 
 
const buf = Buffer.from(arr); 
 
for(const byt of buf.values()){ 
    console.log(byt); 
 }

Output Result

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

true is1false is 0.

Conclusion:

In this Node.js tutorial – Node.js Converts Arrays to BuffersWe learned how to convert 8-byte arrays, numeric arrays, and boolean arrays into Node.js buffers.