Created
September 5, 2013 05:50
-
-
Save makotom/6446491 to your computer and use it in GitHub Desktop.
JS random string generator
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
(function(){ | |
"use strict"; | |
var URANDSRC = "/dev/urandom", | |
getUrandomInt8 = (function(){ | |
var fs = require("fs"), | |
urandom = fs.openSync(URANDSRC, "r"), | |
buf = new Buffer(1); | |
return function(){ | |
fs.readSync(urandom, buf, 0, 1, 0); | |
return buf.readUInt8(0); | |
}; | |
})(), | |
createCharPool = function(type){ | |
var i = 0, | |
ret = []; | |
switch(type){ | |
case "lower": | |
for(i = 48; i <= 57; i += 1){ | |
ret.push(String.fromCharCode(i)); | |
} | |
for(i = 97; i <= 122; i += 1){ | |
ret.push(String.fromCharCode(i)); | |
} | |
break; | |
case "mixed": | |
for(i = 48; i <= 57; i += 1){ | |
ret.push(String.fromCharCode(i)); | |
} | |
for(i = 65; i <= 90; i += 1){ | |
ret.push(String.fromCharCode(i)); | |
} | |
for(i = 97; i <= 122; i += 1){ | |
ret.push(String.fromCharCode(i)); | |
} | |
break; | |
case "ascii": | |
for(i = 33; i <= 126; i += 1){ | |
ret.push(String.fromCharCode(i)); | |
} | |
break; | |
default: | |
break; | |
} | |
return ret; | |
}, | |
echo = function(str){ | |
return process.stdout.write(str + "\n"); | |
}, | |
exit = process.exit, | |
argv = process.argv.slice(1), | |
argc = argv.length - 1; | |
(function(){ | |
var charPool = [], userLength = 0, | |
ret = []; | |
if(argc !== 2){ | |
echo("Usage: "+ argv[0] +" length {lower|mixed|ascii}"); | |
exit(1); | |
} | |
if(isNaN(userLength = parseInt(argv[1], 10))){ | |
echo("Invalid length \u001b[1m" + argv[1] + "\u001b[0m."); | |
exit(1); | |
} | |
if(argv[2] !== "lower" && argv[2] !== "mixed" && argv[2] !== "ascii"){ | |
echo("Unknown type \u001b[1m" + argv[2] + "\u001b[0m."); | |
exit(1); | |
} | |
charPool = createCharPool(argv[2]); | |
(function(){ | |
var i = userLength; | |
for(i; i > 0; i -= 1){ | |
ret.push(charPool[Math.floor(getUrandomInt8() * charPool.length / 256)]); | |
} | |
})(); | |
echo(ret.join("")); | |
return; | |
})(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment