Skip to content

Instantly share code, notes, and snippets.

@zivester
Last active December 15, 2015 22:19
Show Gist options
  • Select an option

  • Save zivester/5332362 to your computer and use it in GitHub Desktop.

Select an option

Save zivester/5332362 to your computer and use it in GitHub Desktop.
encoding/decoding and Buffers
// Return a buffer, that when encoded to base64, will be of size "length"
exports.randomBytesBase64 = function(length){
length = Math.ceil(length * 3/4);
return require('crypto').randomBytes(length);
}
// Take a buffer and create a base64, url safe encoding
exports.urlEncode = function(buffer){
return buffer.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
}
exports.urlDecode = function(string){
return new Buffer(string.replace(/_/g,'/').replace(/\-/g,'+'), 'base64');
}
var original = exports.randomBytesBase64(8),
encoded = exports.urlEncode(original),
decoded = exports.urlDecode(encoded);
// original should be the same as decoded
console.log(original, encoded.toString(), decoded, original.toString() == decoded.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment