如何用node.js生成唯一的ID

时间:2022-11-25 13:40:33
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;}

How to set a variable value with database query callback? How I can do it?

如何使用数据库查询回调设置变量值?我怎么做呢?

Thanks in advance.

提前谢谢。

7 个解决方案

#1


9  

It's been some time since I used node.js, but I think I might be able to help.

我使用node已经有一段时间了。我想我能帮上忙。

Firstly, in node, you only have a single thread and are supposed to use callbacks. What will happen with your code, is that base.getID query will get queued up by for execution, but the while loop will continusouly run as a busy loop pointlessly.

首先,在node中,您只有一个线程,应该使用回调。你的代码会发生什么呢?getID查询将排队等待执行,但是while循环将继续作为一个没有意义的繁忙循环运行。

You should be able to solve your issue with a callback as follows:

你应该能够用回叫来解决你的问题:

function generate(count, k) {    var _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',    var str = '';    for(var i = 0; i < count; i++) {        str += _sym[parseInt(Math.random() * (_sym.length))];    }    base.getID(str, function(err, res) {        if(!res.length) {          k(str)                   // use the continuation        } else generate(count, k)  // otherwise, recurse on generate    });}

And use it as such

并以此类推。

generate(10, function(uniqueId){  // have a uniqueId})

I haven't coded any node/js in around 2 years and haven't tested this, but the basic idea should hold – don't use a busy loop, and use callbacks. You might want to have a look at the node async package.

我在大约两年内没有编写任何节点/js,也没有测试过它,但是基本的思想应该是:不要使用繁忙的循环,使用回调。您可能想了解一下node async包。

#2


134  

Use https://github.com/broofa/node-uuid

使用https://github.com/broofa/node-uuid

npm install uuidvar uuid = require('uuid');

Then create some ids ...

然后创建一些id……

// Generate a v1 (time-based) iduuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'// Generate a v4 (random) iduuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

** UPDATE 3.1.0
The above usage is deprecated, so use this package like this:

** *更新3.1.0以上的用法已被弃用,请使用以下包:

const uuidv1 = require('uuid/v1');uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' const uuidv4 = require('uuid/v4');uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

#3


73  

The fastest possible way to create random 32-char string in Node is by using native crypto module:

在节点中创建32字符随机字符串的最快方法是使用本机加密模块:

const crypto = require("crypto");const id = crypto.randomBytes(16).toString("hex");console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e

#4


13  

Another approach is using the shortid package from npm.

另一种方法是使用来自npm的shortid包。

It is very easy to use:

它很容易使用:

var shortid = require('shortid');console.log(shortid.generate()); // e.g. S1cudXAF

and has some compelling features:

并有一些引人注目的特点:

ShortId creates amazingly short non-sequential url-friendly unique ids. Perfect for url shorteners, MongoDB and Redis ids, and any other id users might see.

ShortId创建短得惊人的非连续url友好的唯一id。非常适合url缩写者、MongoDB和Redis id,以及任何其他id用户可能看到的内容。

  • By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
  • 默认情况下,7-14个url友好字符:A-Z、A-Z、0-9、_-
  • Non-sequential so they are not predictable.
  • 非连续的,所以它们是不可预测的。
  • Can generate any number of ids without duplicates, even millions per day.
  • 可以生成任意数量的id而不需要重复,甚至每天可以生成数百万个。
  • Apps can be restarted any number of times without any chance of repeating an id.
  • 应用程序可以重新启动任意次数,而不需要重复任何id。

#5


7  

node-uuid is deprecated so please use uuid

节点uuid已被弃用,因此请使用uuid

npm install uuid --save// Generate a v1 UUID (time-based) const uuidV1 = require('uuid/v1');uuidV1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' // Generate a v4 UUID (random) const uuidV4 = require('uuid/v4');uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

Npm link

Npm链接

#6


3  

More easy and without addition modules

更简单,没有添加模块

Math.random().toString(26).slice(2)

#7


1  

If some one needs cryptographic-strong UUID, there is solution for that as well.

如果有人需要密码强大的UUID,也有解决方案。

https://www.npmjs.com/package/generate-safe-id

https://www.npmjs.com/package/generate-safe-id

npm install generate-safe-id

Why not UUIDs?

为什么不uuid呢?

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.

随机uuid (UUIDv4)没有足够的熵来实现普遍的唯一性(讽刺,是吗?)随机熵的uuid只有122位,这表明重复发生后只有2 ^ 61 id。此外,一些uuuidv4实现不使用加密强随机数生成器。

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.

该库使用节点生成240位id。js加密提高,表明生成后的第一个重复发生2 ^ 120 id。基于人类目前的能量生产,在可预见的未来,这个阈值是不可能跨越的。

var generateSafeId = require('generate-safe-id');var id = generateSafeId();// id == "zVPkWyvgRW-7pSk0iRzEhdnPcnWfMRi-ZcaPxrHA"

#1


9  

It's been some time since I used node.js, but I think I might be able to help.

我使用node已经有一段时间了。我想我能帮上忙。

Firstly, in node, you only have a single thread and are supposed to use callbacks. What will happen with your code, is that base.getID query will get queued up by for execution, but the while loop will continusouly run as a busy loop pointlessly.

首先,在node中,您只有一个线程,应该使用回调。你的代码会发生什么呢?getID查询将排队等待执行,但是while循环将继续作为一个没有意义的繁忙循环运行。

You should be able to solve your issue with a callback as follows:

你应该能够用回叫来解决你的问题:

function generate(count, k) {    var _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',    var str = '';    for(var i = 0; i < count; i++) {        str += _sym[parseInt(Math.random() * (_sym.length))];    }    base.getID(str, function(err, res) {        if(!res.length) {          k(str)                   // use the continuation        } else generate(count, k)  // otherwise, recurse on generate    });}

And use it as such

并以此类推。

generate(10, function(uniqueId){  // have a uniqueId})

I haven't coded any node/js in around 2 years and haven't tested this, but the basic idea should hold – don't use a busy loop, and use callbacks. You might want to have a look at the node async package.

我在大约两年内没有编写任何节点/js,也没有测试过它,但是基本的思想应该是:不要使用繁忙的循环,使用回调。您可能想了解一下node async包。

#2


134  

Use https://github.com/broofa/node-uuid

使用https://github.com/broofa/node-uuid

npm install uuidvar uuid = require('uuid');

Then create some ids ...

然后创建一些id……

// Generate a v1 (time-based) iduuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'// Generate a v4 (random) iduuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

** UPDATE 3.1.0
The above usage is deprecated, so use this package like this:

** *更新3.1.0以上的用法已被弃用,请使用以下包:

const uuidv1 = require('uuid/v1');uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' const uuidv4 = require('uuid/v4');uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

#3


73  

The fastest possible way to create random 32-char string in Node is by using native crypto module:

在节点中创建32字符随机字符串的最快方法是使用本机加密模块:

const crypto = require("crypto");const id = crypto.randomBytes(16).toString("hex");console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e

#4


13  

Another approach is using the shortid package from npm.

另一种方法是使用来自npm的shortid包。

It is very easy to use:

它很容易使用:

var shortid = require('shortid');console.log(shortid.generate()); // e.g. S1cudXAF

and has some compelling features:

并有一些引人注目的特点:

ShortId creates amazingly short non-sequential url-friendly unique ids. Perfect for url shorteners, MongoDB and Redis ids, and any other id users might see.

ShortId创建短得惊人的非连续url友好的唯一id。非常适合url缩写者、MongoDB和Redis id,以及任何其他id用户可能看到的内容。

  • By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
  • 默认情况下,7-14个url友好字符:A-Z、A-Z、0-9、_-
  • Non-sequential so they are not predictable.
  • 非连续的,所以它们是不可预测的。
  • Can generate any number of ids without duplicates, even millions per day.
  • 可以生成任意数量的id而不需要重复,甚至每天可以生成数百万个。
  • Apps can be restarted any number of times without any chance of repeating an id.
  • 应用程序可以重新启动任意次数,而不需要重复任何id。

#5


7  

node-uuid is deprecated so please use uuid

节点uuid已被弃用,因此请使用uuid

npm install uuid --save// Generate a v1 UUID (time-based) const uuidV1 = require('uuid/v1');uuidV1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' // Generate a v4 UUID (random) const uuidV4 = require('uuid/v4');uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

Npm link

Npm链接

#6


3  

More easy and without addition modules

更简单,没有添加模块

Math.random().toString(26).slice(2)

#7


1  

If some one needs cryptographic-strong UUID, there is solution for that as well.

如果有人需要密码强大的UUID,也有解决方案。

https://www.npmjs.com/package/generate-safe-id

https://www.npmjs.com/package/generate-safe-id

npm install generate-safe-id

Why not UUIDs?

为什么不uuid呢?

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.

随机uuid (UUIDv4)没有足够的熵来实现普遍的唯一性(讽刺,是吗?)随机熵的uuid只有122位,这表明重复发生后只有2 ^ 61 id。此外,一些uuuidv4实现不使用加密强随机数生成器。

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.

该库使用节点生成240位id。js加密提高,表明生成后的第一个重复发生2 ^ 120 id。基于人类目前的能量生产,在可预见的未来,这个阈值是不可能跨越的。

var generateSafeId = require('generate-safe-id');var id = generateSafeId();// id == "zVPkWyvgRW-7pSk0iRzEhdnPcnWfMRi-ZcaPxrHA"