Skip to content

Instantly share code, notes, and snippets.

@dbrockman
Created September 12, 2015 20:46
Show Gist options
  • Save dbrockman/067be51033673700d2fa to your computer and use it in GitHub Desktop.
Save dbrockman/067be51033673700d2fa to your computer and use it in GitHub Desktop.
const encode_regex = /[\+=\/]/g;
const decode_regex = /[\._\-]/g;
// Buffer -> Base64 String -> Url Safe Base64 String
export function encode(buffer) {
return buffer.toString('base64').replace(encode_regex, encodeChar);
}
// Url Safe Base64 String -> Base64 String -> Buffer
export function decode(string) {
return new Buffer(string.replace(decode_regex, decodeChar), 'base64');
}
function encodeChar(c) {
switch (c) {
case '+': return '.';
case '=': return '-';
case '/': return '_';
}
}
function decodeChar(c) {
switch (c) {
case '.': return '+';
case '-': return '=';
case '_': return '/';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment