Nodejs生成短的唯一字母数字

我想生成一个简短的独特的字母数字值作为在线购买的确认代码。 我正在寻findhttps://github.com/broofa/node-uuid,但他们的uuids太长,我想要他们约8个字符长。 我能达到这个目标的最好方法是什么?

15/23/15:下面也看到哈希答案!

你可以借用URL缩短模型,并做这样的事情:

(100000000000).toString(36); // produces 19xtf1ts (200000000000).toString(36); // produces 2jvmu3nk 

只需增加数字以保持其独特性:

 function(uniqueIndex) { return uniqueIndex.toString(36); } 

请注意 ,这对于“单一实例”服务是非常有用的,这些服务并不介意按照这种顺序(通过基本增量)进行一定程度的可预测性。 如果您需要跨越多个应用程序/数据库实例的真正独特的价值,您应该考虑每个评论的更全面的function选项。

有一点晚了,但这似乎像哈希会在这种情况下工作得很好。

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

散列(哈希ID)创build从无符号整数短,唯一,可解密的散列

 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 ] 

如果你想要定位8个字符,那么至less需要8个字符。

 hashids = new Hashids("this is my salt", 8); 

那么这个:

 hash = hashids.encrypt(1); // hash is now 'b9iLXiAa' 

被接受的答案是可预测的/可猜测的,这个解决scheme应该是独特和不可预测的。

安装shortId模块( https://www.npmjs.com/package/shortid )。 默认情况下,shortid会生成7-14个url友好字符:AZ,az,0-9,_-,但是如果您愿意,可以用其他字符replace – 和_。 现在,您需要以某种方式将这个shortId粘贴到您的对象中,并保存到数据库中。 最好的方法是像这样将它们粘在Schema中:

 var shortId = require('shortid'); var PurchaseConfirmationSchema = mongoose.Schema({ /* _id will be added automatically by mongoose */ shortId: {type: String, unique: true, default: shortId.generate}, /* WE SHOULD ADD THIS */ name: {type: String}, address: {type: String} }); 

我在这里已经给自己回答了类似的问题:

缩短node.js和mongoose中的ObjectId

为此,我写了一个可以做到这一点的模块。 看看它的页面: id-short

如果每个在线购买都与Unique URL相关联,则可以使用不需要数据库连接的简单包的后端,也不需要Web服务:

 var shorten=require('simple-short'); shorten.conf({length:8}); // Default is 4. code1=shorten('http://store.com/purchase1'); code2=shorten('http://store.com/purchase2'); //.. so on