Quick Tip: Use Node to Create Random Strings
<p>How many times have you worked on an application and you needed a random alpha-numeric string? Did you try to provide a list of numbers and characters in a string and pass in a length to randomly generate a string with a loop?</p>
<p>Using Node.js, this can be a lot simpler. You just need to use the <code>crypto</code> library which is built-in.</p>
<pre>
const { randomBytes } = require(“node:crypto”);
function randomString(length) {
if (length % 2 !== 0) {
length++;
}
return randomBytes(length / 2).toString("hex");
}
const string = randomString(8);
// string = "df5ec630"</pre>
<p>A few issues with this is the length passed to the <code>randomBytes</code> method needs to be an even number so it can be divided in half. Otherwise, the string returned will be twice the length of the length passed in. This is why the condition is part of the function.</p>
<p>As a bonus, if you just quickly need a random string to use outside of an application, you can just go into your terminal, type <code>node</code> to go into the REPL, then add <code>require(‘node:crypto’).randomBytes(8).toString(‘hex’)</code>.</p>
<p><a href="https://skegel.medium.com/quick-tip-use-node-to-create-random-strings-c1b7ba0937a4">Visit Now</a></p>