Spaces:
Running
Running
File size: 1,318 Bytes
30c32c8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
const atob = require('atob');
const btoa = require('btoa');
class Base64Util {
/**
* Convert a base64 encoded string to a Uint8Array.
* @param {string} base64 - a base64 encoded string.
* @return {Uint8Array} - a decoded Uint8Array.
*/
static base64ToUint8Array (base64) {
const binaryString = atob(base64);
const len = binaryString.length;
const array = new Uint8Array(len);
for (let i = 0; i < len; i++) {
array[i] = binaryString.charCodeAt(i);
}
return array;
}
/**
* Convert a Uint8Array to a base64 encoded string.
* @param {Uint8Array} array - the array to convert.
* @return {string} - the base64 encoded string.
*/
static uint8ArrayToBase64 (array) {
let binary = '';
const len = array.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(array[i]);
}
return btoa(binary);
}
/**
* Convert an array buffer to a base64 encoded string.
* @param {array} buffer - an array buffer to convert.
* @return {string} - the base64 encoded string.
*/
static arrayBufferToBase64 (buffer) {
return Base64Util.uint8ArrayToBase64(new Uint8Array(buffer));
}
}
module.exports = Base64Util;
|