Javascript random characters

Posted by Joe Enos on August 04, 2021 · 1 min read
// Asynchronous
const crypto = require('crypto');


function getRandomChars(len, callback) {
const CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const NUM_CHARS = CHARS.length;
crypto.randomBytes(len, (err, buf) => {
let result = "";
buf.forEach(b => {
let idx = Math.floor(b * NUM_CHARS / 256);
result += CHARS[idx];
});
callback(null, result);
});
}