Nodejs生成短的唯一字母数字

teg*_*ggy 15 javascript node.js

我想生成一个简短的唯一字母数字值,用作在线购买的确认码.我正在研究https://github.com/broofa/node-uuid,但他们的uuids太长了,我想让它们长约8个字符.我能做到这一点的最佳方式是什么?

Jam*_*ore 36

在这个问题上稍晚一点,但看起来像hashids在这种情况下会很好用.

https://github.com/ivanakimov/hashids.node.js

hashids(哈希ID)从无符号整数创建短的,唯一的,可解密的哈希值

var Hashids = require('hashids'),
hashids = new Hashids('this is my salt');

var hash = hashids.encrypt(12345);
// hash is now 'ryBo'

var numbers = hashids.decrypt('ryBo');
// numbers is now [ 12345 ]
Run Code Online (Sandbox Code Playgroud)

如果你想要你可以做的约8个字符,下面要求至少8个字符.

hashids = new Hashids("this is my salt", 8);
Run Code Online (Sandbox Code Playgroud)

这个:

hash = hashids.encrypt(1);
// hash is now 'b9iLXiAa'
Run Code Online (Sandbox Code Playgroud)

接受的答案是可预测/可猜测的,这种解决方案应该是独特且不可预测的.


Wes*_*son 35

2015年10月23日:请参阅下面的hashids答案!

您可以借用URL缩短器模型并执行以下操作:

(100000000000).toString(36);
// produces 19xtf1ts

(200000000000).toString(36);
// produces 2jvmu3nk
Run Code Online (Sandbox Code Playgroud)

只需增加数字即可保持唯一:

function(uniqueIndex) {
    return uniqueIndex.toString(36);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这仅对"单实例"服务非常有用,因为它不介意按此方式排序(通过基本增量)的一定量的可预​​测性.如果您需要在多个应用程序/数据库实例中拥有真正独特的值,那么您应该根据某些注释考虑更全面的选项.

  • @teggy,随机使用有什么意义?`(+ new Date()).toString(36)`应该给你唯一的id. (7认同)
  • 这种方法的唯一缺陷是它不能保证并行环境中的唯一性.两台机器或进程可以同时生成代码,您可能会发生冲突. (6认同)
  • 谢谢你的提示.我最终使用了与你提供的类似的东西:var now = new Date(); Math.floor(Math.random()*10)+ parseInt(now.getTime()).toString(36).toUpperCase() (2认同)