Generating Random Short Id in Node.js

Express JSServer Side ProgrammingProgrammingNode.js

The 'shortId' package from NPM can be used to create short non-sequential URL-friendly unique ID's. By default, it returns a 7-14 URL-friendly characters from the following categories: "A-Z, a-z, 0-9, _, -". This package also supports clusters (automatically), custom seeds, and custom alphabets. It can generate any number of ID's without duplication.

Syntax

  • Setting up the NPM project:

npm init -y
  • Installing the 'shortId' dependency:

npm install express shortid
  • Importing shortId:

const short = require('shortid');

Example 1

Create a file with the name "shortId.js" and copy the following code snippet. After creating the file, use the command "node shortId.js" to run this code as shown in the example below −

// Generating Random Short Id in Node.js
// Importing the express & shortId module
const express = require('express');
const short = require('shortid');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;
app.get('/api' , (req , res)=>{
   // generating short random Id
   res.send(short());
})
// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

Hit the following endpoint with a GET Request: localhost:3000/api

UGjx0nys_

Example 2

Let's take a look at one more example.

// Generating Random Short Id in Node.js

// Importing the express & shortId module
const express = require('express');
const short = require('shortid');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;
app.get('/api' , (req , res)=>{
   // generating short random Id
   console.log("1. ", short());
   console.log("2. ", short());
   console.log("3. ", short());
   console.log("4. ", short());
   res.end();
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

Hit the following endpoint with a GET Request: localhost:3000/api

C:\home\node>> node shortId.js
Server listening on PORT 3000
1. Utw_TxFec
2. YHFJhDSMQ4
3. YxnJzSynVu
4. e5SpHUBCFf
raja
Updated on 06-Apr-2022 08:07:04

Advertisements