Open In App

Node.js NPM shortid Module

Last Updated : 08 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 alphabet. It Can generate any number of ids without duplication.

Command to install:

npm install shortid

Syntax to import the package in local file-

const shortid = require('shortid')

Syntax to create unique id-

const newId = shortid.generate()

There are some methods defined on shortid modules to create unique ids and customize the ids. some of the methods are illustrated below.

shortid.generate() – Used to create unique id.

Example:

users.insert({
  _id: shortid.generate(),
  name: '...',
  email: '...'
});

shortid.isValid(id) – Used to check if id is valid or not.

Example:

shortid.isValid('41GHDbE');
// true
shortid.isValid('i have spaces');
// false

shortid.characters(characters) – Used to customize the ids.

Example:

shortid.characters('ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉ'
+ 'ⓊⓋⓌⓍⓎⓏⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥ'
+ 'ⓦⓧⓨⓩ①②③④⑤⑥⑦⑧⑨⑩⑪⑫');

Example 1: This example illustrates how to generate and use shortid package to create unique ids.

filename-index.js : This file contains all the logic to create short id and attach it with user information and save to the database.

javascript




const express = require('express')
const bodyParser = require('body-parser')
const shortid = require('shortid')
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 = shortid.generate()
   
  // 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=
  <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

Submitting information3

Database:

Database after submitting the informations

Example 2: This example illustrates how to customize and use shortid package to create unique ids.

filename-index.js: This file contains all the logic to create short id and attach it with user information and save to the database.

javascript




const express = require('express')
const bodyParser = require('body-parser')
const shortid = require('shortid')
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
 
  // Customising id creation
  shortid.characters('ⒶⒷⒸⒹⒺⒻⒼⒽⒾ'
    + 'ⒿⓀⓁⓜⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ'
    + 'ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠ'
    + 'ⓡⓢⓣⓤⓥⓦⓧⓨⓩ①②③④⑤⑥⑦⑧⑨⑩⑪⑫')
 
  // Creating new unique id
  const userId = shortid.generate()
 
  // 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




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 information1

Submitting information 2

Submitting information 3

Database:

Database after submitting the informations

Note: We have used some Bulma classes in form.js file to design our content.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads