Skip to content

Instantly share code, notes, and snippets.

@Agoreddah
Last active November 29, 2018 13:30
Show Gist options
  • Save Agoreddah/b39c2b17ed885e9c2471a2011a27d79a to your computer and use it in GitHub Desktop.
Save Agoreddah/b39c2b17ed885e9c2471a2011a27d79a to your computer and use it in GitHub Desktop.
Simple token generator with bin2hex in node.js
const crypto = require('crypto');
/**
* Convert binary to hex.
* @param {Number} bytesLength
*/
function bin2hex( bytesLength ){
let bin = crypto.randomBytes( bytesLength );
return new Buffer( bin ).toString( "hex" );
}
/**
* Generate simple token.
* @param {String} tokenPrefix default value is ''
* @param {Number} bytesLength default value is 10
*/
function getSimpleToken( tokenPrefix = '', bytesLength = 10 ){
return tokenPrefix + bin2hex( bytesLength );
}
getSimpleToken('token-');
// Example result: token-a56083f85c6306854088
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment