How to generate UUID in JavaScript
Generating UUID in JavaScript using the Crypto module
One way to generate UUID in JavaScript is to use the built-in Crypto module. As of Node.js version 14.17.0, the Crypto module includes a new method called crypto.randomUUID()
. This method can be used to directly generate a version 4 UUID. Here is an example:
const crypto = require('crypto');
const uuid = crypto.randomUUID();
console.log(myUUID);
Generating UUID in JavaScript using the uuid
package
Another way to generate UUID in JavaScript is to use the uuid package. This package provides a simple and convenient API for generating UUID of various versions, and can be used on both the client and server sides of a JavaScript application.
To use the uuid
package, you first need to install it using the npm or yarn package manager:
npm install uuid
Once you have installed the package, you can import it into your code:
import { v4 as uuidv4 } from 'uuid';
Here, we are importing the v4
method from the uuid
package, which generates Version 4 UUID.
To generate a UUID, simply call the uuidv4()
method:
const myUUID = uuidv4();
console.log(myUUID);
This will output a randomly generated UUID Version 4.
The uuid
package also provides methods for generating other types of UUID, such as Version 1 and Version 5 UUID. You can find more information about these methods in the package documentation.
Using this package really can simplify the process of generating UUID in your JavaScript projects.