Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random 32 Bit Number in Node

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.

like image 327
fvrghl Avatar asked Jan 21 '15 06:01

fvrghl


Video Answer


1 Answers

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));
  }
}
like image 184
mscdex Avatar answered Nov 14 '22 23:11

mscdex