• Stars
    star
    4,148
  • Rank 10,001 (Top 0.3 %)
  • Language
    JavaScript
  • License
    BSD 3-Clause "New...
  • Created about 15 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Base64 implementation for JavaScript

CI via GitHub Actions

base64.js

Yet another Base64 transcoder.

Install

$ npm install --save js-base64

Usage

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/[email protected]/base64.min.js"></script>

This good old way loads Base64 in the global context (window). Though Base64.noConflict() is made available, you should consider using ES6 Module to avoid tainting window.

As an ES6 Module

locally…

import { Base64 } from 'js-base64';
// or if you prefer no Base64 namespace
import { encode, decode } from 'js-base64';

or even remotely.

<script type="module">
// note jsdelivr.net does not automatically minify .mjs
import { Base64 } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs';
</script>
<script type="module">
// or if you prefer no Base64 namespace
import { encode, decode } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs';
</script>

node.js (commonjs)

const {Base64} = require('js-base64');

Unlike the case above, the global context is no longer modified.

You can also use esm to import instead of require.

require=require('esm')(module);
import {Base64} from 'js-base64';

SYNOPSIS

let latin = 'dankogai';
let utf8  = '小飼弾'
let u8s   =  new Uint8Array([100,97,110,107,111,103,97,105]);
Base64.encode(latin);             // ZGFua29nYWk=
Base64.encode(latin, true);       // ZGFua29nYWk skips padding
Base64.encodeURI(latin);          // ZGFua29nYWk
Base64.btoa(latin);               // ZGFua29nYWk=
Base64.btoa(utf8);                // raises exception
Base64.fromUint8Array(u8s);       // ZGFua29nYWk=
Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe
Base64.encode(utf8);              // 5bCP6aO85by+
Base64.encode(utf8, true)         // 5bCP6aO85by-
Base64.encodeURI(utf8);           // 5bCP6aO85by-
Base64.decode(      'ZGFua29nYWk=');// dankogai
Base64.decode(      'ZGFua29nYWk'); // dankogai
Base64.atob(        'ZGFua29nYWk=');// dankogai
Base64.atob(        '5bCP6aO85by+');// '�飼弾' which is nonsense
Base64.toUint8Array('ZGFua29nYWk=');// u8s above
Base64.decode(      '5bCP6aO85by+');// 小飼弾
// note .decodeURI() is unnecessary since it accepts both flavors
Base64.decode(      '5bCP6aO85by-');// 小飼弾
Base64.isValid(0);      // false: 0 is not string
Base64.isValid('');     // true: a valid Base64-encoded empty byte
Base64.isValid('ZA=='); // true: a valid Base64-encoded 'd'
Base64.isValid('Z A='); // true: whitespaces are okay
Base64.isValid('ZA');   // true: padding ='s can be omitted
Base64.isValid('++');   // true: can be non URL-safe
Base64.isValid('--');   // true: or URL-safe
Base64.isValid('+-');   // false: can't mix both

Built-in Extensions

By default Base64 leaves built-in prototypes untouched. But you can extend them as below.

// you have to explicitly extend String.prototype
Base64.extendString();
// once extended, you can do the following
'dankogai'.toBase64();        // ZGFua29nYWk=
'小飼弾'.toBase64();           // 5bCP6aO85by+
'小飼弾'.toBase64(true);       // 5bCP6aO85by-
'小飼弾'.toBase64URI();        // 5bCP6aO85by- ab alias of .toBase64(true)
'小飼弾'.toBase64URL();        // 5bCP6aO85by- an alias of .toBase64URI()
'ZGFua29nYWk='.fromBase64();  // dankogai
'5bCP6aO85by+'.fromBase64();  // 小飼弾
'5bCP6aO85by-'.fromBase64();  // 小飼弾
'5bCP6aO85by-'.toUint8Array();// u8s above
// you have to explicitly extend Uint8Array.prototype
Base64.extendUint8Array();
// once extended, you can do the following
u8s.toBase64();     // 'ZGFua29nYWk='
u8s.toBase64URI();  // 'ZGFua29nYWk'
u8s.toBase64URL();  // 'ZGFua29nYWk' an alias of .toBase64URI()
// extend all at once
Base64.extendBuiltins()

.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).

Brief History

  • Since version 3.3 it is written in TypeScript. Now base64.mjs is compiled from base64.ts then base64.js is generated from base64.mjs.
  • Since version 3.7 base64.js is ES5-compatible again (hence IE11-compatible).
  • Since 3.0 js-base64 switch to ES2015 module so it is no longer compatible with legacy browsers like IE (see above)

More Repositories

1

js-combinatorics

power set, combination, permutation and more in JavaScript
JavaScript
736
star
2

swift-json

Even Swiftier JSON Handler
Swift
575
star
3

js-deflate

RFC 1951 raw deflate/inflate for JavaScript
JavaScript
401
star
4

swift2-pons

Protocol-Oriented Number System in Pure Swift
Swift
202
star
5

swift-sion

SION handler in Swift. also handles / JSON / Property List / msgpack.org[SION,Swift]
Swift
90
star
6

swift-complex

Complex numbers in Swift
Swift
69
star
7

p5-encode

Encode - character encodings (for Perl 5.8 or better)
Perl
36
star
8

js-object-clone

Deep clone and comparison with ES5 property descriptor and object extensibility support
JavaScript
32
star
9

js-hanzenkaku

Hankaku-Zenkaku Translator in JS
JavaScript
32
star
10

swift-lazylist

A Haskell-Like Lazy List in Swift
Swift
26
star
11

swift-bignum

