forked from BoubkerElmaayouf/mini-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
51 lines (42 loc) · 1.52 KB
/
server.js
File metadata and controls
51 lines (42 loc) · 1.52 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
42
43
44
45
46
47
48
49
50
51
const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = 3000;
const PUBLIC_DIR = path.join(__dirname, "app");
const server = http.createServer((req, res) => {
let filePath = path.join(PUBLIC_DIR, req.url);
const ext = path.extname(filePath).toLowerCase();
// MIME types for known file extensions
const mimeTypes = {
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
".png": "image/png",
".jpg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".txt": "text/plain",
};
const contentType = mimeTypes[ext] || "application/octet-stream";
fs.stat(filePath, (err, stats) => {
if (!err && stats.isFile()) {
// Serve the requested file
res.writeHead(200, { "Content-Type": contentType });
return fs.createReadStream(filePath).pipe(res);
}
// Fallback: serve index.html
const indexPath = path.join(PUBLIC_DIR, "index.html");
fs.readFile(indexPath, (indexErr, content) => {
if (indexErr) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("500 Internal Server Error");
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(content);
}
});
});
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});