How to generate unique ID with node.js?
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.
Table of Content
- Using UUID
- Using Crypto
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.
- Install UUID
npm i uuid
Example : Implementation of above given UUID.
Javascript
// server.js 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
// Server.js const crypto = require( 'crypto' ); console.log( 'Unique ID:' , crypto.randomBytes(16).toString( 'hex' )); |
Output:
Contact Us