How to generate unique ID with node.js

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


        
相关标签:
14条回答
  • 2020-12-12 10:44

    nanoid does exactly what you want.

    Example usage:

    const { nanoid } = require("nanoid")
    
    console.log(nanoid())
    //=> "n340M4XJjATNzrEl5Qvsh"
    
    0 讨论(0)
  • 2020-12-12 10:49

    Simple, time based, without dependencies:

    (new Date()).getTime().toString(36)
    

    Output: jzlatihl


    plus random number (Thanks to @Yaroslav Gaponov's answer)

    (new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)
    

    Output jzlavejjperpituute

    0 讨论(0)
  • 2020-12-12 10:50

    The solutions here are old and now deprecated: https://github.com/uuidjs/uuid#deep-requires-now-deprecated

    Use this:

    npm install uuid

    //add these lines to your code
    const { v4: uuidv4 } = require('uuid');
    var your_uuid = uuidv4();
    console.log(your_uuid);
    
    0 讨论(0)
  • 2020-12-12 10:55

    It's been some time since I used node.js, but I think I might be able to help.

    Firstly, in node, you only have a single thread and are supposed to use callbacks. What will happen with your code, is that base.getID query will get queued up by for execution, but the while loop will continusouly run as a busy loop pointlessly.

    You should be able to solve your issue with a callback as follows:

    function generate(count, k) {
        var _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
        var str = '';
    
        for(var i = 0; i < count; i++) {
            str += _sym[parseInt(Math.random() * (_sym.length))];
        }
        base.getID(str, function(err, res) {
            if(!res.length) {
              k(str)                   // use the continuation
            } else generate(count, k)  // otherwise, recurse on generate
        });
    }
    

    And use it as such

    generate(10, function(uniqueId){
      // have a uniqueId
    })
    

    I haven't coded any node/js in around 2 years and haven't tested this, but the basic idea should hold – don't use a busy loop, and use callbacks. You might want to have a look at the node async package.

    0 讨论(0)
  • 2020-12-12 10:58

    If some one needs cryptographic-strong UUID, there is solution for that as well.

    https://www.npmjs.com/package/generate-safe-id

    npm install generate-safe-id
    

    Why not UUIDs?

    Random UUIDs (UUIDv4) do not have enough entropy to be universally unique (ironic, eh?). Random UUIDs have only 122 bits of entropy, which suggests that a duplicate will occur after only 2^61 IDs. Additionally, some UUIDv4 implementations do not use a cryptographically strong random number generator.

    This library generates 240-bit IDs using the Node.js crypto RNG, suggesting the first duplicate will occur after generating 2^120 IDs. Based on the current energy production of the human race, this threshold will be impossible to cross for the foreseeable future.

    var generateSafeId = require('generate-safe-id');
    
    var id = generateSafeId();
    // id == "zVPkWyvgRW-7pSk0iRzEhdnPcnWfMRi-ZcaPxrHA"
    
    0 讨论(0)
  • 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' 
    
    0 讨论(0)
提交回复
热议问题