Nodejs, How to Convert Buffer to ArrayBuffer


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

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

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

Buffer object can be created using 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?

As ArrayBuffer can not be read or write, Instead create a typed array or view and copy the data to it. In the example, Buffer object is created, which is going to convert to ArrayBuffer. As we have a limitation with not modified in ArrayBuffer, Created ArrayBuffer object with length of 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 typed array. Finally, 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

You learned copy data from arraybuffer to/from to buffer in Nodejs

I hope you liked it.

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

Similar Posts