DEV Community

Cover image for Quick Tip: Use Node to Create Random Strings
Sean Kegel
Sean Kegel

Posted on • Originally published at seankegel.com on

Quick Tip: Use Node to Create Random Strings

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"
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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’))
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)