How to generate unique ID with node.js

前端 未结 14 1892
感动是毒
感动是毒 2020-12-12 10:17
function generate(count) {
    var founded = false,
        _sym = \'abcdefghijklmnopqrstuvwxyz1234567890\',
        str = \'\';
    while(!founded) {
        for(va         


        
14条回答
  •  醉话见心
    2020-12-12 11:10

    Another approach is using the shortid package from npm.

    It is very easy to use:

    var shortid = require('shortid');
    console.log(shortid.generate()); // e.g. S1cudXAF
    

    and has some compelling features:

    ShortId creates amazingly short non-sequential url-friendly unique ids. Perfect for url shorteners, MongoDB and Redis ids, and any other id users might see.

    • By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
    • Non-sequential so they are not predictable.
    • Can generate any number of ids without duplicates, even millions per day.
    • Apps can be restarted any number of times without any chance of repeating an id.

提交回复
热议问题