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
// The body-parser middleware to parse form data
app.use(bodyParser.urlencoded({extended : true}))
// Get route to display HTML form
app.get('/', (req, res) => {
res.send(formTemplet({}))
})
// Post route to handle form submission logic and
app.post('/', (req, res) => {
// Fetching user inputs
const {name, email} = req.body
// Creating new unique id
const userId = uuidv4()
// Saving record to the database
// with attaching userid to each record
repo.create({
userId,
name,
email
})
res.send('Information submitted!')
})
// Server setup
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
// Importing node.js file system module
const fs = require('fs')
class Repository {
constructor(filename) {
// Filename where data are going to store
if(!filename) {
throw new Error(
'Filename is required to create a datastore!')
}
this.filename = filename
try {
fs.accessSync(this.filename)
} catch(err) {
// If file not exist it is created
// with empty array
fs.writeFileSync(this.filename, '[]')
}
}
// Get all existing records
async getAll() {
return JSON.parse(
await fs.promises.readFile(this.filename, {
encoding : 'utf8'
})
)
}
// Create new record
async create(attrs){
// Fetch all existing records
const records = await this.getAll()
// All the existing records with new
// record push back to database
records.push(attrs)
await fs.promises.writeFile(
this.filename,
JSON.stringify(records, null, 2)
)
return attrs
}
}
// The 'datastore.json' file created at runtime
// and all the information provided via signup form
// store in this file in JSON format.
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=
'https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'>
<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
// The body-parser middleware to parse form data
app.use(bodyParser.urlencoded({extended : true}))
// Get route to display HTML form
app.get('/', (req, res) => {
res.send(formTemplet({}))
})
// Post route to handle form submission logic and
app.post('/', (req, res) => {
// Fetching user inputs
const {name, email} = req.body
// Creating new unique id
const userId = uuidv4()
const parsedId = uuidParse(userId)
const stringfyId = uuidStringify(parsedId)
console.log(`parsedId : ${parsedId}\n`)
console.log(`StringifyId : ${stringfyId}\n`)
// Saving record to the database
// with attaching userid to each record
repo.create({
userId,
name,
email
})
res.send('Information submitted!')
})
// Server setup
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
// Importing node.js file system module
const fs = require('fs')
class Repository {
constructor(filename) {
// Filename where datas are going to store
if(!filename) {
throw new Error(
'Filename is required to create a datastore!')
}
this.filename = filename
try {
fs.accessSync(this.filename)
} catch(err) {
// If file not exist it is created
// with empty array
fs.writeFileSync(this.filename, '[]')
}
}
// Get all existing records
async getAll() {
return JSON.parse(
await fs.promises.readFile(this.filename, {
encoding : 'utf8'
})
)
}
// Create new record
async create(attrs){
// Fetch all existing records
const records = await this.getAll()
// All the existing records with new
// record push back to database
records.push(attrs)
await fs.promises.writeFile(
this.filename,
JSON.stringify(records, null, 2)
)
return attrs
}
}
// The 'datastore.json' file created at runtime
// and all the information provided via signup form
// store in this file in JSON format.
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=
'https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'>
<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.
Similar Reads
Node.js NPM shortid Module
NPM(Node Package Manager) is a package manager of Node.js packages. There is a NPM package called 'shortid' used to create short non-sequential url-friendly unique ids. By default, it uses 7-14 url-friendly characters: A-Z, a-z, 0-9, _-. It Supports cluster (automatically), custom seeds, custom alph
6 min read
NodeJS NPM
NPM (Node Package Manager) is a package manager for NodeJS modules. It helps developers manage project dependencies, scripts, and third-party libraries. By installing NodeJS on your system, NPM is automatically installed, and ready to use.It is primarily used to manage packages or modulesâthese are
6 min read
Node.js OS
The os module in Node.js provides operating system-related utility methods and properties. It helps retrieve system information such as CPU details, memory usage, and network interfaces, enabling you to write system-aware applications.It provides functions to interact with the operating system. It p
3 min read
Node.js Tutorial
Node.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was earlier mainly used for frontend d
4 min read
npm run dev
When working with Node.js and JavaScript projects, especially those involving frontend frameworks like React, Vue, or Next.js, you often encounter the command npm run dev. This command is pivotal for developers as it initiates the development server, enabling live reloading, hot module replacement,
3 min read
Node.js process.setuid() Method
The process.setuid() method is an inbuilt application programming interface of the process module which is used to set the user identity of the Node.js process. Syntax:Â process.setuid(id) Parameters: This method accepts single parameter as mentioned above and described below:Â Â id: It is a required
2 min read
Node.js Utility Module
The util module in Node.js provides a variety of utility functions that assist with tasks such as debugging, formatting, and inheritance. It includes methods for inspecting objects, formatting strings, and extending classes. Node.js Utility ModuleThe util module offers essential utilities that are n
4 min read
Node.js process.seteuid() Method
The process.seteuid() method is an inbuilt application programming interface of the process module which is used to set the effective user identity of the Node.js process. Syntax:Â process.seteuid( id ) Parameters: This method accepts single parameter as mentioned above and described below:Â Â id: It
2 min read
Node.js crypto.randomUUID( ) Function
The crypto.randomUUID() is  an inbuilt application programming interface of class Crypto within crypto module which is used to generate a random RFC 4122 Version 4 UUID. Syntax: const crypto.randomUUID([options]) Parameters: This function takes the disableEntropyCache as a parameter Return Value: Th
1 min read
Node JS Versions
Node.js is an open-source, cross-platform runtime environment built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applic
5 min read