Generating Random Characters
Last Updated: February 6, 2020.
Today’s note is about using Javascript (Node!) to generate a string of random characters.
“The use case for this”, you ask?
Well, let’s assume we need a simple utility to provide reasonably random refs each time it’s called – which doesn’t necessarily have to be a UUID, GUID, or even RFC4122 complaint.
I for one, from time to time, need to do this and there are a few snippets I have lying around my PC for this
Using Node
Using the randomBytes
API of the crypto package which comes bundled with node, we can generate reasonably random characters as thus:
const crypto = require('crypto');
// using an arbitrary byte size of 14
const randomCharBuf = crypto.randomBytes(14);
/* ... */
At this point, randomCharBuf
isn’t the string of random characters we desire, but per the docs, a Buffer.
/* ... */
console.log(randomCharBuf);
// <Buffer 5f 48 b2 7f 7c 17 d3 fc 12 92 ee 60 cc f2>
/* ... */
To convert the buffer to an actual string we can go about making use of, we call the .toString()
method which Buffer instances have on them, passing in a character encoding type to use.
/* ... */
const randomChar = randomCharBuf.toString('hex');
/* ... */
At this point, mission accomplished:
/* ... */
console.log(randomChar);
// 5f48b27f7c17d3fc1292ee60ccf2
Putting It All Together
We can nicely package all of the above into a simple utility function as follows…
function genRandChar() {
const randomCharBuf = require('crypto').randomBytes(14);
const randomChar = randomCharBuf.toString('hex');
return randomChar;
}
… such that to generate a random string we just have to do this …
const ref = genRandChar();
console.log(ref); // f0b975b2279d07ac8d59d7da08b0
Using the “uuidgen” CLI binary
If you make use of a Mac, simply opening a terminal session and typing uuidgen
should do the job:
If you are on Linux, you can check if you have a corresponding library installed on your machine:
which uuid
or
which uuidgen
If not found, you can install the uuid tool from your preferred package manager. For Ubuntu (for example):
sudo apt install uuid
That’s it for today, folks!