Open In App

Node.js crypto.randomInt() Method

Last Updated : 08 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Crypto.randomInt method in Node.js is an inbuilt application programming interface of the crypto module which is used to create a random integer synchronously or asynchronously based on our usage.

Syntax:

crypto.randomInt([min, ] max [, callback])

Parameters: This method accepts three parameters as mentioned above and described below.

  • min: An optional minimum value (included) for random int to be generated. Default: 0
  • max: A required maximum value (excluded) for random int to be generated.
  • callback: An optional callback function which gets executed after a random integer is generated. If callback is specified, method works asynchronously otherwise synchronously by default.

Return Value: The Crypto.randomInt method returns a random integer n, such that min <= n < max.

Note: The range (max – min) must be less than 248 & min and max must be safe integers.

Below examples illustrate the use of crypto.randomInt method in Node.js .

Example 1: Synchronous 

Javascript




const crypto = require("crypto");
 
// Only max value provided
console.log("Random integers less than 50:");
console.log(crypto.randomInt(50));
console.log(crypto.randomInt(50));
console.log(crypto.randomInt(50));
console.log();
 
// Min value also provided
console.log("Random integers in range 30-50:");
console.log(crypto.randomInt(30, 50));
console.log(crypto.randomInt(30, 50));
console.log(crypto.randomInt(30, 50));


Output:

  

Example 2: Asynchronous 

Javascript




const crypto = require("crypto");
 
// Asynchronous
crypto.randomInt(50, (err, result) => {
  if (err) console.log("Some error occurred while"+
                       " generating random integer !");
  else console.log("Random integer with max limit 50:", result);
});
 
// Asynchronous with both min & max
crypto.randomInt(20, 50, (err, result) => {
  if (err) console.log("Some error occurred while "+
                       "generating random integer !");
  else console.log("Random integer in range 20-50:", result);
});


Output :

 

Reference : https://nodejs.org/api/crypto.html#crypto_crypto_randomint_min_max_callback



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads