-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
60 lines (50 loc) · 1.38 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
60
const fs = require("fs");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const CSVToJSON = require("csvtojson");
const logDir = path.resolve(__dirname, "./logs");
const commentCSV = path.resolve(logDir, "comment.csv");
const config = JSON.parse(fs.readFileSync("package.json")).config;
const server = express();
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true });
}
if (!fs.existsSync(commentCSV)) {
fs.writeFileSync(commentCSV, "time,comment\n", {
flag: "wx",
});
}
server.post(
"/api/comment",
bodyParser.json({ type: "*/*" }),
(req, res, next) => {
const now = new Date().getTime();
const record = `${now},${req.body.comment}`;
fs.appendFile(commentCSV, `${record}\n`, (err) => {
if (err) {
console.error(err);
res.sendStatus(500);
} else {
res.sendStatus(200);
}
next();
});
}
);
server.get("/api/comment", (req, res) => {
CSVToJSON()
.fromFile("./logs/comment.csv")
.then((data) => {
res.json({ data });
})
.catch((err) => {
console.log(err);
});
});
server.use("/xss", express.static(__dirname + "/xss"));
server.use(express.static(__dirname + "/public"));
const port = parseInt(config["port"], 10);
server.listen(port, () => {
console.log(`Server is listening on http://localhost:${port}/`);
});