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.
Generating UUID in Node.js
To generate a UUID in Node.js, follow the steps below:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
crypto.randomBytes()method to generate a UUID that is compliant with RFC4122 version 4. - Convert the generated UUID to a proper UUID (hexadecimal string) using the
Number.prototype.toString()method. - 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.