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



filter_none

edit
close

play_arrow

link
brightness_4
code

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}`)
})

chevron_right


filename – repository.js: This file contain all the logic to create database and interact with it.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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')

chevron_right


filename – form.js: This file contain all the logic to render form.

filter_none

edit
close

play_arrow

link
brightness_4
code

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>
  `
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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}`)
})

chevron_right


filename – repository.js: This file contain all the logic to create database and interact with it.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 formet.
module.exports = 
    new Repository('datastore.json')

chevron_right


filename – form.js: This file contain all the logic to render form

filter_none

edit
close

play_arrow

link
brightness_4
code

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>  
  `
}

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.