Giter Club home page Giter Club logo

base64's Introduction

base64 Build status Code coverage status

base64 is a robust base64 encoder/decoder that is fully compatible with atob() and btoa(), written in JavaScript. The base64-encoding and -decoding algorithms it uses are fully RFC 4648 compliant.

Installation

Via npm:

npm install base-64

In a browser:

<script src="base64.js"></script>

In Narwhal, Node.js, and RingoJS:

var base64 = require('base-64');

In Rhino:

load('base64.js');

Using an AMD loader like RequireJS:

require(
  {
    'paths': {
      'base64': 'path/to/base64'
    }
  },
  ['base64'],
  function(base64) {
    console.log(base64);
  }
);

API

base64.version

A string representing the semantic version number.

base64.encode(input)

This function takes a byte string (the input parameter) and encodes it according to base64. The input data must be in the form of a string containing only characters in the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. The base64.encode() function is designed to be fully compatible with btoa() as described in the HTML Standard.

var encodedData = base64.encode(input);

To base64-encode any Unicode string, encode it as UTF-8 first:

var base64 = require('base-64');
var utf8 = require('utf8');

var text = 'foo © bar 𝌆 baz';
var bytes = utf8.encode(text);
var encoded = base64.encode(bytes);
console.log(encoded);
// → 'Zm9vIMKpIGJhciDwnYyGIGJheg=='

base64.decode(input)

This function takes a base64-encoded string (the input parameter) and decodes it. The return value is in the form of a string containing only characters in the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. The base64.decode() function is designed to be fully compatible with atob() as described in the HTML Standard.

var decodedData = base64.decode(encodedData);

To base64-decode UTF-8-encoded data back into a Unicode string, UTF-8-decode it after base64-decoding it:

var encoded = 'Zm9vIMKpIGJhciDwnYyGIGJheg==';
var bytes = base64.decode(encoded);
var text = utf8.decode(bytes);
console.log(text);
// → 'foo © bar 𝌆 baz'

Support

base64 is designed to work in at least Node.js v0.10.0, Narwhal 0.3.2, RingoJS 0.8-0.9, PhantomJS 1.9.0, Rhino 1.7RC4, as well as old and modern versions of Chrome, Firefox, Safari, Opera, and Internet Explorer.

Unit tests & code coverage

After cloning this repository, run npm install to install the dependencies needed for development and testing. You may want to install Istanbul globally using npm install istanbul -g.

Once that’s done, you can run the unit tests in Node using npm test or node tests/tests.js. To run the tests in Rhino, Ringo, Narwhal, and web browsers as well, use grunt test.

To generate the code coverage report, use grunt cover.

Author

twitter/mathias
Mathias Bynens

License

base64 is available under the MIT license.

base64's People

Contributors

mathiasbynens 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

base64's Issues

UTF-8 error

base64.decode(text); // return "localização";
correct // return "localização";
posible solution?

Convert Base64 string to Utf-8 byte array

I'm currently working on a feature to provide images to a partner in utf-8 bytecode. We currently store images as base64 strings. I've tried using your base64 and utf8 packages to accomplish this, but I think I'm doing something wrong.

My thought process is:

  1. decode string from base 64
  2. encode as utf-8
  3. create a buffer from the utf string
  4. spread the buffer to an array.
// const b64 = base64 string
const bytes = base64.decode(b64);
const utf = utf8.encode(bytes);

const buff = Buffer.from(utf, 'utf8');
const arr = [...buff];

How import this in react native?

How import this in react native?

const base64 = require('base-64');
Module does not exist in the module map or in these directories

not added to package.JSON but there base64 folder in node modules.

Test cases are not running

Hi,

I am trying to run the test cases with npm on my system, and each item I am facing this issue, the system does not proceed further from this.

root@a213ad56268a:/shreya/base64# npm test

> [email protected] test /shreya/base64
> node tests/tests.js

Please wait.

I have look into the issue, the error is coming the quint-extras.js file present in node_modules/qunit-extras/qunit-extras.js directory.
Quint-extras is one of the dev dependencies of the package.

Please suggest what can be done to resolve the error.

Envirnonment -
1- npm version 6.4.1
2- node version v10.8.0

Decode issue

Hy. I have encoded a string that contains a price with EURO SIGN in it.

Original text was:
Inclusief eenmalige korting van € 130 & verlaagd vastrecht.

After decode the text is:
Inclusief eenmalige korting van � 130 & verlaagd vastrecht.

As you see the euro sign is missing

Thanks

Invalid UTF-8 detected

