How to generate short id in Node.js ?
Last Updated :
09 Apr, 2021
In this article we are going to see how to generate a short id in Node.js. There is an 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.
Setting up of the environment:
-
Setting up of the NPM package of the project :
npm init -y
-
Installing Dependencies :
npm install express shortid
Basic Express server:
index.js
const express = require( 'express' );
const app = express();
app.get( '/' , (req , res)=>{
res.send( "GeeksforGeeks" );
})
app.listen(4000 , ()=>{
console.log( "server is running on port 4000" );
})
|
Output:
Example: Importing ‘shortid’ into our project, there are lots of features in shortid module.
Syntax:
const short = require('shortid');
server.js
const express = require( 'express' );
const app = express();
const short = require( 'shortid' );
app.get( '/' , (req , res)=>{
res.send(short());
})
app.listen(4000 , ()=>{
console.log( "server is running on port 4000" );
})
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...