如何使用node.js生成唯一ID

JavaScript Node.js

米亚阿飞米亚

2020-03-26

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;
}

如何使用数据库查询回调设置变量值?我该怎么办?

第3784篇《如何使用node.js生成唯一ID》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
2020.03.26

简单,基于时间,没有依赖关系:

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

输出: jzlatihl


加上随机数(感谢@Yaroslav Gaponov的回答)

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

输出量 jzlavejjperpituute

宝儿理查德 2020.03.26

更简单,无需添加模块

Math.random().toString(26).slice(2)
斯丁前端 2020.03.26

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

const crypto = require("crypto");

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

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android