Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active April 29, 2017 02:44
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/ed05681fe73ece4917de850c2c3bd7a1 to your computer and use it in GitHub Desktop.
Save WebReflection/ed05681fe73ece4917de850c2c3bd7a1 to your computer and use it in GitHub Desktop.
Quite possibly the smallest base 64 utility out there.
// base64.decode(base64.encode('💩'));
// Browsers
const base64 = {
encode: str => btoa(unescape(encodeURIComponent(str))),
decode: str => decodeURIComponent(escape(atob(str)))
};
/* ES3 compat version
var base64 = {
encode: function (str) {
return btoa(unescape(encodeURIComponent(str)));
},
decode: function (str) {
return decodeURIComponent(escape(atob(str)));
}
};
*/
// NodeJS
const base64 = {
encode: str => Buffer.from(str).toString('base64'),
decode: str => Buffer.from(str, 'base64').toString()
};
@WebReflection
Copy link
Author

As single module for both browsers and node

var base64 = {
  encode: typeof btoa === 'function' ?
    function (str) {
      return btoa(unescape(encodeURIComponent(str)));
    } :
    function (str) {
      return Buffer.from(str).toString('base64');
    },
  decode: typeof atob === 'function' ?
    function (str) {
      return decodeURIComponent(escape(atob(str)));
    } :
    function (str) {
      return Buffer.from(str, 'base64').toString();
    } 
};

try { module.exports = base64; } catch(o_O) {}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment