generated from HugoDF/node-mit-boilerplate
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.js
More file actions
41 lines (36 loc) · 1.27 KB
/
serve.js
File metadata and controls
41 lines (36 loc) · 1.27 KB
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
// Dev server with no dependencies
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { join, extname as _extname } from "path";
const PORT = process.env.PORT || 3000;
const PUBLIC_DIR = import.meta.dirname;
const mimeTypes = {
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
".json": "application/json",
// map more types if necessary
};
createServer(async (req, res) => {
console.log(`${req.method} ${req.url}`);
// Default to index.html if no file is specified
let filePath = join(PUBLIC_DIR, req.url === "/" ? "html-esc.html" : req.url);
const extname = _extname(filePath).toLowerCase();
const contentType = mimeTypes[extname] || "application/octet-stream";
try {
const content = await readFile(filePath);
res.writeHead(200, { "Content-Type": contentType });
res.end(content, "utf-8");
} catch (error) {
console.error("Encountered error", error);
if (error.code === "ENOENT") {
res.writeHead(404, { "Content-Type": "text/html" });
res.end("Page not found", "utf-8");
} else {
res.writeHead(500);
res.end(`Sorry, there was an error: ${error.code}`);
}
}
}).listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});