How to generate unique ID with node.js

前端 未结 14 1825
感动是毒
感动是毒 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.
    0 讨论(0)
  • 2020-12-12 11:10

    used https://www.npmjs.com/package/uniqid in npm

    npm i uniqid
    

    It will always create unique id's based on the current time, process and machine name.

    • With the current time the ID's are always unique in a single process.
    • With the Process ID the ID's are unique even if called at the same time from multiple processes.
    • With the MAC Address the ID's are unique even if called at the same time from multiple machines and processes.

    Features:-

    • Very fast
    • Generates unique id's on multiple processes and machines even if called at the same time.
    • Shorter 8 and 12 byte versions with less uniqueness.
    0 讨论(0)
提交回复
热议问题