Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An extremely simple implementation of base64 encoding / decoding using node.js Buffers (plus url-safe versions)
/*
* base64.js: An extremely simple implementation of base64 encoding / decoding using node.js Buffers
*
* (C) 2010, Nodejitsu Inc.
* (C) 2011, Cull TV, Inc.
*
*/
var base64 = exports;
base64.encode = function(unencoded) {
return new Buffer(unencoded || '').toString('base64');
};
base64.decode = function(encoded) {
return new Buffer(encoded || '', 'base64').toString('utf8');
};
base64.urlEncode = function(unencoded) {
var encoded = base64.encode(unencoded);
return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
};
base64.urlDecode = function(encoded) {
encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');
while (encoded.length % 4)
encoded += '=';
return base64.decode(encoded);
};
@WangJi

This comment has been minimized.

Copy link

commented Sep 25, 2017

nice work.

@cosinekitty

This comment has been minimized.

Copy link

commented Oct 24, 2018

Thank you for saving me time and allowing me to have one less npm package dependency.

@mike-marcacci

This comment has been minimized.

Copy link

commented Apr 28, 2019

These are incorrect, as using string patterns in .replace() will only replace the first instance; instead you need to use regex with the g flag:

encoded.replace(/\+/g, '-').replace(/\//, '_').replace(/=+$/, '');
@netzmensch

This comment has been minimized.

Copy link

commented Jul 15, 2019

Your line is also incorrect, as you missed the "g" for the last two replacements :)

encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');

@aaronjameslang

This comment has been minimized.

Copy link

commented Aug 1, 2019

I don't know that it's needed for the last one as the + is greedy, but it shoudln't hurt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.