Converting any binary to base64 using FileReader and Blob

To base64-encode a Uint8Array with arbitrary data (not necessarily UTF-8) using native browser functionality:

const base64_arraybuffer = async (data) => {
    // Use a FileReader to generate a base64 data URI
    const base64url = await new Promise((r) => {
        const reader = new FileReader()
        reader.onload = () => r(reader.result)
        reader.readAsDataURL(new Blob([data]))

    The result looks like 
    "data:application/octet-stream;base64,<your base64 data>", 
    so we split off the beginning:
    return base64url.split(",", 2)[1]

// example use:
await base64_arraybuffer(new Uint8Array([1,2,3,100,200]))


This article was updated on 2023-01-25

I'm nabeards. I'm a full stack JavaScript developer. I travel full time, a.k.a., Professional Wanderer, a.k.a., Digital Nomad.