Explain Codes LogoExplain Codes Logo

Convert base64 string to ArrayBuffer

javascript
base64-conversion
arraybuffer
binary-data
Nikita BarsukovbyNikita Barsukov·Feb 2, 2025
TLDR

To turn a base64 string into an ArrayBuffer with fewer hassle:

const b64ToBuffer = (b64) => Uint8Array.from(atob(b64), c => c.charCodeAt(0)).buffer; const arrayBuffer = b64ToBuffer('YourBase64String'); // Replace 'YourBase64String' 😉

Pass your base64 string to the existing b64ToBuffer function to receive your arrayBuffer.

The voyage of base64 to ArrayBuffer

To make the most out of base64 to ArrayBuffer conversion, we need to dive deep into its depths and tackle some of the frequently encountered challenges. Hold my {}, let's venture forth!

Browsers really do matter

Although atob() has been the standard go-to for decoding base64 strings to binary, dealing directly with binary strings is less appealing than watching paint dry. Switching up to Uint8Array gives us access to a much neater, user-friendly interface to the binary data, in the form of ArrayBuffer.

"Look Ma, no binary strings!"

When size does matter: handling large data

For chunkier data sets, the Blob and FileReader APIs come into play with an asynchronous twist:

function b64ToBlobAndBack(b64) { // Who doesn't love chewing blobs of base64 goodness? const blob = base64ToBlob(b64); // FileReader, because blobs don't digest quickly return blobToArrayBuffer(blob); }

This approach prevents the common 'oom' (out of memory) situation, when dealing with potentially massive chunks of data.

Server-side diets with Node.js

To prove that Buffer.from() is not just loafing around in Node.js badge, you can use it to convert your base64 string to a buffer, similar to an ArrayBuffer:

const buffer = Buffer.from('YourBase64String', 'base64'); // Because server-side needs love too!

Remember not to bite off more 'buffer' than you can chew!

Unicorns and Unicode

atob() and btoa() can be occasionally picky about Unicode characters due to their UTF-16 encoding. To prevent upsetting these functions, we use the TextEncoder and TextDecoder APIs for a foolproof conversion:

const b64ToBufferUnicode = (b64) => { const binary_string = window.atob(b64); const bytes = new Uint8Array(binary_string.length); for (let i = 0; i < binary_string.length; i++) { bytes[i] = binary_string.charCodeAt(i); } return new TextDecoder("utf-8").decode(bytes); // UTF-8, not UTF-16. 🦄 safe! };

Let the unicorns (Unicode characters) roam free!

Real-life encounters

When the going gets tough: handling large binary data

For larger datasets, such as files or images, we need a more robust solution. Let's combine Fetch API with some async magic:

async function fetchBase64AsArrayBuffer(base64) { const response = await fetch(`data:;base64,${base64}`); const buffer = await response.arrayBuffer(); return buffer; }

This solution shines when you're fetching a file from a server that throws base64 data at you like there's no tomorrow.

React Native realm considerations

In mobile development, notably when dealing with React Native, global objects like atob and btoa might've taken a vacation. You might need to count on native modules to handle base64 to ArrayBuffer conversion.

Securing your secrets

Base64 encoded data might contain sensitive info, just like your grandma's secret pie recipe. In all cases, remember to only use such data in secure contexts and don't let it end up in the wrong hands (or belly).