Reputation: 3728
What is the best way to generate a 32 bit random unsigned number in Node? Here is what I tried:
var max32 = Math.pow(2, 32) - 1
var session = Math.floor(Math.random() * max32);
I need this for a unique id.
Upvotes: 6
Views: 10505
Reputation: 106696
You could use crypto.randomBytes()
like:
var crypto = require('crypto');
function randU32Sync() {
return crypto.randomBytes(4).readUInt32BE(0, true);
}
// or
function randU32(cb) {
return crypto.randomBytes(4, function(err, buf) {
if (err) return cb(err);
cb(null, buf.readUInt32BE(0, true));
}
}
Upvotes: 12