base64.js
Yet another Base64 transcoder
HEADS UP: ES2015 support required since version 3
Version 3 is completely rewritten with ES2015 features like arrow functions. All modern browsers and node.js are directly supported. Your codes should run unchanged. IE is no longer supported directly but you can transpile the script to use it (see below).
The hardest part of maintaining this module was not Base64 features, but cross-platform support (eg. nodejs vs web browsers). By making ES2015 mandatory virtually all codes are common (except atob()
and btoa()
).
If you need to support legacy browsers like IE, use version 2 or transpile.
Usage
Install
$ npm install --save js-base64
In Browser
Locally…
<script src="base64.js"></script>
… or Directly from CDN. In which case you don't even need to install.
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.min.js">
node.js
const Base64 = require('js-base64').Base64;
As a ES6 Module
locally…
import { Base64 } from 'js-base64';
import { encode, decode } from 'js-base64';
or even remotely.
<script type="module">
import { Base64 } from 'https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.mjs';
import { encode, decode } from 'https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.mjs';
</script>
SYNOPSIS
let latin = 'dankogai';
let utf8 = '小飼弾'
let u8s = new Uint8Array([100,97,110,107,111,103,97,105]);
Base64.encode(latin);
Base64.btoa(latin);
Base64.btoa(utf8);
Base64.fromUint8Array(u8s);
Base64.fromUint8Array(u8s);
Base64.encode(utf8);
Base64.encode(utf8, true)
Base64.encodeURI(utf8);
Base64.decode( 'ZGFua29nYWk=');
Base64.atob( 'ZGFua29nYWk=');
Base64.atob( '5bCP6aO85by+');
Base64.toUint8Array('ZGFua29nYWk=');
Base64.decode( '5bCP6aO85by+');
Base64.decode( '5bCP6aO85by-');
Built-in Extensions
By default Base64
leaves built-in prototypes untouched. But you can extend them as below.
Base64.extendString();
'dankogai'.toBase64();
'小飼弾'.toBase64();
'小飼弾'.toBase64(true);
'小飼弾'.toBase64URI();
'小飼弾'.toBase64URL();
'ZGFua29nYWk='.fromBase64();
'5bCP6aO85by+'.fromBase64();
'5bCP6aO85by-'.fromBase64();
'5bCP6aO85by-'.toUint8Array();
Base64.extendString();
u8s.toBase64();
u8s.toBase64URI();
u8s.toBase64URL();
Base64.extendBuiltins()
TypeScript
TypeScript 2.0 type definition was added to the DefinitelyTyped repository.
$ npm install --save @types/js-base64
.decode()
vs .atob
(and .encode()
vs btoa()
)
Suppose you have:
var pngBase64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
Which is a Base64-encoded 1x1 transparent PNG, DO NOT USE Base64.decode(pngBase64)
. Use Base64.atob(pngBase64)
instead. Base64.decode()
decodes to UTF-8 string while Base64.atob()
decodes to bytes, which is compatible to browser built-in atob()
(Which is absent in node.js). The same rule applies to the opposite direction.
Or even better, Base64.toUint8Array(pngBase64)
.
SEE ALSO