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&nbsp;<code>crypto</code>&nbsp;library which is built-in.</p> <pre> const { randomBytes } = require(&ldquo;node:crypto&rdquo;); function randomString(length) { if (length % 2 !== 0) { length++; } return randomBytes(length / 2).toString(&quot;hex&quot;); } const string = randomString(8); // string = &quot;df5ec630&quot;</pre> <p>A few issues with this is the length passed to the&nbsp;<code>randomBytes</code>&nbsp;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&nbsp;<code>node</code>&nbsp;to go into the REPL, then add&nbsp;<code>require(&lsquo;node:crypto&rsquo;).randomBytes(8).toString(&lsquo;hex&rsquo;)</code>.</p> <p><a href="https://skegel.medium.com/quick-tip-use-node-to-create-random-strings-c1b7ba0937a4">Visit Now</a></p>
Tags: Strings Node