-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
59 lines (49 loc) · 1.6 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const express = require('express')
const fs = require('fs')
const serveIndex = require('serve-index')
const bodyParser = require('body-parser')
const crypto = require('crypto')
const app = express()
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({ extended: false }))
const config = JSON.parse(fs.readFileSync('./data/config.json'))
app.get("/", (req,res)=>{
res.render('index')
})
app.post("/", (req,res)=> {
const hash = crypto.randomBytes(3).toString('hex')
const originalUrl = req.body['url']
const shortUrl = `http://${config['domain']}/s/${hash}`
if (originalUrl === ""){
res.redirect("/")
} else {
fs.readFile("./data/urls.json", (error, data) => {
if (error) throw error;
const urls = JSON.parse(data);
urls[hash] = {};
urls[hash]["originalUrl"] = originalUrl;
urls[hash]["shortUrl"] = shortUrl;
fs.writeFile("./data/urls.json", JSON.stringify(urls, null, 2),
(error2) => {
if (error2) throw error2;
}
);
});
res.render('url', {url:shortUrl})
}
})
app.get("/s/:hash", (req,res) =>{
const hash = req.params["hash"]
const urls = JSON.parse(fs.readFileSync('./data/urls.json'))
if (!urls[hash]) {
res.redirect("/")
}
else {
res.redirect(urls[hash]['originalUrl'])
}
})
app.use(express.static("./views/"))
app.use('/assets/', serveIndex('./assets/'))
app.listen(config['port'], () => {
console.log(`✔️ App listening on URL: ${config['domain']}:${config['port']}`)
})