-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (54 loc) · 1.84 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
const http = require("http");
const fs = require("fs");
const path = require("path");
const hostname = "localhost";
const port = 3000;
const server = http.createServer((req, res) => {
console.log("Request for" + req.url + "by method" + req.method);
if (req.method == "GET") {
var fileURL;
if (req.url == "/") {
fileURL = "/index.html";
} else {
fileURL = req.url;
}
var filePath = path.resolve("./public" + fileURL);
const fileExt = path.extname(filePath);
if (fileExt == ".html" || fileExt == ".css" || fileExt == ".jpg") {
fs.exists(filePath, (exists) => {
if (!exists) {
res.statusCode = 404;
res.setHeader("Content-Type", "text/html");
res.end(
"<html> <body> <h1> error 404: " +
fileURL +
" doesnot exists </h1> </body> </html>"
);
} else {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
fs.createReadStream(filePath).pipe(res);
}
});
} else {
res.statusCode = 404;
res.setHeader("Content-Type", "text/html");
res.end(
"<html> <body> <h1> error 404: " +
fileURL +
" not an HTML file. </h1> </body> </html>"
);
}
} else {
res.statusCode = 404;
res.setHeader("Content-Type", "text/html");
res.end(
"<html> <body> <h1> error 404: " +
fileURL +
" not supported. </h1> </body> </html>"
);
}
});
server.listen(port, hostname, () => {
console.log(`Server Running at http://${hostname}:${port}`);
});