Open In App

Node.js NPM uuid

Last Updated : 08 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

MethodWork
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.


Next Article

Similar Reads