JavaScript program to convert array buffer to string

In this tutorial, we will see a JavaScript program to convert an array buffer to a string.

Assume a scenario where we have to export the Private crypto key to string format, for that we will have to convert the private key that provides an array buffer to a string format.

First, we will convert the key buffer to unit8Array and then convert each byte to string using the fromCodePoint method of the string.

const arrayBufferToString = (exportedPrivateKey) => {
   const byteArray = new Uint8Array(exportedPrivateKey);
   let byteString = '';
   for(var i=0; i < byteArray.byteLength; i++) {
      byteString += String.fromCodePoint(byteArray[i]);
   }
   return byteString;
}

Here for testing, we are using the inverse method, string to array buffer. This will give us the array buffer of the given string and our method will turn that array buffer back to string.

console.log(arrayBufferToString(stringToArrayBuffer("abcd")));
// "abcd"

We get the same string in the output.