NPM(Node Package Manager) is a package manager of Node.js packages. There is an NPM package called ‘shortid’ used to create short non-sequential url-friendly unique ids. Unique ids are created by Cryptographically-strong random values that’s why it is very secure. It has support for cross-platform like Node, React Native, Chrome, Safari, Firefox, etc.
Command to install:
npm install uuid
Syntax to import the package in local file
const {v4 : uuidv4} = require('uuid')
Syntax to create unique id
const newId = uuidv4()
There are some methods defined on shortid modules to create unique ids and customize the ids. some of the methods are illustrates below:
Method |
Work |
uuid.NIL |
The nil UUID string (all zeros) |
uuid.parse() |
Convert UUID string to array of bytes |
uuid.validate() |
Test a string to see if it is a valid UUID |
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 |
uuid.stringify() |
Convert array of bytes to UUID string |
Example 1: This example illustrates how to generate and use uuid package to create unique ids.
filename-index.js: This file contains all the logic to create unique ids and attach it with user information and save to the database.
javascript
const express = require( 'express' )
const bodyParser = require( 'body-parser' )
const {v4 : uuidv4} = require( 'uuid' )
const formTemplet = require( './form' )
const repo = require( './repository' )
const app = express()
const port = process.env.PORT || 3000
app.use(bodyParser.urlencoded({extended : true }))
app.get( '/' , (req, res) => {
res.send(formTemplet({}))
})
app.post( '/' , (req, res) => {
const {name, email} = req.body
const userId = uuidv4()
repo.create({
userId,
name,
email
})
res.send( 'Information submitted!' )
})
app.listen(port, () => {
console.log(`Server start on port ${port}`)
})
|
filename – repository.js: This file contain all the logic to create database and interact with it.
javascript
const fs = require( 'fs' )
class Repository {
constructor(filename) {
if (!filename) {
throw new Error(
'Filename is required to create a datastore!' )
}
this .filename = filename
try {
fs.accessSync( this .filename)
} catch (err) {
fs.writeFileSync( this .filename, '[]' )
}
}
async getAll() {
return JSON.parse(
await fs.promises.readFile( this .filename, {
encoding : 'utf8'
})
)
}
async create(attrs){
const records = await this .getAll()
records.push(attrs)
await fs.promises.writeFile(
this .filename,
JSON.stringify(records, null , 2)
)
return attrs
}
}
module.exports = new Repository( 'datastore.json' )
|
filename – form.js: This file contain all the logic to render form.
javascript
module.exports = ({errors}) => {
return `
<!DOCTYPE html>
<html>
<head>
<link rel= 'stylesheet' href=
<style>
div.columns {
margin-top: 100px;
}
.button {
margin-top: 10px
}
</style>
</head>
<body>
<div class= 'container' >
<div class= 'columns is-centered' >
<div class= 'column is-5' >
<form action= '/' method= 'POST' >
<div>
<div>
<label class= 'label'
id= 'str' >Name
</label>
</div>
<input class= 'input' type= 'text'
name= 'name' placeholder= 'Name'
for = 'name' >
</div>
<div>
<div>
<label class= 'label' id= 'email' >
Email
</label>
</div>
<input class= 'input' type= 'email'
name= 'email' placeholder= 'Email'
for = 'email' >
</div>
<div>
<button class= 'button is-info' >
Submit
</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
`
}
|
Output:
Submitting information1
submitting information2
Database:
Database after Submitting the informations
Example 2: This example illustrates how to use uuid.parse() and uuid.stringify() methods.
filename-index.js: This file contains all the logic to create unique ids and attach it with user information and save to the database and also convert id to parsed bytes and parsed bytes to string id.
javascript
const express = require( 'express' )
const bodyParser = require( 'body-parser' )
const {
v4 : uuidv4,
parse:uuidParse,
stringify : uuidStringify
} = require( 'uuid' )
const formTemplet = require( './form' )
const repo = require( './repository' )
const app = express()
const port = process.env.PORT || 3000
app.use(bodyParser.urlencoded({extended : true }))
app.get( '/' , (req, res) => {
res.send(formTemplet({}))
})
app.post( '/' , (req, res) => {
const {name, email} = req.body
const userId = uuidv4()
const parsedId = uuidParse(userId)
const stringfyId = uuidStringify(parsedId)
console.log(`parsedId : ${parsedId}\n`)
console.log(`StringifyId : ${stringfyId}\n`)
repo.create({
userId,
name,
email
})
res.send( 'Information submitted!' )
})
app.listen(port, () => {
console.log(`Server start on port ${port}`)
})
|
filename – repository.js: This file contain all the logic to create database and interact with it.
javascript
const fs = require( 'fs' )
class Repository {
constructor(filename) {
if (!filename) {
throw new Error(
'Filename is required to create a datastore!' )
}
this .filename = filename
try {
fs.accessSync( this .filename)
} catch (err) {
fs.writeFileSync( this .filename, '[]' )
}
}
async getAll() {
return JSON.parse(
await fs.promises.readFile( this .filename, {
encoding : 'utf8'
})
)
}
async create(attrs){
const records = await this .getAll()
records.push(attrs)
await fs.promises.writeFile(
this .filename,
JSON.stringify(records, null , 2)
)
return attrs
}
}
module.exports = new Repository( 'datastore.json' )
|
filename – form.js : This file contain all the logic to render form.
javascript
const getError = (errors, prop) => {
try {
return errors.mapped()[prop].msg
} catch (error) {
return ''
}
}
module.exports = ({errors}) => {
return `
<!DOCTYPE html>
<html>
<head>
<link rel= 'stylesheet' href=
<style>
div.columns {
margin-top: 100px;
}
.button {
margin-top: 10px
}
</style>
</head>
<body>
<div class= 'container' >
<div class= 'columns is-centered' >
<div class= 'column is-5' >
<form action= '/' method= 'POST' >
<div>
<div>
<label class= 'label' id= 'str' >
Name
</label>
</div>
<input class= 'input' type= 'text'
name= 'name' placeholder= 'Name'
for = 'name' >
</div>
<div>
<div>
<label class= 'label' id= 'email' >
Email
</label>
</div>
<input class= 'input' type= 'email'
name= 'email' placeholder= 'Email'
for = 'email' >
</div>
<div>
<button class= 'button is-info' >
Submit
</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
`
}
|
Output:
Submitting information
Parsed id and stringify id
Database:
Database after submitting the informations
Note: We have used some Bulma classes in form.js file to design our content.
Last Updated :
08 Apr, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...