How to generate unique ID with node.js
Install NPM uuid package (sources: https://github.com/kelektiv/node-uuid):
npm install uuid
and use it in your code:
var uuid = require('uuid');
Then create some ids ...
// 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:
const uuidv1 = require('uuid/v1');uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' const uuidv4 = require('uuid/v4');uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
** UPDATE 7.x
And now the above usage is deprecated as well, so use this package like this:
const { v1: uuidv1, v4: uuidv4,} = require('uuid');uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
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
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 uniqueids. Perfect for url shorteners, MongoDB and Redis ids, and any otherid 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.