Skip to content
This repository was archived by the owner on Oct 5, 2025. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions JavaScript/shortner/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Import required modules
const express = require('express');
const shortid = require('shortid');
const app = express();
const port = 3000;

// In-memory storage for URLs
const urlDatabase = {};

// Middleware to parse JSON requests
app.use(express.json());

// Endpoint to create a short URL
app.post('/shorten', (req, res) => {
const originalUrl = req.body.url;

// Validate if URL is provided
if (!originalUrl) {
return res.status(400).json({ error: 'URL is required' });
}

// Generate a unique short ID
const shortUrl = shortid.generate();

// Store the original URL with the short URL as key
urlDatabase[shortUrl] = originalUrl;

// Return the short URL
res.json({ originalUrl, shortUrl: `http://localhost:${port}/${shortUrl}` });
});

// Endpoint to redirect to the original URL
app.get('/:shortUrl', (req, res) => {
const shortUrl = req.params.shortUrl;

// Look up the original URL
const originalUrl = urlDatabase[shortUrl];

if (!originalUrl) {
return res.status(404).json({ error: 'URL not found' });
}

// Redirect to the original URL
res.redirect(originalUrl);
});

// Start the server
app.listen(port, () => {
console.log(`URL shortener app listening at http://localhost:${port}`);
});
17 changes: 17 additions & 0 deletions JavaScript/shortner/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "nodejs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start":"node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.19.2",
"shortid":"^4.19.0"
}
}