Sometimes, we want to convert uint8 array to base64 encoded string with JavaScript.
In this article, we’ll look at how to convert uint8 array to base64 encoded string with JavaScript.
How to convert uint8 array to base64 encoded string with JavaScript?
To convert uint8 array to base64 encoded string with JavaScript, we can use the FileReader
constructor.
For instance, we write
const base64Arraybuffer = async (data) => {
const base64url = await new Promise((r) => {
const reader = new FileReader();
reader.onload = () => r(reader.result);
reader.readAsDataURL(new Blob([data]));
});
return base64url.split(",", 2)[1];
};
//...
await base64Arraybuffer(new Uint8Array([1, 2, 3, 100, 200]));
to define the base64Arraybuffer
function that returns a promise with the blob that we convert from the data
the Uint8Array
into a base64 string.
We create the reader
FileReader
object and then call readAsDataURL
with the blob value to read the blob into a base64 string.
Then we call r
with reader.result
to return the reader.result
base64 string as the resolve value.
Then we call base64Arraybuffer
in an async function with a Unit8Array
as its argument to read it into a base64 string.
Conclusion
To convert uint8 array to base64 encoded string with JavaScript, we can use the FileReader
constructor.