function generate(count) {
var founded = false,
_sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
str = '';
while(!founded) {
for(var i = 0; i < count; i++) {
str += _sym[parseInt(Math.random() * (_sym.length))];
}
base.getID(string, function(err, res) {
if(!res.length) {
founded = true; // How to do it?
}
});
}
return str;
}
如何设置一个变量值与数据库查询回调?我该怎么做呢?
我的5美分:
const crypto = require('crypto');
const generateUuid = () => {
return [4, 2, 2, 2, 6] // or 8-4-4-4-12 in hex
.map(group => crypto.randomBytes(group).toString('hex'))
.join('-');
};
遗憾的是,Pono的字符串缺少连字符,所以它不符合uuid标准,这是我相信大多数人来这里的原因。
> generateUuid();
'143c8862-c212-ccf1-e74e-7c9afa78d871'
> generateUuid();
'4d02d4d6-4c0d-ea6b-849a-208b60bfb62e'
如果有人需要加密强UUID,也有解决方案。
https://www.npmjs.com/package/generate-safe-id
npm install generate-safe-id
Why not UUIDs?
Random UUIDs (UUIDv4) do not have enough entropy to be universally
unique (ironic, eh?). Random UUIDs have only 122 bits of entropy,
which suggests that a duplicate will occur after only 2^61 IDs.
Additionally, some UUIDv4 implementations do not use a
cryptographically strong random number generator.
This library generates 240-bit IDs using the Node.js crypto RNG,
suggesting the first duplicate will occur after generating 2^120 IDs.
Based on the current energy production of the human race, this
threshold will be impossible to cross for the foreseeable future.
var generateSafeId = require('generate-safe-id');
var id = generateSafeId();
// id == "zVPkWyvgRW-7pSk0iRzEhdnPcnWfMRi-ZcaPxrHA"
安装uuid
npm install --save uuid
Uuid被更新,旧的导入
const uuid = require('uuid/v4');
不工作,我们现在应该使用这个导入
const {v4: uuid} = require('uuid');
把它作为一个函数来使用
const createdPlace = {
id: uuid(),
title,
description,
location: coordinates,
address,
creator
};