-
Notifications
You must be signed in to change notification settings - Fork 6
生成不重复的随机字符串 #19
Copy link
Copy link
Closed
Labels
Back-endWhere data really come and goWhere data really come and goFront-endEverything you see and experienceEverything you see and experienceJSJavascriptJavascript
Metadata
Metadata
Assignees
Labels
Back-endWhere data really come and goWhere data really come and goFront-endEverything you see and experienceEverything you see and experienceJSJavascriptJavascript
需求描述
业务上的一个需求,要批量生成不重复的随机字符串。
方案调研
调研过程
先尝试 Google
js generate many random strings,第一条结果就是 Stack Overflow 的,点进去看看:Generate random string/characters in JavaScript
回答里面,有说用
Math.random()方法的,有说用 Node.js 的crypto这个库的,还有说用uuid之类的库的。看了这篇问答拿不定主意,于是再 Google
node crypto randombytes duplicate,第一条结果是 node-hat 的 issue,里面有个高分回答也建议用 Node.js 的crypto这个库中的randomBytes方法。在 Google 出来的第二条结果 Secure random values (in Node.js) 中,也是既有人推荐用 Node.js 的
crypto这个库(更加原生),也有人推荐用uuid之类的库(更能确保唯一性,但其实没啥区别)。几个链接看下来,最后自己的结论就是:Node.js 的
crypto,和uuid这类的库都可以满足自己的需求。另外,uuid 这个库只能以一种固定格式
1c572360-faca-11e7-83ee-9d836d45ff41生成随机字符串,而 nanoid 这个库则可以自定义所生成的字符串的长度,可以自定义字符串中包含哪些字符,在自定义性上更胜一筹。入选方案
排除方案
1c572360-faca-11e7-83ee-9d836d45ff41生成随机字符串。应用过程
略。
要点总结
重要的事情有三点:
最后还是想说,GitHub 真是个宝库啊。