var encoded = 'Zm9vIMKpIGJhciDwnYyGIGJheg==';
var bytes = base64.decode(encoded);
var text = utf8.decode(bytes);
console.log(text);
output
Invalid UTF-8 detected

Bad performance with Hermes Engine

Hello, I am using this package in a React Native app.
The problem is that while using the Hermes Engine the string concatenation with += is very slow.

With this issue https://github.com/facebook/hermes/issues/111 one of Herme's developers suggested to use output as an array and push elements to it and finally join everything.
Can this package be modified to support those kinds of optimizations and be used with the new Hermes Engine?

Thank you

RangeError: Maximum call stack size exceeded for large ArrayBuffer

Hello,

I am running into the following error:
RangeError: Maximum call stack size exceeded.
I am converting an ArrayBuffer to a Base64String using the encoding function.

I am getting this ArrayBuffer as a response from a server. The ArrayBuffer length is 92778. I am thinking that this is causing the problem. Could someone confirm that this may cause this error? And if there is a workaround that may be able to help.

Below is the code that I am running to generate the string

var base64 = require('base-64');
var pdf_base64Str = base64.encode(String.fromCharCode.apply(null, new Uint8Array(response.data)));

Thanks

Returns error if string I want to decode contains dot character (.)

If string contains . while calling decode method, then next error will appear:

InvalidCharacterError
at /home/kuno/code/aviokarte-web/node_modules/base-64/base64.js:23:36
at Object. (/home/kuno/code/aviokarte-web/node_modules/base-64/base64.js:165:2)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (/home/kuno/code/aviokarte-web/seeders/fetch_sample_pages.js:3:14)

Legal comment is removed when package is bundled and uglified

Hello,

I noticed that the legal comment is removed when this package is bundled (with browserify) and minified (with UglifyJS2).

Let me first say that this IS an issue in Uglify, see mishoo/UglifyJS#88 (comment) for more info. Uglify seems to fail adding the comment node to the AST. I post this issue more as FYI if you are concerned about userland honouring the legal stuff.

Testing this is pretty easy:

> browserify -r base-64 | uglifyjs --beautify --comments all

I also see this in https://github.com/mathiasbynens/utf8.js

The real solution would ofc to fix Uglify but the referenced issue above is old and I don't expect to see any fix soon.

By doing some shotgun debugging I found that moving the introductory semicolon to be the first character in the file, before the legal comment, makes Uglify parse it and make it a part of the AST. Also removing the semicolon renders the same result but makes the code vulnerable to other bundling processes like concatenation.

Tested with [email protected] and [email protected] but saw issue with older versions aswell.

Thanks for developing this package!

React native encode base64

Hi, Just trying to run your example from the readme to see if the code works correctly.

import utf8 from 'utf8'
import base64 from 'base-64'

var text = 'foo © bar 𝌆 baz';
var bytes = utf8.encode(text);
var encoded = base64.encode(bytes);
console.log(encoded);
// → 'Zm9vIMKpIGJhciDwnYyGIGJheg=='

When I run the above code I am getting the following. Can you please let me know what I am doing wrong please.

W29iamVjdCBBcnJheUJ1ZmZlcl0=

Please help

How do i import this

I can't use require('blah') only import.

What is the correct syntax to import this.

Not working with UTF-8

I tried to convert a JSON string to Base64 with this package, depend on the README, but it's simply return an [object ArrayBuffer] and I can't get the value from the object as a string.

Here is the code which I have written.

var text = data.profile; // It is a JSON string.
var bytes = utf8.encode(text);
var encoded = base64.encode(bytes);
_this.changeURL(_this.domain+"user/fb_login_callback?userNode="+encoded);

errors during installation

npm version: 5.5.1
node version: 8.6.0
OS: macOS 10.12.6

$ npm install --save base64

> node-gyp rebuild

  CXX(target) Release/obj.target/base64/base64.o
../base64.cc:13:17: error: calling a protected constructor of class 'v8::HandleScope'
    HandleScope scope;
                ^
~/.node-gyp/8.6.0/include/node/v8.h:876:13: note: declared protected here
  V8_INLINE HandleScope() {}
            ^
../base64.cc:14:52: error: no member named 'New' in 'v8::String'
    return ThrowException(Exception::Error(String::New(msg)));
                                           ~~~~~~~~^
../base64.cc:122:29: error: unknown type name 'Arguments'; did you mean 'v8::internal::Arguments'?
base64_encode_binding(const Arguments &args)
                            ^~~~~~~~~
                            v8::internal::Arguments
~/.node-gyp/8.6.0/include/node/v8.h:141:7: note: 'v8::internal::Arguments' declared here
class Arguments;
      ^
