7

I am creating an app where I sometimes need to allow user to generate some random strings. I would like to force that to be generated in the following format:

xxxx-xxxx-xxxx

Where "x" is some number [0-9] or character [A-Z]. What would the most efficient way to do this? When generated, I would also need to check does it already exist in database so I am a little bit worried about the time which it would take.

user4386126
  • 1,205
  • 5
  • 17
  • 32

2 Answers2

19

We can make it so simple like

require("crypto").randomBytes(64).toString('hex')
yasarui
  • 6,209
  • 8
  • 41
  • 75
17

You can use crypto library.

var crypto = require('crypto');

//function code taken from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript
function randomValueHex (len) {
    return crypto.randomBytes(Math.ceil(len/2))
        .toString('hex') // convert to hexadecimal format
        .slice(0,len).toUpperCase();   // return required number of characters
}

var string = randomValueHex(4)+"-"+randomValueHex(4)+"-"+randomValueHex(4);
console.log(string);

Check these threads: Generate random string/characters in JavaScript

You can check if the field exists in the database. If it does, just generate a new token. Then check again. The probability of it existing is really low if you don't have large user base. Hence, probability of long loop of checks is low as well.

Community
  • 1
  • 1
Andrew Marin
  • 1,053
  • 1
  • 13
  • 15