Node.js uuid package can generate UUIDs (Universally Unique IDentifiers). In this tutorial, we will use some examples to show you how to generate and validate.
1.Install uuid package in node.js
npm install uuid
2.Import uuid
const uuid = require('uuid');
3.Generate unique id using uuid.v4()
for(let x = 0; x<10; x++){ console.log(uuid.v4()); }
Run this code, you will get 10 unique ids.
You should notice: uuid package can generate different version unique id: v1, v3, v4, v5. The value of them is different.
const uuid = require('uuid'); console.log("v1: " + uuid.v1()); console.log("v3: " + uuid.v3()); console.log("v4: " + uuid.v4()); console.log("v5: " + uuid.v5());
4.Validate unique id using uuid.validate()
Here is an examplde code:
const uuid = require('uuid'); console.log(uuid.validate('something')); console.log(uuid.validate('83dc308b-ac4e-4d1e-9e0b-9e49041308c4')); console.log(uuid.version('83dc308b-ac4e-4d1e-9e0b-9e49041308c4'));
Run this code, you will see: