Skip to content

Instantly share code, notes, and snippets.

@nsrau
Created November 10, 2020 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsrau/cfa705d55917dc1531107c10c5cd2616 to your computer and use it in GitHub Desktop.
Save nsrau/cfa705d55917dc1531107c10c5cd2616 to your computer and use it in GitHub Desktop.
btoa, atob - NODE JS - ES6
class Base64 {
constructor() {
}
// A helper that returns Base64 characters and their indices.
static chars = {
ascii: function () {
return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
},
indices: function () {
if (!this.cache) {
this.cache = {};
let ascii = Base64.chars.ascii();
for (let c = 0; c < ascii.length; c++) {
let chr = ascii[c];
this.cache[chr] = c;
}
}
return this.cache;
}
};
/**
* Binary to ASCII (encode data to Base64)
* @param {String} data
* @returns {String}
*/
static btoa(data) {
let ascii = Base64.chars.ascii(),
len = data.length - 1,
i = -1,
b64 = '';
while (i < len) {
let code = data.charCodeAt(++i) << 16 | data.charCodeAt(++i) << 8 | data.charCodeAt(++i);
b64 += ascii[(code >>> 18) & 63] + ascii[(code >>> 12) & 63] + ascii[(code >>> 6) & 63] + ascii[code & 63];
}
let pads = data.length % 3;
if (pads > 0) {
b64 = b64.slice(0, pads - 3);
while (b64.length % 4 !== 0) {
b64 += '=';
}
}
return b64;
};
/**
* ASCII to binary (decode Base64 to original data)
* @param {String} b64
* @returns {String}
*/
static atob(b64) {
let indices = Base64.chars.indices(),
pos = b64.indexOf('='),
padded = pos > -1,
len = padded ? pos : b64.length,
i = -1,
data = '';
while (i < len) {
let code = indices[b64[++i]] << 18 | indices[b64[++i]] << 12 | indices[b64[++i]] << 6 | indices[b64[++i]];
if (code !== 0) {
data += String.fromCharCode((code >>> 16) & 255, (code >>> 8) & 255, code & 255);
}
}
if (padded) {
data = data.slice(0, pos - b64.length);
}
return data;
};
}
console.log("btoa('QQ==') = " + Base64.atob('QXJndW1lbnQxO0FyZ3VtZW50MjtBcmd1bWVudDMNCnBsdXRvO+g7YXJyYWJiaWF0bw0K'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment