How to convert a binary NodeJS Buffer to JavaScript ArrayBuffer?

JavascriptObject Oriented ProgrammingFront End Technology

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;
}
raja
Updated on 24-Jun-2020 06:28:30

Advertisements