-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
82 lines (72 loc) · 2.23 KB
/
server.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
82
import http from "http";
import fs from "fs";
import path from "path";
import exec from "child_process";
import chalk from "chalk";
const hostname = "127.0.0.1";
const port = 6969;
const siteDir = "./site";
const tsDir = "./src";
const notFound = path.join(siteDir, "404.html");
const data404 = fs.readFileSync(notFound);
exec.execSync("pnpm build");
fs.watch(tsDir, () => {
exec.execSync("pnpm build");
});
const server = http.createServer((req, res) => {
// Handling requests
let requestPath = path.join(siteDir, req.url);
if (req.url === "/") {
requestPath = path.join(siteDir, "index.html");
}
if (path.extname(requestPath) === "") {
requestPath += ".html";
}
let ext = path.extname(requestPath);
let type = {
".html": "text/html",
".css": "text/css",
".js": "text/javascript",
".json": "application/json",
".ico": "image/x-icon",
".png": "image/png",
".jpg": "image/jpg",
".wav": "audio/wav",
};
let contentType = type[ext] || "text/plain";
console.log(`Requested: ${requestPath} (${contentType})`);
// Serving files
fs.readFile(requestPath, (err, data) => {
if (!err) {
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
return;
}
// Else we handle the error
switch (err.code) {
case "ENOENT":
console.log(chalk.yellow(`!! ${requestPath} not found`));
res.writeHead(404, { "Content-Type": "text/html" });
res.end(data404);
break;
default:
console.log(chalk.red(`ERROR: ${err.code}`));
res.writeHead(500);
res.end(
`ERROR: ${err.code}\nContact the site owner about this`
);
}
});
});
// Error handling
server.on("error", (err) => {
if (err.code === "EADDRINUSE") {
console.log(chalk.red(`ERROR: port ${port} is already in use`));
process.exit(1);
} else {
console.log(chalk.red(`ERROR: ${err.code}`));
}
});
server.listen(port, hostname, () => {
console.log(chalk.blue(`Server running at http://${hostname}:${port}/`));
});