In the realm of Node.js development, generating universally unique identifiers (UUIDs) is a common requirement. Node.js offers a versatile module, UUID, to accomplish this task efficiently. In this comprehensive guide, we’ll unravel the intricacies of Node.js UUID, providing insights and practical examples.
Understanding Node.js UUID
UUID, short for Universally Unique Identifier, is a standardized method for generating unique identifiers across different systems without requiring a centralized authority. These identifiers are 128-bit numbers, typically displayed as 32 hexadecimal digits separated by hyphens. Node.js offers the uuid
module to facilitate the generation of UUIDs effortlessly.
Basic Usage Example
Let’s start with a basic example of using Node.js UUID to generate a UUID:
const { v4: uuidv4 } = require('uuid');
// Generate a UUID
const uuid = uuidv4();
console.log('Generated UUID:', uuid);
Output:
Generated UUID: a6fd4ce9-d595-45ef-a3b7-5b0d5c6a56c4
Generating Multiple UUIDs
Node.js UUID allows generating multiple UUIDs in a single call. Let’s see how:
const { v4: uuidv4 } = require('uuid');
// Generate five UUIDs
for (let i = 0; i < 5; i++) {
console.log('Generated UUID:', uuidv4());
}
Output:
Generated UUID: e57aa5ac-ec16-4b91-9044-3bfe16c30661
Generated UUID: 23f282d4-480b-41f6-89b5-991d5d245fbf
Generated UUID: 80fcf146-af7e-4d29-8d64-5d7f73f88e9c
Generated UUID: 51e4465c-b079-4680-8f08-d8dd1809f184
Generated UUID: 6f9b3163-85e3-4fbf-ae82-0c02011fc6ff
Specifying Custom UUID Versions
Node.js UUID allows specifying the version of UUIDs to generate. Let’s generate a UUID of a specific version (e.g., version 5):
const { v5: uuidv5, NIL } = require('uuid');
// Generate a UUID with version 5
const uuid = uuidv5('hello', NIL);
console.log('Generated UUID (Version 5):', uuid);
Output:
Generated UUID (Version 5): 90710426-b0b3-5f4b-8570-f5c46c7b0c19