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


  • min <integer> 随机范围的开始(包括)。 默认值: 0
  • max <integer> 随机范围的结束(不包括)。
  • callback <Function> function(err, n) {}.

返回随机整数 n,使得 min <= n < max。 这种实现避免了模偏差

范围 (max - min) 必须小于 248minmax 必须是安全整数

如果不提供 callback 函数,则同步生成随机整数。

// 异步的
const {
  randomInt
} = await import('node:crypto');

randomInt(3, (err, n) => {
  if (err) throw err;
  console.log(`Random number chosen from (0, 1, 2): ${n}`);
});// 异步的
const {
  randomInt,
} = require('node:crypto');

randomInt(3, (err, n) => {
  if (err) throw err;
  console.log(`Random number chosen from (0, 1, 2): ${n}`);
});
// 同步的
const {
  randomInt
} = await import('node:crypto');

const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);// 同步的
const {
  randomInt,
} = require('node:crypto');

const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
// 带有 `min` 参数
const {
  randomInt
} = await import('node:crypto');

const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);// 带有 `min` 参数
const {
  randomInt,
} = require('node:crypto');

const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);
  • min <integer> Start of random range (inclusive). Default: 0.
  • max <integer> End of random range (exclusive).
  • callback <Function> function(err, n) {}.

Return a random integer n such that min <= n < max. This implementation avoids modulo bias.

The range (max - min) must be less than 248. min and max must be safe integers.

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}`);