Code Monkey home page Code Monkey logo

js-base64's Introduction

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)

js-base64's People

Contributors

baluvyamajala avatar busterc avatar cbovis avatar cdanu avatar ctomacheski-evernote avatar dallonf avatar dankogai avatar davido avatar deniscarriere avatar gauben avatar htaketani avatar itayp-harmonie avatar jimmyhchan avatar jineshshah36 avatar jounqin avatar jstayton avatar kidonng avatar leechael avatar mha-trustpilot avatar michsior14 avatar neojski avatar ohnorobo avatar pubkey avatar robertmassaioli avatar samthor avatar scottweinstein avatar sidharthv96 avatar sylvainpolletvillard avatar winzaa123 avatar yjcxy12 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-base64's Issues

Fails in the browser with Systemjs

The bellow verification fails in the browser when using SystemJS (like with Angular 2 + angular2-jwt). This library tries to load Buffer without success.

if (typeof module !== 'undefined' && module.exports) {
try {
buffer = require('buffer').Buffer;
} catch (err) {}
}

Not sure how to fix it though.

Don't pass global object as argument

Please, don't pass global object as argument here https://github.com/dankogai/js-base64/blob/master/base64.js#L11
Build with Babel fails here with error

Requiring external module babel-core/register
/Users/meu/web/node_modules/js-base64/base64.js:16
    var _Base64 = global.Base64;
                        ^

TypeError: Cannot read property 'Base64' of undefined
    at /Users/meu/web/node_modules/js-base64/base64.js:14:25
    at Object.<anonymous> (/Users/meu/web/node_modules/js-base64/base64.js:194:2)
    at Module._compile (module.js:425:26)
    at normalLoader (/Users/meu/web/node_modules/babel-core/lib/api/register/node.js:199:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/meu/web/node_modules/babel-core/lib/api/register/node.js:216:7)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/Users/meu/web/node_modules/postcss/lib/map-generator.js:5:15)

Version 2.2.0 introduced breaking changes (angular-oauth2-oidc)

This is bogus commit dd715ce

Part of source code of [email protected]

import {Base64} from 'js-base64';
var claimsJson = Base64.decode(claimsBase64);
var js_base64_1 = require('js-base64');
var claimsJson = js_base64_1.Base64.decode(claimsBase64); // js_base64_1.Base64 is undefined

Webpack converts to:

    // that's it!
    if (global['Meteor']) {
        Base64 = global.Base64; // for normal export in Meteor.js
    }
    if (typeof module !== 'undefined' && module.exports) {
        module.exports.Base64 = global.Base64;
    }
    if (true) {
        // AMD. Register as an anonymous module.
        !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function(){ return global.Base64 }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    }

Invalid output for some png files

