首页 > 解决方案 > 生成 18 位唯一编号

问题描述

我想在我的 NodeJS 应用程序中创建一个生成唯一 18 位数字的函数。我期待的是获得唯一的 18 位数字,如下所示:

73306495056092753667  

我想通过将 Date.now() 与 Math.random() 结合使用以下逻辑:

Date.now()+""+Math.floor(Math.random()*10000000)  

但是在我的函数在同一毫秒被调用的情况下,如果在相同的情况下,Math.random() 返回相同的值,上述逻辑将不会返回唯一 ID。

在 NodeJS/Javascript 中,是否有像 UUID 这样生成全局唯一数值的模块?或者任何人都可以帮助我创建一个生成唯一 ID 的算法吗?

标签: javascript

解决方案


这是使用nanoid ( npm install -S nanoid) 的解决方案:

const { customAlphabet } = require('nanoid')
const nanoid = customAlphabet('1234567890', 18)
console.log(nanoid()) // sample outputs => 455712511712968405, 753952709650782495

推荐阅读