How to easily generate a random string in Node.js

June 18, 2020 Ken Fisher Loading... Post a comment

This article introduces to you an easy way to 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.
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles

0
Would love your thoughts, please comment.x
()
x