var bases = require('bases'); var crypto = require('crypto'); // Returns a base-62 (alphanumeric only) string of the given length: function randomStr(length) { // We generate a random number in a space at least as big as 62^length, // and if it's too big, we just retry. This is still statistically O(1) // since repeated probabilities less than one converge to zero. Hat-tip to // a Google interview for teaching me this technique! ;) // The native randomBytes() returns an array of bytes, each of which is // effectively a base-256 integer. We derive the number of bytes to // generate based on that, but note that it can overflow after ~150: var maxNum = Math.pow(62, length); var numBytes = Math.ceil(Math.log(maxNum) / Math.log(256)); if (numBytes === Infinity) { throw new Error('Length too large; caused overflow: ' + length); } do { var bytes = crypto.randomBytes(numBytes); var num = 0 for (var i = 0; i < bytes.length; i++) { num += Math.pow(256, i) * bytes[i]; } } while (num >= maxNum); return bases.toBase62(num); } for (var i = 1; i < 80; i++) { console.log(randomStr(i)); }