I want to generate a unique number everytime. I have used crypto module for that.
const alphanu = crypto.randomBytes(16).toString('hex')
This will generate alphanumeric string of length 32. I want to generate a number of length 8.
I tried randomInt as well.
const num = crypto.randomInt(10000000,99999999)
Will it always generate a unique number?
How do I achieve what I want?
Your "unique" requirement will be harder to achieve than you think. If you meant "non-deterministic", then just use crypto.randomInt()
as you did in your question:
crypto.randomInt(10**7, 10**8-1) // 8 digit, no leading zeroes
crypto.randomInt(0, 10**8-1).toString().padStart(8, "0") // 8 digits, allows leading zeroes
Technically speaking, this is psuedorandom, not random. However, for most use cases, you won't be able to tell the difference.
Now if you need unique, then here's two fairly easy approaches you could use:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With