Reputation: 4501
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?
Upvotes: 385
Views: 589301
Reputation: 10282
Since Node 14.17.0 you can now use the built-in crypto module to generate UUIDs (UUIDv4 Flavored):
const { randomUUID } = require('crypto'); // Added in: node v14.17.0
console.log(randomUUID());
// 'd2e46f61-09a3-469a-85bf-7c9d7932d13f'
For more you can explore https://nodejs.org/api/crypto.html#crypto_crypto_randomuuid_options
Note: crypto.randomUUID
is three times faster than uuid. And no need to add extra dependency.
Upvotes: 267
Reputation: 1
var uid = new ShortUniqueId(); var id = uid();
//add cdn link of ShortUniqueId in index.html body just above your script.js
Upvotes: -2
Reputation: 375
const uniqueId = self.crypto.randomUUID();
console.log(uniqueId)
Upvotes: 7
Reputation: 754
For me, the easiest way to get unique id is the time
, and I use hash
for that example
const hash = require('object-hash');
const user = { ..., iat: Date.now() }
const user_id = hash(user)
console.log(user_id) // ex. 49686bab1a2276e0b1bd61ccc86f8156
and that is how I actually get unique identifier in any aspect. because in real world time never repeats.
Upvotes: -1
Reputation: 9956
Install NPM uuid package (sources: https://github.com/uuidjs/uuid):
npm install uuid
and use it in your code, e.g. with ES6 imports:
import { v4 as uuidv4, v6 as uuidv6 } from 'uuid';
uuidv4();
uuidv6();
Or with CommonJS requires:
const {
v1: uuidv1,
v4: uuidv4,
} = require('uuid');
uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
For
Upvotes: 561
Reputation: 48566
Here is one benchmark for current solutions refer to nanoid benchmark
import { v4 as uuid4 } from 'uuid'
import benchmark from 'benchmark'
import shortid from 'shortid'
let suite = new benchmark.Suite()
suite
.add('crypto.randomUUID', () => {
crypto.randomUUID()
})
.add('nanoid', () => {
nanoid()
})
.add('uuid v4', () => {
uuid4()
})
.add("math.random", () => {
(new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)
})
.add('crypto.randomBytes', () => {
crypto.randomBytes(32).toString('hex')
})
.add('shortid', () => {
shortid()
})
.on('cycle', event => {
let name = event.target.name
let hz = formatNumber(event.target.hz.toFixed(0)).padStart(10)
process.stdout.write(`${name}${pico.bold(hz)}${pico.dim(' ops/sec')}\n`)
})
.run()
The result is
node ./test/benchmark.js
crypto.randomUUID 13,281,440 ops/sec
nanoid 3,278,757 ops/sec
uuid v4 1,117,140 ops/sec
math.random 1,206,105 ops/sec
crypto.randomBytes 280,199 ops/sec
shortid 30,728 ops/sec
Test env:
Upvotes: 2
Reputation: 564
let count = 0;
let previous = 0;
const generateUniqueId = () => {
const time = new Date().getTime()
count = time > previous ? 0 : (++count)
const uid = time + count
previous = uid
return uid
}
Upvotes: -2
Reputation: 19
You can use urid package npm install urid
import urid from 'urid';
urid(); // qRpky22nKJ4vkbFZ
Read full docs here: https://www.npmjs.com/package/urid
// Set the size
urid(8); //ZDJLC0Zq
// Use the character set
urid('num'); // 4629118294212196
urid('alpha'); // ebukmhyiagonmmbm
urid('alphanum'); // nh9glmi1ra83979b
// Use size with character set
urid(12, 'alpha'); // wwfkvpkevhbg
// use custom character set
urid(6, '0123456789ABCDEF'); // EC58F3
urid('0123456789ABCDEF'); // 6C11044E128FB44B
// some more samples
urid() // t8BUFCUipSEU4Ink
urid(24) // lHlr1pIzAUAOyn1soU8atLzJ
urid(8, 'num') // 12509986
urid(8, 'alpha') // ysapjylo
urid(8, 'alphanum') // jxecf9ad
// example of all character sets
urid('num') // 5722278852141945
urid('alpha') // fzhjrnrkyxralgpl
urid('alphanum') // l5o4kfnrhr2cj39w
urid('Alpha') // iLFVgxzzUFqxzZmr
urid('ALPHA') // ALGFUIJMZJILJCCI
urid('ALPHANUM') // 8KZYKY6RJWZ89OWH
urid('hex') // 330f726055e92c51
urid('HEX') // B3679A52C69723B1
// custom character set
urid('ABCD-') // ACA-B-DBADCD-DCA
Upvotes: 2
Reputation: 3279
to install uuid
npm install --save uuid
uuid is updated and the old import
const uuid = require('uuid/v4');
is not working and we should now use this import
const {v4: uuid} = require('uuid');
and for using it use as a function like this
const createdPlace = {
id: uuid(),
title,
description,
location: coordinates,
address,
creator
};
Upvotes: 12
Reputation: 1601
Simple, time based, without dependencies:
(new Date()).getTime().toString(36)
or
Date.now().toString(36)
Output: jzlatihl
plus random number (Thanks to @Yaroslav Gaponov's answer)
(new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)
Output jzlavejjperpituute
Upvotes: 59
Reputation: 8063
Generates cryptographically strong pseudorandom data. The size argument is a number indicating the number of bytes to generate.
// Asynchronous
const {
randomBytes,
} = require('crypto');
randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: unique random ID ${buf.toString('hex')}`);
});
Upvotes: 0
Reputation: 2063
i want to use this
class GUID {
Generate() {
const hex = "0123456789ABCDEF";
const model = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx";
var str = "";
for (var i = 0; i < model.length; i++) {
var rnd = Math.floor(Math.random() * hex.length);
str += model[i] == "x" ? hex[rnd] : model[i] ;
}
return str.toLowerCase();
}
}
console.log(new GUID().Generate());
console.log(new GUID().Generate());
console.log(new GUID().Generate());
console.log(new GUID().Generate());
console.log(new GUID().Generate());
Upvotes: 3
Reputation: 13739
My 5 cents:
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's string lacked hyphens sadly, so it did not conform to the uuid standard, which is what I believe most people came here for.
> generateUuid();
'143c8862-c212-ccf1-e74e-7c9afa78d871'
> generateUuid();
'4d02d4d6-4c0d-ea6b-849a-208b60bfb62e'
Upvotes: 9
Reputation: 9398
If you use node v15.6.0+ us can use crypto.randomUUID([options])
. Full documentation here.
Upvotes: 13
Reputation: 45029
edit: shortid has been deprecated. The maintainers recommend to use nanoid instead.
Another approach is using the shortid package from npm.
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.
- By default 7-14 url-friendly characters: 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.
- Apps can be restarted any number of times without any chance of repeating an id.
Upvotes: 47
Reputation: 774
Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random()
.
Math.random()
Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.
I call this the "Fractional-Unique-ID".
Wrote code to generate 1,000,000 Math.random()
numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):
random_numbers = []
for (i = 0; i < 1000000; i++) {
random_numbers.push(Math.random());
//random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16
}
if (i === 1000000) {
console.log("Before checking duplicate");
console.log(random_numbers.length);
console.log("After checking duplicate");
random_set = new Set(random_numbers); // Set removes duplicates
console.log([...random_set].length); // length is still the same after removing
}
Upvotes: 1
Reputation: 9232
nanoid achieves exactly the same thing that you want.
Example usage:
const { nanoid } = require("nanoid")
console.log(nanoid())
//=> "n340M4XJjATNzrEl5Qvsh"
Upvotes: 2
Reputation: 1519
used https://www.npmjs.com/package/uniqid in npm
npm i uniqid
It will always create unique id's based on the current time, process and machine name.
Features:-
Upvotes: 1
Reputation: 859
The solutions here are old and now deprecated: https://github.com/uuidjs/uuid#deep-requires-now-deprecated
Use this:
npm install uuid
//add these lines to your code
const { v4: uuidv4 } = require('uuid');
var your_uuid = uuidv4();
console.log(your_uuid);
Upvotes: 1
Reputation: 447
I am using the following and it is working fine plus without any third-party dependencies.
const {
randomBytes
} = require('crypto');
const uid = Math.random().toString(36).slice(2) + randomBytes(8).toString('hex') + new Date().getTime();
Upvotes: 1
Reputation: 2109
More easy and without addition modules
Math.random().toString(26).slice(2)
Upvotes: 19
Reputation: 334
If some one needs cryptographic-strong UUID, there is solution for that as well.
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"
Upvotes: 5
Reputation: 6980
node-uuid
is deprecated so please use 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'
Upvotes: 23
Reputation: 11836
The fastest possible way to create random 32-char string in Node is by using native crypto
module:
const crypto = require("crypto");
const id = crypto.randomBytes(16).toString("hex");
console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e
Upvotes: 478
Reputation: 3946
It's been some time since I used node.js, but I think I might be able to help.
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.
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.
Upvotes: 27