import crypto from 'node:crypto';
/**
* Generates a random 8-digit integer between 10,000,000 and 99,999,999 (inclusive).
* Guaranteed to start with a non-zero digit (1-9).
*
* @returns {number} An 8-digit positive integer.
*/
export function generate8DigitNumber() {
const min = 10_000_000;
const maxExclusive = 100_000_000; // crypto.randomInt(min, max) excludes the max bound
// crypto.randomInt guarantees a uniform distribution using OS entropy
return crypto.randomInt(min, maxExclusive);
}
/**
* Generates an 8-character numeric string code between "00000000" and "99999999".
* Preserves leading zeros, making it suitable for OTPs, PINs, or verification tokens.
*
* @returns {string} An 8-character numeric string padded with leading zeros if needed.
*/
export function generate8DigitCode() {
// Generate a random integer in range [0, 99999999]
const rawValue = crypto.randomInt(0, 100_000_000);
// Pad short integers with leading zeros to guarantee exact 8-character length
return String(rawValue).padStart(8, '0');
}
// ==========================================
// Example Execution & Usage
// ==========================================
function main() {
try {
// 1. Generate an 8-digit mathematical integer [10000000 to 99999999]
const randomNumber = generate8DigitNumber();
console.log(`Generated 8-digit integer: ${randomNumber}`);
// 2. Generate an 8-character string code [00000000 to 99999999] preserving leading zeros
const randomCode = generate8DigitCode();
console.log(`Generated 8-digit OTP/PIN code: ${randomCode}`);
} catch (error) {
console.error('Failed to generate random value:', error);
}
}
// Run the script directly if executed as the main module
main();
/*
run:
Generated 8-digit integer: 43933748
Generated 8-digit OTP/PIN code: 00007931
*/