-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (83 loc) · 3.01 KB
/
index.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
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
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
fs.readdir('./files', (err, files) => {
if (err) {
console.error("Error reading directory:", err);
return res.status(500).send("Server error");
}
// Read the contents of each file and store them along with the file name
let fileContents = [];
files.forEach((file) => {
const content = fs.readFileSync(`./files/${file}`, 'utf8');
fileContents.push({ fileName: file, content: content });
});
res.render('index', { files: fileContents });
});
});
app.post('/create', (req, res) => {
const { title, details } = req.body;
const fileName = `./files/${title.split(' ').join('')}.txt`; // Remove spaces from the filename
fs.writeFile(fileName, details, (err) => {
if (err) {
console.error("Error writing file:", err);
return res.status(500).send("Server error");
}
res.redirect('/');
});
});
app.get('/file/:filename', (req, res) => {
fs.readFile(`./files/${req.params.filename}`,"utf-8",function (err, data) {
res.render('show',{fileName:req.params.filename,data:data});
})
})
app.get('/edit/:filename', (req, res) => {
fs.readFile(`./files/${req.params.filename}`, "utf-8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
return res.status(500).send("Server error");
}
res.render('edit', { fileName: req.params.filename, fileContent: { title: req.params.filename, details: data } });
});
});
app.post('/edit/:filename', (req, res) => {
const { title, details } = req.body;
const oldFileName = `./files/${req.params.filename}`;
const newFileName = `./files/${title.split(' ').join('')}.txt`; // Remove spaces from the filename
fs.writeFile(newFileName, details, (err) => {
if (err) {
console.error("Error writing file:", err);
return res.status(500).send("Server error");
}
if (oldFileName !== newFileName) {
fs.unlink(oldFileName, (err) => {
if (err) {
console.error("Error deleting old file:", err);
return res.status(500).send("Server error");
}
res.redirect('/');
});
} else {
res.redirect('/');
}
});
});
app.post('/delete/:filename', (req, res) => {
const fileName = `./files/${req.params.filename}`;
fs.unlink(fileName, (err) => {
if (err) {
console.error("Error deleting file:", err);
return res.status(500).send("Server error");
}
res.redirect('/');
});
});
app.listen(8000, function () {
console.log('Server is running on port 8000');
});