-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
100 lines (83 loc) · 2.5 KB
/
app.js
File metadata and controls
100 lines (83 loc) · 2.5 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const express = require('express')
const { engine } = require('express-handlebars')
const app = express()
const port = 3000
const fs = require('fs')
const fileName = 'data.json'
const data = fs.readFileSync(fileName);
let longLink = ''
let words = ''
app.engine('.hbs', engine({ extname: '.hbs' }))
app.set('view engine', '.hbs')
app.set('views', './views')
app.use(express.static('public'))
app.use(express.urlencoded({ extended: false })); //解析POST請求
app.get('/', (req, res) => {
res.render('index')
})
app.post('/shorten', (req, res) => {
longLink = req.body.url
shorten(longLink)
res.render('shorten', { words })
})
app.listen(port, () => {
console.log(`express server is running on http://localhost:${port}`)
})
app.get('/', (req, res) => {
res.render('index')
})
app.get('/:words', (req, res) => {
const { words } = req.params;
let searchData = JSON.parse(data)
for (let x = 0; x < searchData.length; x++) {
let stringSearchWord = (JSON.stringify(Object.values(searchData[x])))
modifiedWord = stringSearchWord.replace(/\["(.*)"\]/, '$1')
if (modifiedWord === words) {
let stringSearchLong = (JSON.stringify(Object.keys(searchData[x])))
modifiedLong = stringSearchLong.replace(/\["(.*)"\]/, '$1')
res.redirect(modifiedLong);
return;
}
}
res.status(404).send('No matched website')
})
function shorten(longLink) {
let oldData = '';
let saveData = [];
if (longLink.slice(-1) != '/') {
longLink += '/';
}
try {
if (data.length) {
oldData = JSON.parse(data);
for (let x = 0; x < oldData.length; x++) {
if (`["${longLink}"]` === JSON.stringify(Object.keys(oldData[x]))) {
stringWords = JSON.stringify(Object.values(oldData[x]));
words = stringWords.replace(/\["(.*)"\]/, '$1')
return words;
}
}
saveData = oldData;
}
randGen();
const newData = {
[longLink]: words
};
saveData.push(newData);
saveData = JSON.stringify(saveData);
fs.writeFileSync(fileName, saveData);
return words;
} catch (err) {
console.error('Error while reading or writing file:', err);
}
}
function randGen() {
words = ''
alltext = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
for (let i = 0; i < 5; i++) {
let randNum = Math.floor(Math.random() * 61 + 1)
let bingoNum = alltext[randNum]
words += bingoNum
}
return words;
}