Generating UUID in Node.js

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to generate a UUID in Node.js. UUIDs are unique identifiers that are commonly used in distributed systems to uniquely identify entities without requiring centralized coordination. We will use the crypto module in Node.js to generate a UUID that is compliant with RFC4122 version 4.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28687{{"`Generating UUID in Node.js`"}} javascript/data_types -.-> lab-28687{{"`Generating UUID in Node.js`"}} javascript/arith_ops -.-> lab-28687{{"`Generating UUID in Node.js`"}} javascript/comp_ops -.-> lab-28687{{"`Generating UUID in Node.js`"}} end

Generating UUID in Node.js

To generate a UUID in Node.js, follow the steps below:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the crypto.randomBytes() method to generate a UUID that is compliant with RFC4122 version 4.
  3. Convert the generated UUID to a proper UUID (hexadecimal string) using the Number.prototype.toString() method.
  4. Alternatively, you can use the crypto.randomUUID() method that provides similar functionality.

Here's an example code snippet to generate UUID in Node.js:

const crypto = require("crypto");

const UUIDGeneratorNode = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
  );

You can call the UUIDGeneratorNode() method to generate a UUID.

UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'

Summary

Congratulations! You have completed the Generate UUID (Node.js) lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like