{

How to Convert Buffer to ArrayBuffer in NodeJS with example


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

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

Data inside 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 object can be created using the alloc method

const buf1 = Buffer.alloc(10);

ArrayBuffer created using 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 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 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 copy data from arraybuffer to/from to buffer in Nodejs

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.