How to Convert Buffer to ArrayBuffer in NodeJS with example

In this post, Learn how to convert the buffer to/from ArrayBuffer in Nodejs application with example.

You can also check other posts on npm command deprecate option is deprecated and Fix for digital envelope routines::unsupported

Buffer is an object in Nodejs to represents a fixed length of bytes. ArrayBuffer also stores the fixed length of the array of binary bytes data in javascript.

Data inside the array buffer can not be read directly but you can use Data view Object or typed array only. Some of the typed Arrays are Int8Array, UInt8Array, Float32Array, etc..

Buffer objects can be created using the alloc method

const buf1 = Buffer.alloc(10);

ArrayBuffer was created using the new keyword as follows

new ArrayBuffer(fixedlengthbytes);

How to convert Buffer to ArrayBuffer in Nodejs?

Create a typed array or view and copy the data to it instead of using ArrayBuffer, which cannot be read or written.

In the example, a Buffer object is created, to convert to ArrayBuffer. As we have a limitation with not being modified in ArrayBuffer, Created ArrayBuffer object with a length of the buffer object. As we have to create a typed array Uint8Array with ArrayBuffer object as a parameter in a constructor. Iterate the buffer object with for loop and copy the data to the typed array. Finally, a Typed array is returned which is a pointer to Array Buffer

const bufferObject = Buffer.alloc(16);

var arrayBuffer = new ArrayBuffer(bufferObject.length);
var typedArray = new Uint8Array(arrayBuffer);
for (var i = 0; i < bufferObject.length; ++i) {
  typedArray[i] = bufferObject[i];
}

How to convert ArrayBuffer to Buffer in Nodejs

First, create a buffer object using the alloc method with arraybuffer length, It allocates buffer memory. Iterate ArrayBuffer object and copy data of each element to buffer object.

var arrayBuffer = new ArrayBuffer(16);
var bufferObject = new Buffer.alloc(arrayBuffer.byteLength);
for (var i = 0; i < arrayBuffer.length; i++) {
  bufferObject[i] = arrayBuffer[i];
}

Conclusion

To Sum up, You learned to copy data from arraybuffer to/from to buffer in Nodejs