Arbitrary-precision arithmetic for Swift, in Swift
Swift
26
star
12

swift-jsdemo

Use JavaScriptCore from Swift
Swift
25
star
13

js-math-complex

Complex Number in JavaScript
JavaScript
22
star
14

js-xiterable

Make ES6 Iterators Functional Again
TypeScript
21
star
15

swift-pons

Protocol-Oriented Number System in Pure Swift
Swift
19
star
16

js-lambda

DSL for lambda calculus
JavaScript
16
star
17

SION

Swift Interchangeable Object Notation
15
star
18

swift-prime

Prime number in Swift
Swift
15
star
19

p5-uri-escape-xs

URI::Escape::XS - Drop-In replacement for URI::Escape
Perl
15
star
20

js-codepoints

make your javascript handle unicode codepoints more correctly
JavaScript
15
star
21

js-math-bigint

BigInt in JavaScript
JavaScript
14
star
22

osx-mv2trash

mv2trash - move (file|folder)s? to trash on OS X
Perl
14
star
23

swift-perl

Run Perl from Swift
Swift
11
star
24

js-es2pi

ES6 + a little more on top of ES5
JavaScript
11
star
25

swift-combinatorics

Combinatorics in Swift
Swift
11
star
26

swift-operators

Convenient operators for Swift
8
star
27

c-bucketsort

bucketsort - bucket sort that can be used for general purpose
Perl
8
star
28

js-cocytus

A sandboxed web worker without eval() and assignments to global variables
JavaScript
8
star
29

p5-uri-amazon-apa

URI::Amazon::APA - URI to access Amazon Product Advertising API
Perl
7
star
30

js-wrap

Universal Wrapper Object System for ECMAScript 5 and beyond
JavaScript
7
star
31

p5-lingua-ja-numbers

Lingua::JA::Numbers - Converts numeric values into their Japanese string equivalents and vice versa
Perl
6
star
32

js-trie-patricia

Patricia Trie in JavaScript
JavaScript
6
star
33

js-list-lazy

Lazy List in JavaScript
JavaScript
6
star
34

p5-regexp-optimizer

Regexp::Optimizer - optimizes regular expressions
Perl
6
star
35

js-hexfloat

Rudimentary C99 Hexadecimal Floating Point Support in JS
JavaScript
5
star
36

swift-tap

Test Anything Protocol for Swift
Swift
5
star
37

p5-jcode

Jcode - Japanese Charset Handler
C
5
star
38

p5-lingua-ja-kana

Lingua::JA::Kana - Kata-Romaji related utilities
Perl
5
star
39

p5-http-response-encoding

HTTP::Response::Encoding - Adds encoding() to HTTP::Response
Perl
4
star
40

node-voorhees

JavaScript
3
star
41

p5-attribute-util

Attribute::Util - Assorted general utility attributes
Perl
3
star
42

p5-class-builtin

Class::Builtin - Scalar/Array/Hash as objects
Perl
3
star
43

swift-bf

Brainfuck Interpreter/Compiler in Swift
Swift
3
star
44

p5-attribute-tie

Attribute::Tie - Tie via Attribute
Perl
3
star
45

js-charnames

Unicode Character Names
3
star
46

p5-text-darts

Text::Darts - Perl interface to DARTS by Taku Kudoh
C++
3
star
47

swift-gmpint

Swift binding to GMP Integer
Swift
3
star
48

p5-tie-array-lazy

Tie::Array::Lazy - Lazy -- but mutable -- arrays.
Perl
2
star
49

p5-perl6-perl

Perl6::Perl - $obj->perl just like $obj.perl in Perl 6
Perl
2
star
50

p5-bsd-stat

BSD::stat - stat() with BSD 4.4 extentions
Perl
2
star
51

scripts

script files anything and everything
JavaScript
2
star
52

js-sion

SION deserializer/serializer for ECMAScript
JavaScript
2
star
53

p5-bsd-getloadavg

BSD::getloadavg - Perl Interface to getloadavg (3)
Perl
2
star
54

js-es6-map

Yet another ES6 Map/Set implementation which avoids linear search when possible
JavaScript
2
star
55

p5-data-lock

Data::Lock - makes variables (im)?mutable
Perl
2
star
56

swift-interval

Interval Arithmetic in Swift with Interval Type
Swift
2
star
57

p5-tie-array-pack

Tie::Array::Pack − An array implemented as a packed string
Perl
2
star
58

p5-text-tx

Text::Tx - Perl interface to Tx by OKANOHARA Daisuke
Perl
2
star
59

js-installproperty

defineProperty, undoably.
JavaScript
2
star
60

p5-file-glob-slurp

File::Glob::Slurp - Turns <> into a slurp operator
Perl
1
star
61

p5-encode-jis2k

Encode::JIS2K - JIS X 0212 (aka JIS 2000) Encodings
Perl
1
star
62

morscript

JavaScript
1
star
63

swift-toliteral

convert values to swift literals
Swift
1
star
64

p5-digest-siphash

Digest::SipHash - Perl XS interface to the SipHash algorithm
Perl
1
star
65

swift-int2x

Int2X made of IntX
Swift
1
star
66

p5-psgi-or-cgi

PSGI::OR::CGI - Write a PSGI app that also runs as CGI
Perl
1
star
67

p5-acme-akashic-records

Acme::Akashic::Records - Access The Akashic Records
Perl
1
star
68

p5-app-solo

run only one process up to given timeout
Perl
1
star
69

p5-data-decycle

Data::Decycle - (Cyclic|Circular) reference decycler
Perl
1
star