javascript - 生成 18 位唯一编号
问题描述
我想在我的 NodeJS 应用程序中创建一个生成唯一 18 位数字的函数。我期待的是获得唯一的 18 位数字,如下所示:
73306495056092753667
我想通过将 Date.now() 与 Math.random() 结合使用以下逻辑:
Date.now()+""+Math.floor(Math.random()*10000000)
但是在我的函数在同一毫秒被调用的情况下,如果在相同的情况下,Math.random() 返回相同的值,上述逻辑将不会返回唯一 ID。
在 NodeJS/Javascript 中,是否有像 UUID 这样生成全局唯一数值的模块?或者任何人都可以帮助我创建一个生成唯一 ID 的算法吗?
解决方案
这是使用nanoid ( npm install -S nanoid
) 的解决方案:
const { customAlphabet } = require('nanoid')
const nanoid = customAlphabet('1234567890', 18)
console.log(nanoid()) // sample outputs => 455712511712968405, 753952709650782495
推荐阅读
- python - Seaborn lmplot 的子图
- python - 从辅助屏幕启动时,Tkinter 窗口跳转到主屏幕
- java - 如何从广播接收器更新小部件的 TextViewText?
- python - 如何使用基于 JWT 令牌的授权保护 fastapi API 端点?
- scala - 如何在流 Akka Streams 中重用相同的 flowShape
- c# - AWS KMS GenerateDataKeyPairAsync 如何使用生成的密钥?
- tensorflow - 将具有多维输出的 tf.data 数据集馈送到 Keras 模型
- ios - 为什么在多线程环境下修改可变对象会导致EXC_BAD_ACCESS?
- node.js - 附加 scss 的 Express JS pug 文件将样式显示为电子邮件中的文本
- python - 如何在通过 exec() 创建的函数中使用变量?