Node.js NPM shortid Module
Last Updated :
08 Apr, 2022
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
app.use(bodyParser.urlencoded({extended : true }))
app.get( '/' , (req, res) => {
res.send(formTemplet({}))
})
app.post( '/' , (req, res) => {
const {name, email} = req.body
const userId = shortid.generate()
repo.create({
userId,
name,
email
})
res.send( 'Information submitted!' )
})
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
const fs = require( 'fs' )
class Repository {
constructor(filename) {
if (!filename) {
throw new Error(
'Filename is required to create a datastore!' )
}
this .filename = filename
try {
fs.accessSync( this .filename)
} catch (err) {
fs.writeFileSync( this .filename, '[]' )
}
}
async getAll(){
return JSON.parse(
await fs.promises.readFile( this .filename, {
encoding : 'utf8'
})
)
}
async create(attrs){
const records = await this .getAll()
records.push(attrs)
await fs.promises.writeFile(
this .filename,
JSON.stringify(records, null , 2)
)
return attrs
}
}
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
app.use(bodyParser.urlencoded({extended : true }))
app.get( '/' , (req, res) => {
res.send(formTemplet({}))
})
app.post( '/' , (req, res) => {
const {name, email} = req.body
shortid.characters( 'ⒶⒷⒸⒹⒺⒻⒼⒽⒾ'
+ 'ⒿⓀⓁⓜⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ'
+ 'ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠ'
+ 'ⓡⓢⓣⓤⓥⓦⓧⓨⓩ①②③④⑤⑥⑦⑧⑨⑩⑪⑫' )
const userId = shortid.generate()
repo.create({
userId,
name,
email
})
res.send( 'Information submitted!' )
})
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
const fs = require( 'fs' )
class Repository {
constructor(filename) {
if (!filename) {
throw new Error(
'Filename is required to create a datastore!' )
}
this .filename = filename
try {
fs.accessSync( this .filename)
} catch (err) {
fs.writeFileSync( this .filename, '[]' )
}
}
async getAll(){
return JSON.parse(
await fs.promises.readFile( this .filename, {
encoding : 'utf8'
})
)
}
async create(attrs){
const records = await this .getAll()
records.push(attrs)
await fs.promises.writeFile(
this .filename,
JSON.stringify(records, null , 2)
)
return attrs
}
}
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
Share your thoughts in the comments
Please Login to comment...