How to generate unique identifiers in Node.js

Using UUID as a identifier

A universal unique identifier (UUID) is a standard of generating identifiers, standardized by the Open Software Foundation (OSF).

The intent of UUIDs is to be able to generate unique identifiers in a distributed system without central coordination point.

Version 1 UUID is meant for generating time-based UUIDs. They also accept 48 bit long identifier (281,474,976,710,655 available values). In many cases it make sense to use a machine MAC Address as an identifier.

Version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers. UUID v4 are not giving us guaranteed unique numbers; they are rather practically unique. Probability of getting a duplicate is as follows: Only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%.

The Node.js node-uuid module is very simple to use.

# sudo npm install -g node-uuid
# npm link node-uuid

var uuid = require('node-uuid');

Non-sequential url-friendly unique ids

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.

# sudo npm install -g shortid
# npm link shortid

var shortid = require('shortid');

idgen supports generating any length ID.

# sudo npm install -g idgen
# npm link idgen

var idgen = require('idgen');
comments powered by Disqus