The Uint8Array.fromBase64() method is a modern JavaScript feature that creates a Uint8Array from a base64-encoded string. If you're working in an environment where this method isn't supported, you can achieve similar functionality using the atob() function combined with Uint8Array. Here's how you can implement this:
function base64ToUint8Array(base64) {
// Decode the base64 string to a binary string
const binaryString = atob(base64);
// Create a Uint8Array with the same length as the binary string
const bytes = new Uint8Array(binaryString.length);
// Populate the Uint8Array with the character codes from the binary string
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
// Example usage:
const base64String = "SGVsbG8gd29ybGQ="; // "Hello world" in base64
const uint8Array = base64ToUint8Array(base64String);
console.log(uint8Array);
// Output: Uint8Array(11) [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
Explanation:
-
Decoding the Base64 String: The atob() function decodes a base64-encoded string into a binary string. Each character in this binary string represents a byte.
-
Creating a Uint8Array: A Uint8Array is instantiated with a length equal to the binary string. This array will hold the byte values.
-
Populating the Uint8Array: A loop iterates over the binary string, and for each character, its character code (which corresponds to the byte value) is assigned to the Uint8Array.
Note: The atob() function is widely supported in browsers but may not be available in all JavaScript environments, such as Node.js. In such cases, you might consider using a library like base64-arraybuffer to handle base64 encoding and decoding.
This approach provides a reliable way to convert base64-encoded strings to Uint8Array instances in environments where Uint8Array.fromBase64() is not available.