|
| 1 | +import { createServer } from "node:http"; |
| 2 | +import { readFile, stat } from "node:fs"; |
| 3 | +import { join, dirname, extname } from "node:path"; |
| 4 | +import { fileURLToPath } from "node:url"; |
| 5 | + |
| 6 | +// Get the current directory name |
| 7 | +const __filename = fileURLToPath(import.meta.url); |
| 8 | +const __dirname = dirname(__filename); |
| 9 | + |
| 10 | +// Define the path to the index.html file |
| 11 | +const filePath = join(__dirname, "src", "index.html"); |
| 12 | + |
| 13 | +// Create the server |
| 14 | +const server = createServer((req, res) => { |
| 15 | + // Handle requests for the root path |
| 16 | + if (req.url === "/") { |
| 17 | + readFile(filePath, (err, data) => { |
| 18 | + if (err) { |
| 19 | + res.writeHead(500, { "Content-Type": "text/plain" }); |
| 20 | + res.end("Internal Server Error"); |
| 21 | + } else { |
| 22 | + res.writeHead(200, { "Content-Type": "text/html" }); |
| 23 | + res.end(data); |
| 24 | + } |
| 25 | + }); |
| 26 | + } else { |
| 27 | + // Serve static files (like CSS) |
| 28 | + const fileUrl = join(__dirname, "src", req.url); |
| 29 | + stat(fileUrl, (err) => { |
| 30 | + if (err) { |
| 31 | + // If the file doesn't exist, send a 404 Not Found response |
| 32 | + res.writeHead(404, { "Content-Type": "text/plain" }); |
| 33 | + res.end("Not Found"); |
| 34 | + } else { |
| 35 | + // Read the requested file |
| 36 | + readFile(fileUrl, (err, data) => { |
| 37 | + if (err) { |
| 38 | + res.writeHead(500, { "Content-Type": "text/plain" }); |
| 39 | + res.end("Internal Server Error"); |
| 40 | + } else { |
| 41 | + // Determine the content type based on the file extension |
| 42 | + const ext = extname(req.url); |
| 43 | + let contentType = "text/plain"; |
| 44 | + switch (ext) { |
| 45 | + case ".css": |
| 46 | + contentType = "text/css"; |
| 47 | + break; |
| 48 | + case ".js": |
| 49 | + contentType = "application/javascript"; |
| 50 | + break; |
| 51 | + case ".png": |
| 52 | + contentType = "image/png"; |
| 53 | + break; |
| 54 | + case ".jpg": |
| 55 | + contentType = "image/jpeg"; |
| 56 | + break; |
| 57 | + case ".gif": |
| 58 | + contentType = "image/gif"; |
| 59 | + break; |
| 60 | + case ".svg": |
| 61 | + contentType = "image/svg+xml"; |
| 62 | + break; |
| 63 | + case ".html": |
| 64 | + contentType = "text/html"; |
| 65 | + break; |
| 66 | + } |
| 67 | + // Send the file contents with a 200 OK status |
| 68 | + res.writeHead(200, { "Content-Type": contentType }); |
| 69 | + res.end(data); |
| 70 | + } |
| 71 | + }); |
| 72 | + } |
| 73 | + }); |
| 74 | + } |
| 75 | +}); |
| 76 | + |
| 77 | +// Start the server on port 5300 |
| 78 | +server.listen(5300, () => { |
| 79 | + console.log("Server is running on http://localhost:5300"); |
| 80 | +}); |
0 commit comments