How to convert a binary NodeJS Buffer to JavaScript ArrayBuffer?


Access the buf.buffer property directly to convert a binary NodeJS Buffer to JavaScript ArrayBuffer. The write through the original Buffer instance writes the ArrayBufferView.

Keep in mind that the instances of Buffer are also instances of Uint8Array in node.js 4.x and higher versions.

Example

You can try the following code snippet to convert a NodeJS buffer to JavaScript ArrayBuffer −

function toArrayBuffer(myBuf) {
   var myBuffer = new ArrayBuffer(myBuf.length);
   var res = new Uint8Array(myBuffer);
   for (var i = 0; i < myBuf.length; ++i) {
      res[i] = myBuf[i];
   }
   return myBuffer;
}

Updated on: 24-Jun-2020

586 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements