How to generate unique ID with node.js

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


        
14条回答
  •  旧巷少年郎
    2020-12-12 11:01

    Install NPM uuid package (sources: https://github.com/kelektiv/node-uuid):

    npm install uuid
    

    and use it in your code:

    var uuid = require('uuid');
    

    Then create some ids ...

    // Generate a v1 (time-based) id
    uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
    
    // Generate a v4 (random) id
    uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
    

    ** UPDATE 3.1.0
    The above usage is deprecated, so use this package like this:

    const uuidv1 = require('uuid/v1');
    uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 
    
    const uuidv4 = require('uuid/v4');
    uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 
    

    ** UPDATE 7.x
    And now the above usage is deprecated as well, so use this package like this:

    const { v1: uuidv1 } = require('uuid');
    uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 
    
    const { v4: uuidv4 } = require('uuid');
    uuidv4(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 
    

提交回复
热议问题