How to generate unique ID with node.js

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


        
14条回答
  •  挽巷
    挽巷 (楼主)
    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"
    

提交回复
热议问题