I am trying to make an random password generator in node.js but it does not work.
function betterRandom(min, max) {
if (max == null){ //checks if there in no max
max = min;
min = 0;
}
return Math.round((Math.random() * (max - min) + min));
}
function randomPassword(length) {
let chars = [
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
['a','b','c','d','e','f','g','h','i','j'],
['k','l','m','n','o','p','q','r','s','t'],
['u','v','w','x','y','z','A','B','C','D'],
['E','F','G','H','I','J','K','L','M','N'],
['O','P','Q','R','S','T','U','V','W','X'],
['Y','Z','!','@','#','$','%','?','=',';']];
let result = "";
for (let i = 0; i < length; i++) {
let x = betterRandom(0, 9);
let y = betterRandom(0, 6);
console.log(`${x}, ${y}`);
result += chars [x][y]; //adds random character from chars to results
result += ' ';
console.log(chars[x] [y]);
}
console.log(result);
}
randomPassword(5);
I tried to fix it and it didn’t work and I thought it would spit out at the end a random password if a specified length is passed.
4
Answers
It looks like there’s a small issue in your ‘betterRandom’ function. It should use ‘Math.floor’ instead of ‘Math.round’
If you don’t want space between generated password then remove this line of code.
result += ' ';
Your code is working,check it.
You just need to change this two lines ,
change
result += chars [x][y]
into
result += chars [y][x]
EDIT: also change the console.log line to :
console.log(chars[y][x]);
and it should work 😉
Your methodology is overly complex and slightly flawed.
Assuming you want to allow any ascii character, that integer range is [ 33, 126 ]:
Then using the randomInt() function in the native crypto module you can easily accomplish what you’re trying to do:
Prints: