Why am I getting an "Uncaught DOM Exception" in the Deno CLI?

To replicate: 1. deno in the command line to initialize a Deno REPL
// Get an array of random bytes
const arr = new Uint8Array(32)
crypto.getRandomValues(arr)

const decoder = new TextDecoder("utf8")
btoa(decoder.decode(arr));
> Uncaught DOMException
// Get an array of random bytes
const arr = new Uint8Array(32)
crypto.getRandomValues(arr)

const decoder = new TextDecoder("utf8")
btoa(decoder.decode(arr));
> Uncaught DOMException
The goal was to get a base64 encoding of the byte array. What am I doing wrong? atob produces the same result.
1 Reply
ioB
ioB•2y ago
Since arr is not guaranteed to contain valid utf-8, btoa will throw an error when it attempts to encode invalid text. According to stackoverflow, you can just use
btoa(String.fromCharCode(...arr))
btoa(String.fromCharCode(...arr))
instead (https://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string)
Stack Overflow
ArrayBuffer to base64 encoded string
I need an efficient (read native) way to convert an ArrayBuffer to a base64 string which needs to be used on a multipart post.