Quick Tip: Use Node to Create Random Strings

Quick Tip: Use Node to Create Random Strings

·

2 min read

Generate random string with Node

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’).

node
Welcome to Node.js v20.4.0.
Type ".help" for more information.
> require('node:crypto').randomBytes(8).toString('hex')
'568b6620639fdf54'

If you want to generate a random string without even going into the REPL, you could use the following:

node -e “console.log(require(‘node:crypto’).randomBytes(8).toString(‘hex’))”

On a Mac, you can even add | pbcopy to the command to have the string copy right to your clipboard.

node -e “console.log(require(‘node:crypto’).randomBytes(8).toString(‘hex’))” | pbcopy

Just remember, when using the command from the terminal or REPL, the length passed to randomBytes will be half the length of what is outputted. So if you need a random string of 8 characters, pass 4 as the length.

I hope this quick tip was helpful. Let me know if the comments if you’ve seen any optimizations to the code above or if there’s an easier way to generate random strings.

Thanks for reading!

Did you find this article valuable?

Support Sean Kegel by becoming a sponsor. Any amount is appreciated!