I found that this library ([email protected]) will produce invalid base64 output from some images. The output is valid base64, but the resulting decoded image is invalid. I had trouble with this image in particular (it's 1px tall, so it may be difficult to see):
test.png

The following is a reproduction of this bug:

var fs = require("fs")
var path = require("path")
var base64 = require("js-base64").Base64
var file = fs.readFileSync("test.png")
console.log(base64.encode(file))
// logs incorrect, invalid image: 77+9UE5HDQoaCgAAAA1JSERSAAADDAAAAAEIAwAAAETvv73v...
console.log(file.toString("base64"))
// logs correct, valid image: iVBORw0KGgoAAAANSUhEUgAAAwwAAAABCAMAAABE19kKAA...

My reproduction code above uses the native Node file.toString('base64'). The output of this library should be consistent with the Node native implementation, correct? I have not investigated why this bug occurs, but I hope the reproduction steps above help to resolve it.

Tag 2.1.3 and 2.1.4

Hey Dan,

Do you mind tagging versions 2.1.3 and 2.1.4? That'll make the library easier to consume with Bower. Thanks!

encodeURI() is not adding correct padding

Base64.encodeURI() is not adding correct padding to some input, such as "賦-卷十四".

Baseline Python 3 encoding:

base64.urlsafe_b64encode(bytes("賦-卷十四",encoding="utf-8")).decode('utf-8')
   '6LOmLeWNt-WNgeWbmw=='

While the Base64.encodeURI() output is: 6LOmLeWNt-WNgeWbmw.

Worth noting that the output of Base64.encode() is padded correctly but of course includes non-URLsafe characters: 6LOmLeWNt+WNgeWbmw==.

EDIT: This is probably happening because you are deleting "=" from uri_escaped values:

  var encode = function(u, urisafe) {
       return !urisafe ? _encode(String(u))  : _encode(String(u)).replace(/[+\/]/g, function(m0)
 {return m0 == '+' ? '-' : '_';}).replace(/=/g, ''); };

Why are you doing this??

Conflict with Moment.js

I import Moment.js use script tag , then import js-base64 in the same way after Moment.js. js-base64 may cover the window.moment object.

window 10
chrome 62.0.3202.94

Base64.decode error

When I decode o562s4yhR0fEUtuRrlO3LBpMl1A58LYTFQsPxKPiGpA
Other decoders give: £�¶³�¡GGÄRÛ�®S·,L�P9ð¶Ä£â�
Base64.decode gives: £�¶³�¡GGÄRۑ®S·,L�P9ð¶ģâ

"Uint8Array" Undefined error in ie8

when i use typescript and webpack compile
import { base64 } from 'js-base64'; base64.encode('string'); ...

ie8 throw a error:"Uint8Array" Undefined

when i debugging in base64.js, find that

buffer = require('buffer').Buffer;
buffer is exist,but Uint8Array is not, so ‘Uint8Array.from’ throw error

The number of lines that are wrongly reported is 163 and 82:
buffer.from && buffer.from !== Uint8Array.from ? ...

CommonJS support in browser

Frameworks like Component, Duo, etc... all let you use require() in the browser. Unfortunately these lines of code causes js-base64 not to be usable by them:

if (typeof module !== 'undefined' && module.exports) {
    buffer = require('buffer').Buffer;
}

Is there a better way to determine if you are running in node? If so we can use this library in the browser using CommonJS. Thanks!

Base64.decode 'undefined', missing module.exports

Hi,

when i require js-base64 via CommonJS

var js_base64_1 = require('js-base64');

js_base64_1.Base64.decode(output);

js_base64_1 will be not defined and i get an Base64.decode 'undefined' error.
But if i append an export declaration for the base64.js module

module.exports.Base64 = global.Base64;

in addition to

global.Base64 = {
        VERSION: version,
      ...
        decode: decode,
};

the code runs fine. So my questions are:

  1. Why does the code in its recent version not run in my environment / what am i doing wrong / is it outdated?
  2. What is the rationale for a 'global export of Base64' instead of a regular export? Can it be improved by a module.export?

ReferenceError: global is not defined

Hello,
after last update ( a day ago) I have the error:

ReferenceError: global is not defined

error line:
Base64 = global.Base64; // for normal export in Meteor.js

Error occurs when working with Meteor

At the bottom of file base64.js, the variable "global" is undefined in the context.
When I use visualize.js from Jaspersoft in Meteor, error occurs.

    // that's it!
})(this);

if (this['Meteor']) {
    Base64 = global.Base64; // for normal export in Meteor.js
}

Add Bower support

You may know about Bower, the new-ish popular package manager for Web assets.

Supporting it would allow users to install this library and include it to our projects in an easier and cleaner way.

All you need to do to support it is:

Create a manifest file

Create a component.json manifest file at the root of the repo with the following content:

{
  "name": "js-base64",
  "version": "1.0.0",
  "main": [
    "./base64.js"
  ],
  "ignore": [
    "old",
    "test"
  ],
  "dependencies": {
  }
}

Create a semantic tag

