Saturday, July 2, 2022
HomeWordPress DevelopmentMaking a url shortener in nodejs

Making a url shortener in nodejs


Right this moment we need to make a url shortener in nodejs. This mission will not use a database to save lots of the info, All the info will likely be saved in JSON file.

to start with, be sure you have put in nodejs. You should utilize nvm(Node model supervisor) to put in it in the event you’re utilizing Linux.

Let’s make the folder we need to code in there:

mkdir url-short
cd url-short
Enter fullscreen mode

Exit fullscreen mode

We are able to make a public/ listing to place out HTML and CSS recordsdata in there. So:

mkdir public/
Enter fullscreen mode

Exit fullscreen mode

And we are going to make a index.html in public/:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Suitable" content material="IE=edge">
    <meta identify="viewport" content material="width=device-width, initial-scale=1.0">
    <title>Doc</title>
    <hyperlink rel="stylesheet" href="index.css">
</head>
<physique>
    <kind motion="https://dev.to/" methodology="publish">
        <h1>Hyperlink shortener</h1>
        <enter sort="textual content" identify="origUrl" id="">
        <button sort="submit">shorten</button>
    </kind>
</physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

and index.css once more in public/:

physique{
    background-color: #00796B;
}
h1{
    coloration: #fff;
    font-size: 2em;
    font-weight: daring;
    text-align: middle;
    margin: 0;
    font-family: Arial, Helvetica, sans-serif;
}
enter{
    width: 70%;
    top: 2em;
    border: none;
    border-bottom: 1px stable #fff;
    background-color: #fff;
    coloration: #000;
    font-size: 1em;
    font-family: Arial, Helvetica, sans-serif;
    border-radius: 50px;
    margin-top:50px;
}
button{
    background-color: #1A237E;
    coloration: #fff;
    font-size: 1em;
    font-family: Arial, Helvetica, sans-serif;
    border: 0;
    border-radius: 50px;
    width: 70px;
    top: 40px;
}
Enter fullscreen mode

Exit fullscreen mode

And now we are going to set up npm package deal we want:

npm i categorical 
Enter fullscreen mode

Exit fullscreen mode

So We make a db.json within the root:

{hyperlinks:[]}
Enter fullscreen mode

Exit fullscreen mode

We are going to add urls to this later.
and index.js within the root:

const categorical = require("categorical")
const app = categorical()
const course of = require("course of")
const fs = require("fs")
// use dotenv to learn .env file and get the PORT
require("dotenv").config()
const port = course of.env.PORT


app.use(categorical.json())
app.use(categorical.urlencoded({ prolonged: true }))
// load html and css in public folder
app.use(categorical.static("public"))
app.get("/", (req, res) => { res.sendFile("index.html") })
Enter fullscreen mode

Exit fullscreen mode

Okay So we all know that index.html will ship a publish request to / containing authentic Url and we will get the info from db.json and chack if we now have saved this url earlier:

app.publish("/", (req, res) => {
    let newJson=JSON.parse(fs.readFileSync("./db.json"))
    const {origUrl} = req.physique;
    // examine if url is not in json
    newJson.hyperlinks.forEach(factor => {
        if (factor.url===origUrl) {
            res.ship(`<h1>Your shorted hyperlink is http://localhost:${port}/${factor.id}</h1>`)
        }
Enter fullscreen mode

Exit fullscreen mode

However what if we have not? We are able to make a id and retailer it json:

    // make the brief id and put it in db.json
    let id = Math.random() * 10000000;
    id=Math.ground(id)
    // push to json
    newJson.hyperlinks.push({
        id:id,
        url:origUrl
    })
    fs.writeFileSync("./db.json",JSON.stringify(newJson))
    res.ship(`<h1>Your brief url is: http://localhost:${port}/${id}</h1>`)
})
Enter fullscreen mode

Exit fullscreen mode

Okay, So we saved the id with the unique url. But when the person went to that id we should redirect the person to authentic url:

app.get("/:id",(req,res)=>{
    // redirect
    const id=req.params.id
    let newJson=JSON.parse(fs.readFileSync("./db.json"))
    let hyperlink=newJson.hyperlinks.discover(hyperlink=>hyperlink.id==id)
    if(hyperlink){
        res.redirect(hyperlink.url)
    }
    else{
        res.ship("no hyperlink discovered")
    }
})
app.hear(port, () => console.log(`app listening on port ${port}!`))
Enter fullscreen mode

Exit fullscreen mode

And so it really works
demo :

Additionally I’ve uploaded the code in github: hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments