Horje
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

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:

Screenshot-2023-11-17-021355

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:

Screenshot-2023-11-17-021852




Reffered: https://www.geeksforgeeks.org


Node.js

Related
Differentiate between worker threads and clusters in Node JS. Differentiate between worker threads and clusters in Node JS.
Best Hosting Platforms for MERN Projects Best Hosting Platforms for MERN Projects
How to Add Express to React App using Gulp ? How to Add Express to React App using Gulp ?
Node.js filehandle.readLines() Method Node.js filehandle.readLines() Method
How "Control Flow" Controls the Functions Calls ? How "Control Flow" Controls the Functions Calls ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13