Generate UUID in Node.js

  1. uuid.v1()
  2. uuid.v3()
  3. uuid.v4()
  4. uuid.v5()

1. uuid.v1()

The uuid.v1() method generates a Version 1 UUID, which is based on the current timestamp, MAC address, and unique identifier of the node.js system.

Here is an example:

const uuid = require('uuid');

const uuidv1 = uuid.v1();
console.log(uuidv1);

2. uuid.v3()

The uuid.v3() method generates a Version 3 UUID, which requires a namespace and a value. It uses the MD5 hashing algorithm to generate the UUID based on the provided namespace and value.

Here is an example:

const uuid = require('uuid');

const namespace = '1b671a64-40d5-491e-99b0-da01ff1f3341';
const value = 'example';

const uuidv3 = uuid.v3(value, namespace);
console.log(uuidv3);

3. uuid.v4()

The uuid.v4() method generates a Version 4 UUID, which is a randomly generated UUID. It does not require any parameters.

Here is an example:

const uuid = require('uuid');

const uuidv4 = uuid.v4();
console.log(uuidv4);

4. uuid.v5()

The uuid.v5() method generates a Version 5 UUID, which requires a namespace and a value. It uses the SHA-1 hashing algorithm to generate the UUID based on the provided namespace and value.

Here is an example:

const uuid = require('uuid');

const namespace = '1b671a64-40d5-491e-99b0-da01ff1f3341';
const value = 'example';

const uuidv5 = uuid.v5(value, namespace);
console.log(uuidv5);

Summary

In this tutorial, we explored different ways of generating UUIDs in Node.js using the uuid module. We learned about the uuid.v1(), uuid.v3(), uuid.v4(), and uuid.v5() methods and saw examples for each of them.

References