Node.js NPM uuid

08 Apr, 2022
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:
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 dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => {  res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.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 setupapp.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 moduleconst 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 dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => {  res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.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 setupapp.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 moduleconst 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.
rkbhola5
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.