-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
84 lines (72 loc) · 2.36 KB
/
index.js
File metadata and controls
84 lines (72 loc) · 2.36 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
const express = require("express");
const app = express();
const port = 3000;
const fs = require("fs");
const path = require("path");
const Handlebars = require("handlebars");
let questionData;
try {
const jsonData = fs.readFileSync(
path.join(__dirname, "question_data.json"),
"utf8",
);
questionData = JSON.parse(jsonData);
} catch (err) {
console.error("Error reading or parsing question_data.json:", err);
process.exit(1);
}
app.use(express.static(path.join(__dirname, "html")));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "html", "startpage.html"));
console.log(`Timestamp: ${new Date().toISOString()}`);
});
app.get("/q", (req, res) => {
fs.readFile(
path.join(__dirname, "html", "questionpage.html"),
"utf8",
(err, htmlData) => {
if (err) {
res.writeHead(404, { "Content-Type": "text/html" });
return res.end("404 Not Found");
}
const questionTemplate = Handlebars.compile(htmlData.toString());
const questionNumber = parseInt(req.query.p, 10);
const totalQuestions = questionData.length;
// Find the question by ID
const question = questionData.find((q) => q.id === questionNumber);
if (!question) {
res.writeHead(404, { "Content-Type": "text/html" });
return res.end("Question not found");
}
const replacements = {
qno: questionNumber,
question: question.question,
answers: question.answers.map((answer) => answer.text),
isFirstQuestion: questionNumber === 1,
isLastQuestion: questionNumber === totalQuestions,
};
const renderedHtml = questionTemplate(replacements);
res.writeHead(200, { "Content-Type": "text/html" });
res.write(renderedHtml);
return res.end();
},
);
console.log(
`Timestamp: ${new Date().toISOString()} | Question: ${req.origialURL} | IP: ${req.ip}\n`,
);
});
app.get("/r", (req, res) => {
fs.readFile(path.join(__dirname, "html", "resultspage.html"), (err, data) => {
if (err) {
res.writeHead(404, { "Content-Type": "text/html" });
return res.end("404 Not Found");
}
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
return res.end();
});
console.log(`Timestamp: ${new Date().toISOString()}`);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});