-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
39 lines (35 loc) · 1.1 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
import http from "http";
import fs from "fs/promises";
import url from "url";
import path from "path";
const port = process.env.PORT || 3000;
// Get the current file name and directory name
const _fileName = url.fileURLToPath(import.meta.url);
const _dirname = path.dirname(_fileName);
console.log(_fileName, _dirname)
const server = http.createServer(async (req, res) => {
try {
if (req.method === "GET") {
let filePath;
if (req.url === "/") {
filePath = path.join(_dirname, "public", "index.html");
} else if (req.url === "/about") {
filePath = path.join(_dirname, "public", "about.html");
} else {
throw new Error("Page not found");
}
const data = await fs.readFile(filePath);
res.writeHead(200, { "content-type": "text/html" });
res.write(data);
res.end()
} else {
throw new Error("Method not allowed");
}
} catch (error) {
res.writeHead(500, { "content-type": "text/html" });
res.end("<h1>Server Error</h1>");
}
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});