Nodejs generate short unique alphanumeric

前端 未结 6 641
借酒劲吻你
借酒劲吻你 2021-01-30 23:55

I would like to generate a short unique alphanumeric value to be used as confirmation codes for online purchases. I\'ve looking into https://github.com/broofa/node-uuid but the

6条回答
  •  一生所求
    2021-01-31 00:27

    A little late on this one but it seems like hashids would work pretty well for this scenario.

    https://github.com/ivanakimov/hashids.node.js

    hashids (Hash ID's) creates short, unique, decryptable hashes from unsigned integers

    var Hashids = require('hashids'),
    hashids = new Hashids('this is my salt');
    
    var hash = hashids.encrypt(12345);
    // hash is now 'ryBo'
    
    var numbers = hashids.decrypt('ryBo');
    // numbers is now [ 12345 ]
    

    If you want to target ~ 8 characters you could do, the following that calls for a minimum of 8 chars.

    hashids = new Hashids("this is my salt", 8);
    

    then this:

    hash = hashids.encrypt(1);
    // hash is now 'b9iLXiAa'
    

    The accepted answer would be predictable/guessable, this solution should be unique and unpredictable.

提交回复
热议问题