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.
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= '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:
Database:
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= '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:
Database:
Note: We have used some Bulma classes in form.js file to design our content.
Contact Us