46 lines
785 B
JavaScript
46 lines
785 B
JavaScript
|
/**
|
||
|
* Module dependencies.
|
||
|
*/
|
||
|
|
||
|
var Base64 = require('Base64');
|
||
|
|
||
|
/**
|
||
|
* Expose `base64_url_decode`
|
||
|
*/
|
||
|
|
||
|
module.exports = {
|
||
|
encode: encode,
|
||
|
decode: decode
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Encode a `base64` `encodeURIComponent` string
|
||
|
*
|
||
|
* @param {string} str
|
||
|
* @public
|
||
|
*/
|
||
|
|
||
|
function encode(str) {
|
||
|
return Base64.btoa(str)
|
||
|
.replace(/\+/g, '-') // Convert '+' to '-'
|
||
|
.replace(/\//g, '_') // Convert '/' to '_'
|
||
|
.replace(/=+$/, ''); // Remove ending '='
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Decode a `base64` `encodeURIComponent` string
|
||
|
*
|
||
|
* @param {string} str
|
||
|
* @public
|
||
|
*/
|
||
|
|
||
|
function decode(str) {
|
||
|
// Add removed at end '='
|
||
|
str += Array(5 - str.length % 4).join('=');
|
||
|
|
||
|
str = str
|
||
|
.replace(/\-/g, '+') // Convert '-' to '+'
|
||
|
.replace(/\_/g, '/'); // Convert '_' to '/'
|
||
|
|
||
|
return Base64.atob(str);
|
||
|
}
|