Created
September 12, 2015 20:46
-
-
Save dbrockman/067be51033673700d2fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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