3 Ways to Generate Random Strings in Node.js

Last updated on November 24, 2021 The Plumber Loading... Post a comment

This article walks you through 3 different ways to generate a random string in Node.js. The first two approaches only use self-written code and utilize the built-in functionality of Node.js. The last approach introduces to you some popular third-party packages that can help you get the job done quickly. Without any further ado, let’s dive right in.

Creating a random string with a given length

The example below will generate a random string with a given length. The result will only contain alphabet letters and numbers (a-z, A-Z, 0-9) but you can modify the chars variable as needed.

The code:

// Create a function for reusable perpose
const generateRandomString = (myLength) => {
  const chars =
    "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
  const randomArray = Array.from(
    { length: myLength },
    (v, k) => chars[Math.floor(Math.random() * chars.length)]
  );

  const randomString = randomArray.join("");
  return randomString;
};

// Try it
console.log(generateRandomString(10));
console.log(generateRandomString(30));

Output:

VPf0yHROkh
LAbYAVKvcE2AVAEh839MDud10xMngy

Using the standard Crypto module

Example

The example below demonstrates how to easily generate random strings in Node.js using the randomBytes API provided by the crypto module (a built-in module and no installation required).

The code:

const crypto = require('crypto');

const randomString1 = crypto.randomBytes(4).toString('hex');
console.log(randomString1);

const randomString2 = crypto.randomBytes(8).toString('hex');
console.log(randomString2);

const randomString3 = crypto.randomBytes(16).toString('hex');
console.log(randomString3);

// 4, 8, 16 indicate the numbers of bytes 

The output will look like this:

fea48baa
9c6fcbdd66bd37da
081779ade290e2ab78ffcb8372177a41

Keep in mind that the output contains random strings, so it will be different each time you execute your code.

More about crypto.randomBytes

Check out the official docs here.

The randomBytes method generates cryptographically strong pseudo-random data.

Syntax:

crypto.randomBytes( size, callback )

Parameters:

  • size (number, required): Indicates the number of bytes to be generated.
  • callback (optional): The callback function.

Using a 3rd library

There are so many good open-source libraries that can help us get the task done, such as unique-string, crypto-random-string, nanoid, randomstring, etc. The example below will use randomstring.

Install:

npm i randomstring

Example:

const randomstring = require("randomstring");

randomstring.generate();
// "XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT"

randomstring.generate(7);
// "xqm5wXX"

randomstring.generate({
  length: 12,
  charset: 'alphabetic'
});
// "AqoTIzKurxJi"

randomstring.generate({
  charset: 'abc'
});

// "accbaabbbbcccbccccaacacbbcbbcbbc"

Conclusion

You’ve learned a few techniques to produce random strings in Node.js. Choose from them the one that fits your need. If you’d like to explore new and awesome things about modern Node.js, take a look at the following articles:

You can also check out our Node.js category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles