How to generate ULID in Nodejs wih example

This tutorial explains abuout How to generate ULID in Nodejs.

ULID or Universally Unique Lexicographically Sortable Identifiers are similar to UUID to have Unique identifier

It is used for creating unique index keys, allows to easily sort and query functions.

node has ulid library, that provides an implementeation of ULID identifier in Javascript and Nodejs.

Open Terminal, Install using below command in Node Project

npm install ulid

Generate ULID Unique Identifer In nodjes

const { ulid } = require("ulid");

const ulidObject = ulid();
console.log(ulidObject); // 01HHSDYQWP4HX5CRXPDS8HXZKT
console.log(typeof ulidObject); //string

Above example, used ulid module in code using require(). ulid() generates the unique identifier and return valiue is a string.

ulid package provides addtitional features

  • Seed Time to return Same ULID key

ulid accepts time parameter that gives same time part of an string

Sytax

ulid(timestamp in milli seconds)

Here is an example

const { monotonicFactory, ulid } = require("ulid");

console.log(ulid()); // 01HHSKG0MBZTP06H4ECCNMZ9XV
console.log(ulid(1234567890)); // 00014SC0PJCJKM3YK8RCT2M6WV
console.log(ulid(1234567890)); // 00014SC0PJ7KMGYRT77TFXVPQB
console.log(ulid(1000000000)); // 0000XSNJG0Z2V8CTNPZHMAW0SV
console.log(ulid(1000000000)); // 0000XSNJG0QGYABPEB6F6QE20Y

Generated string is always same for a given seed timestamp. Example string 00014SC0PJCJKM3YK8RCT2M6WV contains 00014SC0PJ timestamp same for a given seed timestamp

  • Generate Sequence Monotonic Counter

With this library, You can generate the incremented counter of an generated key using monotonicFactory

const { monotonicFactory, ulid } = require("ulid");

const monoUlid = monotonicFactory();
console.log(monoUlid(1000));// 00000000Z8QGX9QE0MMSKDJBDB
console.log(monoUlid(5000000)); // 000004RJT0C6NVR7SRS8XZZPYE
console.log(monoUlid(5000000)) // 000004RJT0C6NVR7SRS8XZZPYF
console.log(monoUlid(5000000)); // 000004RJT0C6NVR7SRS8XZZPYG
console.log(monoUlid(5000000)); // 000004RJT0C6NVR7SRS8XZZPYH
console.log(monoUlid(5000000)); //000004RJT0C6NVR7SRS8XZZPYJ