Create a Git tag called 1.0.0 from the master (it's important that it has 3 digits separated by dots):

git tag 1.0.0
git push origin 1.0.0

Register it

Register your repo on bower by installing bower and typing:

bower register js-base64 git://github.com/dankogai/js-base64.git

PS: I did step 1 & 2 on my fork if you wanna have a look. Didn't do step 3 because Bower registration works on a first-in first-served basis, and that would have meant stealing your repo ^^

SyntaxError: invalid range in character class

Hi. I use coffeescript and Hem (0.3.2) to build it. When i include base64.min.js to libraries, i get error: "SyntaxError: invalid range in character class". It is some problem with coffeescript, hem, or base64? I can use non minified version without any problem.

Base64 URL safe removes padding

If I put

Полтава

through the encoder I get

0J/QvtC70YLQsNCy0LA=

If I enable the URL safe method I get this

0J_QvtC70YLQsNCy0LA

Which has removed the trailing = padding as well as the expected conversion to URL safe

Bad for requirejs.

Can fix and use AMD?

requirejs.config(/* Config base64 path. */);
define(['base64'], function (b) {
    console.log(b);//undefined; 
    console.log(Base64); //It's OK.
});

git tag

Any chance of getting a git tag / release of js-base64? Thanks!

Import js error, Chrome Version 41.0.2272.101 m (64-bit)

Import: base64.min.js
Chrome error:Uncaught SyntaxError: Invalid regular expression: /[À-ß][€-¿]|[à-ï][€-¿]{2}|[ð-÷][€-¿]{3}/: Range out of order in character class
Then Import base64.js work well. And base64.min.js, base64.js work well in ie.

not work in webpack?

this is my conf
1、webpack.base.conf.js

resolve: {
        extensions: ['', '.js', '.vue'],
        fallback: [path.join(__dirname, '../node_modules')],
        alias: {
            'base64': path.resolve(__dirname, '../static/js/lib/base64'),
        }
    },

2、a.vue

<template>
</template>
<script>
require('expose?Base64!base64')
</script>

then get error

Uncaught TypeError: Cannot read property 'Base64' of undefined

after webpack,i found "this" turn 'undefined',like this

 function(module, exports, __webpack_require__) {

    eval("'use strict';\n\nvar _defineProperty = __webpack_require__(84);\n\nvar _defineProperty2 = _interopRequireDefault(_defineProperty);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n(function (global) {\n  'use strict';\n\n  var _Base64 = global.Base64;\n  var version = \"2.1.9\";\n\n  var buffer;\n  if (typeof module !== 'undefined' && module.exports) {\n    try {\n      buffer = __webpack_require__(263).Buffer;\n    } catch (err) {}\n  }\n\n  var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n  var b64tab = function (bin) {\n    var t = {};\n    for (var i = 0, l = bin.length; i < l; i++) {\n      t[bin.charAt(i)] = i;\n    }return t;\n  }(b64chars);\n  var fromCharCode = String.fromCharCode;\n\n  var cb_utob = function cb_utob(c) {\n    if (c.length < 2) {\n      var cc = c.charCodeAt(0);\n      return cc < 0x80 ? c : cc < 0x800 ? fromCharCode(0xc0 | cc >>> 6) + fromCharCode(0x80 | cc & 0x3f) : fromCharCode(0xe0 | cc >>> 12 & 0x0f) + fromCharCode(0x80 | cc >>> 6 & 0x3f) + fromCharCode(0x80 | cc & 0x3f);\n    } else {\n      var cc = 0x10000 + (c.charCodeAt(0) - 0xD800) * 0x400 + (c.charCodeAt(1) - 0xDC00);\n      return fromCharCode(0xf0 | cc >>> 18 & 0x07) + fromCharCode(0x80 | cc >>> 12 & 0x3f) + fromCharCode(0x80 | cc >>> 6 & 0x3f) + fromCharCode(0x80 | cc & 0x3f);\n    }\n  };\n  var re_utob = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFFF]|[^\\x00-\\x7F]/g;\n  var utob = function utob(u) {\n    return u.replace(re_utob, cb_utob);\n  };\n  var cb_encode = function cb_encode(ccc) {\n    var padlen = [0, 2, 1][ccc.length % 3],\n        ord = ccc.charCodeAt(0) << 16 | (ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8 | (ccc.length > 2 ? ccc.charCodeAt(2) : 0),\n        chars = [b64chars.charAt(ord >>> 18), b64chars.charAt(ord >>> 12 & 63), padlen >= 2 ? '=' : b64chars.charAt(ord >>> 6 & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63)];\n    return chars.join('');\n  };\n  var btoa = global.btoa ? function (b) {\n    return global.btoa(b);\n  } : function (b) {\n    return b.replace(/[\\s\\S]{1,3}/g, cb_encode);\n  };\n  var _encode = buffer ? function (u) {\n    return (u.constructor === buffer.constructor ? u : new buffer(u)).toString('base64');\n  } : function (u) {\n    return btoa(utob(u));\n  };\n  var encode = function encode(u, urisafe) {\n    return !urisafe ? _encode(String(u)) : _encode(String(u)).replace(/[+\\/]/g, function (m0) {\n      return m0 == '+' ? '-' : '_';\n    }).replace(/=/g, '');\n  };\n  var encodeURI = function encodeURI(u) {\n    return encode(u, true);\n  };\n\n  var re_btou = new RegExp(['[\\xC0-\\xDF][\\x80-\\xBF]', '[\\xE0-\\xEF][\\x80-\\xBF]{2}', '[\\xF0-\\xF7][\\x80-\\xBF]{3}'].join('|'), 'g');\n  var cb_btou = function cb_btou(cccc) {\n    switch (cccc.length) {\n      case 4:\n        var cp = (0x07 & cccc.charCodeAt(0)) << 18 | (0x3f & cccc.charCodeAt(1)) << 12 | (0x3f & cccc.charCodeAt(2)) << 6 | 0x3f & cccc.charCodeAt(3),\n            offset = cp - 0x10000;\n        return fromCharCode((offset >>> 10) + 0xD800) + fromCharCode((offset & 0x3FF) + 0xDC00);\n      case 3:\n        return fromCharCode((0x0f & cccc.charCodeAt(0)) << 12 | (0x3f & cccc.charCodeAt(1)) << 6 | 0x3f & cccc.charCodeAt(2));\n      default:\n        return fromCharCode((0x1f & cccc.charCodeAt(0)) << 6 | 0x3f & cccc.charCodeAt(1));\n    }\n  };\n  var btou = function btou(b) {\n    return b.replace(re_btou, cb_btou);\n  };\n  var cb_decode = function cb_decode(cccc) {\n    var len = cccc.length,\n        padlen = len % 4,\n        n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) | (len > 3 ? b64tab[cccc.charAt(3)] : 0),\n        chars = [fromCharCode(n >>> 16), fromCharCode(n >>> 8 & 0xff), fromCharCode(n & 0xff)];\n    chars.length -= [0, 0, 2, 1][padlen];\n    return chars.join('');\n  };\n  var atob = global.atob ? function (a) {\n    return global.atob(a);\n  } : function (a) {\n    return a.replace(/[\\s\\S]{1,4}/g, cb_decode);\n  };\n  var _decode = buffer ? function (a) {\n    return (a.constructor === buffer.constructor ? a : new buffer(a, 'base64')).toString();\n  } : function (a) {\n    return btou(atob(a));\n  };\n  var decode = function decode(a) {\n    return _decode(String(a).replace(/[-_]/g, function (m0) {\n      return m0 == '-' ? '+' : '/';\n    }).replace(/[^A-Za-z0-9\\+\\/]/g, ''));\n  };\n  var noConflict = function noConflict() {\n    var Base64 = global.Base64;\n    global.Base64 = _Base64;\n    return Base64;\n  };\n\n  global.Base64 = {\n    VERSION: version,\n    atob: atob,\n    btoa: btoa,\n    fromBase64: decode,\n    toBase64: encode,\n    utob: utob,\n    encode: encode,\n    encodeURI: encodeURI,\n    btou: btou,\n    decode: decode,\n    noConflict: noConflict\n  };\n\n  if (typeof _defineProperty2.default === 'function') {\n    var noEnum = function noEnum(v) {\n      return { value: v, enumerable: false, writable: true, configurable: true };\n    };\n    global.Base64.extendString = function () {\n      Object.defineProperty(String.prototype, 'fromBase64', noEnum(function () {\n        return decode(this);\n      }));\n      Object.defineProperty(String.prototype, 'toBase64', noEnum(function (urisafe) {\n        return encode(this, urisafe);\n      }));\n      Object.defineProperty(String.prototype, 'toBase64URI', noEnum(function () {\n        return encode(this, true);\n      }));\n    };\n  }\n\n  if (global['Meteor']) {\n    Base64 = global.Base64;\n  }\n})(undefined);}

how can i solved it?

base64 is not a function

Just got this when running Gulp on a third party project :

TypeError: base64 is not a function
    at Function.from (native)
    at Function.from (native)
    at /path/to/project/node_modules/js-base64/base64.js:148:34
    at Object.decode (/path/to/project/node_modules/js-base64/base64.js:156:16)
    at PreviousMap.decodeInline (/path/to/project/node_modules/postcss/lib/previous-map.js:106:35)
    at PreviousMap.loadMap (/path/to/project/node_modules/postcss/lib/previous-map.js:138:25)

    at new PreviousMap (/path/to/project/node_modules/postcss/lib/previous-map.js:52:25)
    at new Input (/path/to/project/node_modules/postcss/lib/input.js:73:19)
    at parse (/path/to/project/node_modules/postcss/lib/parse.js:21:17)
    at new LazyResult (/path/to/project/node_modules/postcss/lib/lazy-result.js:70:24)
    at Processor.process (/path/to/project/node_modules/postcss/lib/processor.js:117:12)
    at DestroyableTransform._transform (/path/to/project/node_modules/gulp-autoprefixer/index.js:20:31)
    at DestroyableTransform.Transform._read (/path/to/project/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:182:10)
    at DestroyableTransform.Transform._write (/path/to/project/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:170:83)
    at doWrite (/path/to/project/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:406:64)
    at writeOrBuffer (/path/to/project/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:395:5)

I am still investigating what can cause this, but since it affects this module, I concluded that perhaps someone more familiar with it may have an idea why or how to gracefully handle this better.

Please clarify license.

In #17 and at the top of base64.js, you mention that it is MIT licensed. But package.json and npmjs.org say that it is BSD licensed.

Could you clarify which it is and, if possible, also add a LICENSE file with the full text?

ES6 import feels wrong

With CommonJS you can add an param to the end of the require statement.

var Base64 = require('./base64.js').Base64;
Base64.encode(data)

In ES6 you can't so you have to call it like this and it just feels wrong, and is super confusing.

import base64 from "js-base64"
base64.Base64.encode(data)

'There is no timestamp for /base/src/buffer.js!'

Hi. After update I get next error in mine karma.
'There is no timestamp for /base/src/buffer.js!'
Can you help me and answer what it can be?
Karma conf didn't change. I updated js-base to 2.4.0. Node v9.4.0

base64 validator

This is just an enhancement request, not a bug.

It would be nice if this library would validate input to the decode functions, or at least provide a function to do so. If you use the Base64.decode function with invalid base64 characters, garbage is returned.

This is fixed by doing the check myself, but this does seem like something that could be added here for convenience.

Native Support for Base-64 Encoding and Decoding in Browsers

Client-Side JavaScript implementations (browsers) already have a built-in functions for encoding and decoding a string of binary data and base-64 encoded ASCII strings respectively.

  • The window.btoa function accepts a string of binary data and encodes it as a base-64 encoded ASCII string.
  • The window.atob function accepts a base-64 encoded ASCII string and decodes it as a string of binary data.
var encodedData = window.btoa("Hey World"); // encode a string
var decodedData = window.atob(encodedData); // decode the string

To base-64 encode and decode utf-8 strings use the following functions:

function utf8ToBase64(string) {
    return window.btoa(unescape(encodeURIComponent(string)));
}

function base64ToUTF8(string) {
    return decodeURIComponent(escape(window.atob(string)));
}

Does not compile on Fedora25

Using this package.json:

{
  "name": "test",
  "version": "0.0.1",
  "license": "AGPL-3.0",
  "private": true,
  "dependencies": {
    "intl": "~1.2.5",
    "base64": "~2.1.0"
  },
  "devDependencies": {
    "jshint": "^2.9.2"
  }
}

$ LANG=C npm install

> [email protected] install /home/cf/Development/test/node_modules/base64
> node-gyp rebuild

make: Verzeichnis „/home/cf/Development/test/node_modules/base64/build“ wird betreten
  CXX(target) Release/obj.target/base64/base64.o
../base64.cc: In Funktion »v8::Handle<v8::Value> VException(const char*)«:
../base64.cc:13:17: Fehler: »v8::HandleScope::HandleScope()« is protected within this context
     HandleScope scope;
                 ^~~~~
In file included from ../base64.cc:4:0:
/home/cf/.node-gyp/6.3.1/include/node/v8.h:904:13: Anmerkung: declared protected here
   V8_INLINE HandleScope() {}
             ^~~~~~~~~~~
../base64.cc:14:44: Fehler: »New« ist kein Element von »v8::String«
     return ThrowException(Exception::Error(String::New(msg)));
                                            ^~~~~~
../base64.cc:14:61: Fehler: »ThrowException« wurde in diesem Gültigkeitsbereich nicht definiert
     return ThrowException(Exception::Error(String::New(msg)));
                                                             ^
../base64.cc: Im globalen Gültigkeitsbereich:
../base64.cc:122:29: Fehler: »Arguments« bezeichnet keinen Typ
 base64_encode_binding(const Arguments &args)
                             ^~~~~~~~~
../base64.cc: In Funktion »v8::Handle<v8::Value> base64_encode_binding(const int&)«:
../base64.cc:124:17: Fehler: »v8::HandleScope::HandleScope()« is protected within this context
     HandleScope scope;
                 ^~~~~
In file included from ../base64.cc:4:0:
/home/cf/.node-gyp/6.3.1/include/node/v8.h:904:13: Anmerkung: declared protected here
   V8_INLINE HandleScope() {}
             ^~~~~~~~~~~
../base64.cc:127:14: Fehler: Abfrage des Elementes »Length« in »args«, das vom Nicht-Klassentyp »const int« ist
     if (args.Length() != 1)
              ^~~~~~
../base64.cc:130:35: Fehler: ungültige Typen »const int[int]« für Feldindex
     if (Buffer::HasInstance(args[0])) {
                                   ^
../base64.cc:131:47: Fehler: ungültige Typen »const int[int]« für Feldindex
         v8::Handle<v8::Object> buffer = args[0]->ToObject();
                                               ^
../base64.cc:137:20: Fehler: ungültige Typen »const int[int]« für Feldindex
     else if (args[0]->IsString()) {
                    ^
../base64.cc:138:40: Fehler: ungültige Typen »const int[int]« für Feldindex
         String::Utf8Value v8str (args[0]->ToString());
                                        ^
../base64.cc:144:25: Fehler: »New« ist kein Element von »v8::String«
     Local<String> ret = String::New(str);
                         ^~~~~~
../base64.cc:146:18: Fehler: »class v8::HandleScope« has no member named »Close«
     return scope.Close(ret);
                  ^~~~~
../base64.cc: Im globalen Gültigkeitsbereich:
../base64.cc:150:29: Fehler: »Arguments« bezeichnet keinen Typ
 base64_decode_binding(const Arguments &args)
                             ^~~~~~~~~
../base64.cc: In Funktion »v8::Handle<v8::Value> base64_decode_binding(const int&)«:
../base64.cc:152:17: Fehler: »v8::HandleScope::HandleScope()« is protected within this context
     HandleScope scope;
                 ^~~~~
In file included from ../base64.cc:4:0:
/home/cf/.node-gyp/6.3.1/include/node/v8.h:904:13: Anmerkung: declared protected here
   V8_INLINE HandleScope() {}
             ^~~~~~~~~~~
../base64.cc:155:14: Fehler: Abfrage des Elementes »Length« in »args«, das vom Nicht-Klassentyp »const int« ist
     if (args.Length() < 1)
              ^~~~~~
../base64.cc:160:35: Fehler: ungültige Typen »const int[int]« für Feldindex
     if (Buffer::HasInstance(args[0])) { // buffer
                                   ^
../base64.cc:161:47: Fehler: ungültige Typen »const int[int]« für Feldindex
         v8::Handle<v8::Object> buffer = args[0]->ToObject();
                                               ^
../base64.cc:170:9: Fehler: »AsciiValue« ist kein Element von »v8::String«
         String::AsciiValue b64data(args[0]->ToString());
         ^~~~~~
../base64.cc:171:34: Fehler: »b64data« wurde in diesem Gültigkeitsbereich nicht definiert
         decoded = base64_decode(*b64data, b64data.length(), &outlen);
                                  ^~~~~~~
../base64.cc:174:14: Fehler: Abfrage des Elementes »Length« in »args«, das vom Nicht-Klassentyp »const int« ist
     if (args.Length() > 1 && args[1]->IsString()) {
              ^~~~~~
../base64.cc:174:36: Fehler: ungültige Typen »const int[int]« für Feldindex
     if (args.Length() > 1 && args[1]->IsString()) {
                                    ^
../base64.cc:175:9: Fehler: »AsciiValue« ist kein Element von »v8::String«
         String::AsciiValue flag(args[1]->ToString());
         ^~~~~~
../base64.cc:176:29: Fehler: »flag« wurde in diesem Gültigkeitsbereich nicht definiert
         if (strcmp("utf8", *flag) == 0) encflag = UTF8;
                             ^~~~
../base64.cc:179:55: Warnung: »v8::Local<v8::Value> node::Encode(const void*, size_t, node::encoding)« ist veraltet: Use Encode(isolate, ...) [-Wdeprecated-declarations]
     Local<Value> ret = Encode(decoded, outlen, encflag);
                                                       ^
In file included from ../base64.cc:5:0:
/home/cf/.node-gyp/6.3.1/include/node/node.h:319:45: Anmerkung: hier deklariert
                 inline v8::Local<v8::Value> Encode(
                                             ^
/home/cf/.node-gyp/6.3.1/include/node/node.h:66:42: Anmerkung: in Definition des Makros »NODE_DEPRECATED«
     __attribute__((deprecated(message))) declarator
                                          ^~~~~~~~~~
../base64.cc:182:18: Fehler: »class v8::HandleScope« has no member named »Close«
     return scope.Close(ret);
                  ^~~~~
../base64.cc: In Funktion »void init(v8::Handle<v8::Object>)«:
../base64.cc:187:17: Fehler: »v8::HandleScope::HandleScope()« is protected within this context
     HandleScope scope;
                 ^~~~~
In file included from ../base64.cc:4:0:
/home/cf/.node-gyp/6.3.1/include/node/v8.h:904:13: Anmerkung: declared protected here
   V8_INLINE HandleScope() {}
             ^~~~~~~~~~~
../base64.cc:188:17: Fehler: »New« ist kein Element von »v8::String«
     target->Set(String::New("encode"), FunctionTemplate::New(base64_encode_binding)->GetFunction());
                 ^~~~~~
../base64.cc:188:83: Fehler: keine passende Funktion für Aufruf von »v8::FunctionTemplate::New(v8::Handle<v8::Value> (&)(const int&))«
     target->Set(String::New("encode"), FunctionTemplate::New(base64_encode_binding)->GetFunction());
                                                                                   ^
In file included from ../base64.cc:4:0:
/home/cf/.node-gyp/6.3.1/include/node/v8.h:4452:34: Anmerkung: candidate: static v8::Local<v8::FunctionTemplate> v8::FunctionTemplate::New(v8::Isolate*, v8::FunctionCallback, v8::Local<v8::Value>, v8::Local<v8::Signature>, int)
   static Local<FunctionTemplate> New(
                                  ^~~
/home/cf/.node-gyp/6.3.1/include/node/v8.h:4452:34: Anmerkung:   keine bekannte Umwandlung für Argument 1 von »v8::Handle<v8::Value>(const int&) {aka v8::Local<v8::Value>(const int&)}« nach »v8::Isolate*«
../base64.cc:189:17: Fehler: »New« ist kein Element von »v8::String«
     target->Set(String::New("decode"), FunctionTemplate::New(base64_decode_binding)->GetFunction());
                 ^~~~~~
../base64.cc:189:83: Fehler: keine passende Funktion für Aufruf von »v8::FunctionTemplate::New(v8::Handle<v8::Value> (&)(const int&))«
     target->Set(String::New("decode"), FunctionTemplate::New(base64_decode_binding)->GetFunction());
                                                                                   ^
In file included from ../base64.cc:4:0:
/home/cf/.node-gyp/6.3.1/include/node/v8.h:4452:34: Anmerkung: candidate: static v8::Local<v8::FunctionTemplate> v8::FunctionTemplate::New(v8::Isolate*, v8::FunctionCallback, v8::Local<v8::Value>, v8::Local<v8::Signature>, int)
   static Local<FunctionTemplate> New(
                                  ^~~
/home/cf/.node-gyp/6.3.1/include/node/v8.h:4452:34: Anmerkung:   keine bekannte Umwandlung für Argument 1 von »v8::Handle<v8::Value>(const int&) {aka v8::Local<v8::Value>(const int&)}« nach »v8::Isolate*«
base64.target.mk:86: die Regel für Ziel „Release/obj.target/base64/base64.o“ scheiterte
make: *** [Release/obj.target/base64/base64.o] Fehler 1
make: Verzeichnis „/home/cf/Development/test/node_modules/base64/build“ wird verlassen
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/home/cf/Development/node-v6.3.1-linux-x64/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:276:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:204:12)
gyp ERR! System Linux 4.10.10-200.fc25.x86_64
gyp ERR! command "/home/cf/Development/node-v6.3.1-linux-x64/bin/node" "/home/cf/Development/node-v6.3.1-linux-x64/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/cf/Development/test/node_modules/base64
gyp ERR! node -v v6.3.1
gyp ERR! node-gyp -v v3.3.1
gyp ERR! not ok 
npm ERR! Linux 4.10.10-200.fc25.x86_64
npm ERR! argv "/home/cf/Development/node-v6.3.1-linux-x64/bin/node" "/usr/local/bin/npm" "install"
npm ERR! node v6.3.1
npm ERR! npm  v3.10.3
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the base64 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs base64
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls base64
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/cf/Development/test/npm-debug.log

Fedora 25 installation uses following GCC/C++ packages:

gcc-c++-6.3.1-1.fc25.x86_64
libstdc++-6.3.1-1.fc25.x86_64
libsigc++20-2.10.0-1.fc25.x86_64
libstdc++-devel-6.3.1-1.fc25.x86_64
gcc-6.3.1-1.fc25.x86_64
gcc-c++-6.3.1-1.fc25.x86_64
gcc-gdb-plugin-6.3.1-1.fc25.x86_64
libgcc-6.3.1-1.fc25.x86_64

If js-base64 assumes existence of specific packages, this should be documented.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.