function generate(count) {
    var founded = false,
        _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
        str = '';
    while(!founded) {
        for(var i = 0; i < count; i++) {
            str += _sym[parseInt(Math.random() * (_sym.length))];
        }
        base.getID(string, function(err, res) {
            if(!res.length) {
                founded = true; // How to do it?
            }
        });
    }
    return str;
}

如何设置一个变量值与数据库查询回调?我该怎么做呢?


当前回答

在Node中创建随机32字符字符串的最快方法是使用本地crypto模块:

const crypto = require("crypto");

const id = crypto.randomBytes(16).toString("hex");

console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e

其他回答

从14.17.0开始,你现在可以使用内置的加密模块来生成uuid (UUIDv4 flavour):

const { randomUUID } = require('crypto'); // Added in: node v14.17.0

console.log(randomUUID());

// '89rct5ac2-8493-49b0-95d8-de843d90e6ca'

你可以探索更多 https://nodejs.org/api/crypto.html#crypto_crypto_randomuuid_options

注意:密码。randomUUID比uuid快三倍。而且不需要增加额外的依赖。

在Node中创建随机32字符字符串的最快方法是使用本地crypto模块:

const crypto = require("crypto");

const id = crypto.randomBytes(16).toString("hex");

console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e

从YaroslavGaponov的答案延伸出来,最简单的实现就是使用Math.random()。

Math.random()

从数学上讲,分数在实空间[0,1]中相同的概率理论上为0。在node.js中,它的默认长度为16个小数,概率接近于0。这种实现还应该减少算术溢出,因为不执行任何操作。此外,与字符串相比,它的内存效率更高,因为小数占用的内存比字符串少。

我称之为“分数-唯一id”。

编写代码生成1,000,000个Math.random()数字,但无法找到任何重复的数字(至少对于默认的小数点为16)。参见下面的代码(如果有请提供反馈):

random_numbers = [] 
for (i = 0; i < 1000000; i++) { 
   random_numbers.push(Math.random()); 
   //random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16 
} 

if (i === 1000000) { 
   console.log("Before checking duplicate"); 
   console.log(random_numbers.length); 
   console.log("After checking duplicate"); 
   random_set = new Set(random_numbers); // Set removes duplicates
   console.log([...random_set].length); // length is still the same after removing
} 

这里的解决方案是旧的,现在已弃用:https://github.com/uuidjs/uuid#deep-requires-now-deprecated

用这个:

NPM安装uuid

//add these lines to your code
const { v4: uuidv4 } = require('uuid');
var your_uuid = uuidv4();
console.log(your_uuid);

编辑:shortid已弃用。维护者建议使用纳米体代替。


另一种方法是使用npm中的shortid包。

它非常容易使用:

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

它有一些引人注目的特点:

ShortId创建惊人的短非顺序url友好的唯一 id。完美的url缩短器,MongoDB和Redis id,和任何其他 用户可能看到的Id。 默认7-14个url友好字符:A-Z, A-Z, 0-9, _- 非连续的,所以它们是不可预测的。 可以生成任意数量的id而不重复,甚至每天数百万。 应用程序可以重新启动任意次数,没有任何重复id的机会。