../base64.cc:124:17: error: calling a protected constructor of class 'v8::HandleScope'
    HandleScope scope;
                ^
/Users/blakewillmarth/.node-gyp/8.6.0/include/node/v8.h:876:13: note: declared protected here
  V8_INLINE HandleScope() {}
            ^
../base64.cc:127:13: error: member access into incomplete type 'const v8::internal::Arguments'
    if (args.Length() != 1)
            ^
~/.node-gyp/8.6.0/include/node/v8.h:141:7: note: forward declaration of 'v8::internal::Arguments'
class Arguments;
      ^
../base64.cc:130:33: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    if (Buffer::HasInstance(args[0])) {
                            ~~~~^~
../base64.cc:131:45: error: type 'const v8::internal::Arguments' does not provide a subscript operator
        v8::Handle<v8::Object> buffer = args[0]->ToObject();
                                        ~~~~^~
../base64.cc:137:18: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    else if (args[0]->IsString()) {
             ~~~~^~
../base64.cc:138:38: error: type 'const v8::internal::Arguments' does not provide a subscript operator
        String::Utf8Value v8str (args[0]->ToString());
                                 ~~~~^~
../base64.cc:144:33: error: no member named 'New' in 'v8::String'
    Local<String> ret = String::New(str);
                        ~~~~~~~~^
../base64.cc:146:18: error: no member named 'Close' in 'v8::HandleScope'
    return scope.Close(ret);
           ~~~~~ ^
../base64.cc:150:29: error: unknown type name 'Arguments'; did you mean 'v8::internal::Arguments'?
base64_decode_binding(const Arguments &args)
                            ^~~~~~~~~
                            v8::internal::Arguments
~/.node-gyp/8.6.0/include/node/v8.h:141:7: note: 'v8::internal::Arguments' declared here
class Arguments;
      ^
../base64.cc:152:17: error: calling a protected constructor of class 'v8::HandleScope'
    HandleScope scope;
                ^
/Users/blakewillmarth/.node-gyp/8.6.0/include/node/v8.h:876:13: note: declared protected here
  V8_INLINE HandleScope() {}
            ^
../base64.cc:155:13: error: member access into incomplete type 'const v8::internal::Arguments'
    if (args.Length() < 1)
            ^
/Users/blakewillmarth/.node-gyp/8.6.0/include/node/v8.h:141:7: note: forward declaration of 'v8::internal::Arguments'
class Arguments;
      ^
../base64.cc:160:33: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    if (Buffer::HasInstance(args[0])) { // buffer
                            ~~~~^~
../base64.cc:161:45: error: type 'const v8::internal::Arguments' does not provide a subscript operator
        v8::Handle<v8::Object> buffer = args[0]->ToObject();
                                        ~~~~^~
../base64.cc:170:27: error: expected ';' after expression
        String::AsciiValue b64data(args[0]->ToString());
                          ^
                          ;
../base64.cc:170:17: error: no member named 'AsciiValue' in 'v8::String'
        String::AsciiValue b64data(args[0]->ToString());
        ~~~~~~~~^
../base64.cc:170:40: error: type 'const v8::internal::Arguments' does not provide a subscript operator
        String::AsciiValue b64data(args[0]->ToString());
                                   ~~~~^~
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
make: *** [Release/obj.target/base64/base64.o] Error 1
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:258:23)
gyp ERR! stack     at emitTwo (events.js:125:13)
gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 16.7.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd ...
gyp ERR! node -v v8.6.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok 

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Should I use this package, or atob and btoa?

A topic for discussion: this repo very closely resembles atob and btoa

I find myself in a pickle when deciding which library to use - atob and btoa seem attractive because of the usage stats, longevity, and update frequency, but this one is written by web hero Mathias Bynens.. would it be possible to describe what (if any) major differences there are between the two options to help us decide?

Error when trying to encode Vietnamese chars

Error when trying to encode Vietnamese chars

InvalidCharacterError
at /home/runner/invalidlatin/node_modules/base-64/base64.js:23:36
at Object. (/home/runner/invalidlatin/node_modules/base-64/base64.js:165:2)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require (internal/modules/cjs/loader.js:1019:19)
at /home/runner/invalidlatin/index.js:1:17
at Script.runInContext (vm.js:131:20)

Code

const base64  = require("base-64") ;

const str= "Những hình dạng của kinh tế hậu COVID-19 - Tuổi Trẻ Online";

console.log(base64.encode(str))

Error Example:
https://repl.it/@SoubhikChatterj/invalidlatin

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.