Node.js中的Crypto.randomInt方法是加密模塊的內置應用程序編程接口,用於根據我們的用法同步或異步創建隨機整數。
用法:
crypto.randomInt([min, ] max [, callback])
參數:該方法接受上述和以下所述的三個參數。
- min:生成隨機int的可選最小值(包括)。默認值:0
 - max:生成隨機int所需的最大值(不包括)。
 - callback:可選的回調函數,將在生成隨機整數後執行。如果指定了callback,則默認情況下該方法異步運行,否則同步。
 
返回值:Crypto.randomInt方法返回一個隨機整數n,使得min <= n <max。
注意:範圍(最大值-最小值)必須小於248&最小值,最大值必須為安全整數。
以下示例說明了Node.js中crypto.randomInt方法的使用。
範例1:同步
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));輸出:

範例2:異步
Javascript
const crypto = require("crypto"); 
  
// Asynchronous 
crypto.randomInt(50, (err, result) => { 
  if (err) console.log("Some error occured 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 occured while "+ 
                       "generating random integer !"); 
  else console.log("Random integer in range 20-50:", result); 
});輸出:

參考: https://nodejs.org/api/crypto.html#crypto_crypto_randomint_min_max_callback
相關用法
- Node.js console.timeLog()用法及代碼示例
 - Node.js fs.fsyncSync()用法及代碼示例
 - Node.js process.nextTick()用法及代碼示例
 - Node.js GM charcoal()用法及代碼示例
 - Node.js GM blur()用法及代碼示例
 - Node.js GM sharpen()用法及代碼示例
 - Node.js GM drawLine()用法及代碼示例
 - Node.js GM drawArc()用法及代碼示例
 - Node.js GM drawPolyline()用法及代碼示例
 - Node.js GM drawBezier()用法及代碼示例
 - Node.js GM drawCircle()用法及代碼示例
 
注:本文由純淨天空篩選整理自omkarphansopkar大神的英文原創作品 Node.js crypto.randomInt() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
