crypto.randomInt([min, ]max[, callback])
min<integer> 随机范围的起始值(包含)。默认值:0。max<integer> 随机范围的结束值(不包含)。callback<Function>function(err, n) {}。
返回一个随机整数 n,使得 min <= n < max。此实现避免了 模运算偏差。
【Return a random integer n such that min <= n < max. This
implementation avoids modulo bias.】
范围(max - min)必须小于 248。min 和 max 必须是 安全整数。
如果未提供 callback 函数,将同步生成随机整数。
【If the callback function is not provided, the random integer is
generated synchronously.】
// Asynchronous
const {
randomInt,
} = await import('node:crypto');
randomInt(3, (err, n) => {
if (err) throw err;
console.log(`Random number chosen from (0, 1, 2): ${n}`);
});// Asynchronous
const {
randomInt,
} = require('node:crypto');
randomInt(3, (err, n) => {
if (err) throw err;
console.log(`Random number chosen from (0, 1, 2): ${n}`);
});// Synchronous
const {
randomInt,
} = await import('node:crypto');
const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);// Synchronous
const {
randomInt,
} = require('node:crypto');
const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);// With `min` argument
const {
randomInt,
} = await import('node:crypto');
const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);// With `min` argument
const {
randomInt,
} = require('node:crypto');
const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);