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
The result will change each time you re-execute the code due to the randomness. It is possible for you to get the same result 2 times in a row, but the probability is extremely small.
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:
import crypto from 'crypto';
// If you are using CommonJS, you can use the following "require"
// 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 your output will be different from mine.
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:
import randomstring from 'randomstring';
// CommonJS syntax:
// 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:
- Top 4 best Node.js Open Source Headless CMS
- Node.js: Using __dirname and __filename with ES Modules
- Node.js: Reading and Parsing Excel (XLSX) Files
- Express + TypeScript: Extending Request and Response objects
- Node + Mongoose + TypeScript: Defining Schemas and Models
You can also check out our Node.js category page for the latest tutorials and examples.