-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.js
81 lines (67 loc) · 2.29 KB
/
routes.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
const fs = require('fs');
const requestHandler = (req, res) => {
const url = req.url;
const method = req.method;
if (url === '/') {
// Read the last message from the file
let lastMessage = '';
try {
const messages = fs.readFileSync('message.txt', 'utf8').split('\n').filter(Boolean);
lastMessage = messages;
} catch (err) {
console.error('Error reading file:', err);
res.statusCode = 500;
res.setHeader('Content-Type', 'text/html');
res.write('<html><body><h1>Internal Server Error</h1></body></html>');
return res.end();
}
res.write('<html>');
res.write('<head><title>Enter message</title></head>');
res.write('<body>');
// Display the last message at the top of the form
if (lastMessage) {
res.write(`<p>${lastMessage}</p>`);
}
// Display the form for entering a new message
res.write('<form action="/message" method="POST"><input type="text" name="message"><button type="submit">Send</button></form>');
res.write('</body>');
res.write('</html>');
return res.end();
}
if (url === '/message' && method === 'POST') {
const body = [];
req.on('data', (chunk) => {
body.push(chunk);
});
return req.on('end', () => {
const parseBody = Buffer.concat(body).toString();
const msg = parseBody.split('=')[1];
// Overwrite the entire file with the new message
try {
fs.writeFileSync('message.txt', msg + '\n', 'utf8');
console.log('Message saved to message.txt:', msg);
// Redirect to the home page
res.statusCode = 302;
res.setHeader('Location', '/');
return res.end();
} catch (error) {
console.error('Error writing to file:', error);
res.statusCode = 500;
res.setHeader('Content-Type', 'text/html');
res.write('<html><body><h1>Internal Server Error</h1></body></html>');
return res.end();
}
});
}
res.setHeader('Content-type', 'text/html');
res.write('<html>');
res.write('<head><title>My First Page</title></head>');
res.write('<body><h1>Hello from Node.js server</h1></body>');
res.write('</html>');
res.end();
}
module.exports = requestHandler;
// module.exports = {
// handler : requestHandler;
// someText : Some text;
// }