我想在我的 NodeJS 应用程序中创建一个函数来生成唯一的 18 位数字。我期望得到如下所示的唯一 18 位数字:
73306495056092753667
Run Code Online (Sandbox Code Playgroud)
我考虑使用以下逻辑,将 Date.now() 与 Math.random() 结合起来:
Date.now()+""+Math.floor(Math.random()*10000000)
Run Code Online (Sandbox Code Playgroud)
但是,如果我的函数在同一毫秒被调用,并且在相同的情况下,Math.random() 返回相同的值,则上述逻辑将不会返回唯一的 ID。
在NodeJS/Javascript中,是否有像UUID这样的模块可以生成全局唯一的数值?或者有人可以帮我创建一个可以生成唯一 ID 的算法吗?
Tib*_*. M 12
这是使用nanoid ( )的解决方案npm install -S nanoid:
const { customAlphabet } = require('nanoid')
const nanoid = customAlphabet('1234567890', 18)
console.log(nanoid()) // sample outputs => 455712511712968405, 753952709650782495
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7660 次 |
| 最近记录: |