Quick Tip: Use Node to Create Random Strings

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?

Using Node.js, this can be a lot simpler. You just need to use the crypto library which is built-in.

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"

A few issues with this is the length passed to the randomBytes 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.

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 node to go into the REPL, then add require(‘node:crypto’).randomBytes(8).toString(‘hex’).

Visit Now

Tags: Node Strings