To generate a random number in a specific range, you can use the following equation
Math.random() * (high - low) + low
But you want to use crypto.randomBytes instead of Math.random (), this function returns a buffer with randomly generated bytes. In turn, you need to convert the result of this function from bytes to decimal. this can be done using the biguint-format package. To install this package, simply use the following command:
npm install biguint-format
Now you need to convert the result of crypto.randomBytes to decimal, you can do it like this:
var x= crypto.randomBytes(1); return format(x, 'dec');
Now you can create your random function, which will be as follows:
var crypto = require('crypto'), format = require('biguint-format'); function randomC (qty) { var x= crypto.randomBytes(qty); return format(x, 'dec'); } function random (low, high) { return randomC(4)/Math.pow(2,4*8-1) * (high - low) + low; } console.log(random(50,1000));
source share