How to generate unique ID with node.js?
Last Updated :
17 Nov, 2023
In this article, we are going to learn how to generate a unique ID using Node.js. Unique ID means a string contains a unique identity throughout the program.
Prerequisites
Approach 1: Using UUID
UUID is a module of NPM (Node Package Manager). UUID stands for Universally Unique Identifier. It is used to create a highly unique idenitifier that should not be duplicated easily, and it contains 32 hexadecimal characters that are grouped into five segments, which are separated by a hyphen.
npm i uuid
Example : Implementation of above given UUID.
Javascript
const uuid = require( 'uuid' );
console.log( 'Unique ID:' , uuid.v4());
|
Output:
Approach 2: Using Crypto
Crypto is a library of Node.js; you don’t need to install it separately in your project. It provides cryptographic functionality to Node JS.It can be used for the following requirements:
- Hashing
- Hash based message authentication code
- Encryption and Decryption
- Random Bytes
Example: Implementation of above approach.
Javascript
const crypto = require( 'crypto' );
console.log( 'Unique ID:' , crypto.randomBytes(16).toString( 'hex' ));
|
Output:
Share your thoughts in the comments
Please Login to comment...