-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
75 lines (66 loc) · 2.04 KB
/
app.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
const http = require("http"),
fs = require("fs"),
os = require("os"),
qs = require("querystring"),
sendEmail = require("./emailSender"),
getDateTime = require("./getDateTime");
const port = 3000,
hostname = "127.0.0.1";
http
.createServer((req, res) => {
const pageUrl = req.url;
//handle response
if (pageUrl === "/" || pageUrl === "/home") {
res.writeHead(200, { "Content-Type": "text/html" });
res.write("Go to contact page for more info.");
res.end();
} else if (pageUrl === "/about") {
res.writeHead(200, { "Content-Type": "text/html" });
res.write("This is the about page");
res.end();
} else if (pageUrl === "/contact") {
fs.readFile("contact.html", (err, data) => {
if (err) {
return console.log(err);
}
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
}
//handle post request and send email
if (req.method == "POST") {
let body = "";
let post = {};
let firstname, lastname, email;
req.on("data", function(data) {
body += data;
});
req.on("end", function() {
({ firstname, lastname, email } = qs.parse(body));
sendEmail(email, firstname, lastname);
});
res.writeHead(200, { "Content-Type": "text/plain" }, function() {
res.end("Email sent!");
});
}
//handle user log
const username = os.hostname();
const currentTime = getDateTime();
const userIP = req.connection.remoteAddress;
const userTrack =
pageUrl === "/favicon.ico"
? ``
: `User ${username}, User IP: ${userIP}, currentTime: ${currentTime}, current page: ${pageUrl} \n`;
fs.appendFile("user-log.txt", userTrack, e => {
if (e) {
console.log(e);
}
console.log(
`User ${username}, User IP: ${userIP}, currentTime: ${currentTime}, current page: ${pageUrl} \n`
);
});
})
.listen(port, hostname, () => {
console.log(`Server is running on ${port}`);
});