How to generate a UUID in Nodejs


UUID – Universal Unique Identifier– is a npm package which let you generate safe Cryptographically-strong random values using several settings. The package supports Node 8-14 versions and it has zero dependency module. The package is one of the top weekly downloads in the NPMjs.com

How to install

The package can be installed to Node project using

npm i uuid --save

How to generate values

To use the uuid generator we have to import using either one of the following method

import { v4 as uuidv4 } from 'uuid';
const { v4: uuidv4 } = require('uuid');

Methods

There are 4 commonly used method can be used to generate values.

uuid.v1()Create a version 1 (timestamp) UUID
uuid.v3()Create a version 3 (namespace w/ MD5) UUID
uuid.v4()Create a version 4 (random) UUID
uuid.v5()Create a version 5 (namespace w/ SHA-1) UUID

Random values

we can use uuid.v4() for random values as follows in JavaScript

const { v4: uuidv4 } = require('uuid');​
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

For more guide or instructions on the above method visit the npmjs.

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.