English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
Buffer. |
The Buffer.from method reads an 8-byte array from the array and returns a buffer initialized with these read bytes.
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
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.
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.
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.