Convert base64 String to ArrayBuffer In JavaScript
A Base64 string represents binary data in an ASCII string format by translating it into a radix-64 representation. Often used to encode binary data in text-based formats like JSON or HTML, it needs to be converted back into its original binary format for further processing.
An ArrayBuffer in JavaScript is a generic, fixed-length binary data buffer, which is useful when working with raw binary data such as images or files. Converting a Base64 string to an ArrayBuffer is a common task in web development, especially when dealing with binary data that has been encoded for transmission over networks.
Below are the approaches to convert base64 string to ArrayBuffer in Javascript:
Table of Content
1. Using atob and Uint8Array
The atob() function decodes a Base64-encoded string into a binary string. The Uint8Array constructor can then be used to convert this binary string into an ArrayBuffer.
Example: This function converts a Base64-encoded string into an ArrayBuffer.
function base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const length = binaryString.length;
const bytes = new Uint8Array(length);
for (let i = 0; i < length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
const base64String = "SGVsbG8gd29ybGQ=";
const arrayBuffer = base64ToArrayBuffer(base64String);
console.log(arrayBuffer);
Output
ArrayBuffer {
[Uint8Contents]: <48 65 6c 6c 6f 20 77 6f 72 6c 64>,
byteLength: 11
}
2. Using TextDecoder and Uint8Array
This approach is similar to the first but uses the TextDecoder interface to convert the binary string to an ArrayBuffer. This method is more modern and offers better performance with the UTF-8 format.
Example: This function converts a Base64-encoded string into an ArrayBuffer using the TextEncoder
to encode the binary string.
function base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const encoder = new TextEncoder();
const binaryArray = encoder.encode(binaryString);
return binaryArray.buffer;
}
const base64String = "SGVsbG8gd29ybGQ=";
const arrayBuffer = base64ToArrayBuffer(base64String);
console.log(arrayBuffer);
Output
ArrayBuffer {
[Uint8Contents]: <48 65 6c 6c 6f 20 77 6f 72 6c 64>,
byteLength: 11
}