|
| 1 | +const http = require("http"); |
| 2 | +const fs = require("fs"); |
| 3 | +const path = require("path"); |
| 4 | + |
| 5 | +const server = http.createServer((req, res) => { |
| 6 | + // Parse the URL |
| 7 | + const url = req.url === "/" ? "/index.html" : req.url; |
| 8 | + const filePath = path.join(__dirname, "public", url); |
| 9 | + const contentType = getContentType(filePath); |
| 10 | + |
| 11 | + // Check if the file exists |
| 12 | + fs.access(filePath, fs.constants.F_OK, (err) => { |
| 13 | + if (err) { |
| 14 | + // File not found, send a 404 response |
| 15 | + res.writeHead(404, { "Content-Type": "text/html" }); |
| 16 | + res.end("<h1>404 Not Found</h1>"); |
| 17 | + } else { |
| 18 | + // Read and serve the file |
| 19 | + fs.readFile(filePath, (err, content) => { |
| 20 | + if (err) { |
| 21 | + // Error reading the file, send a 500 response |
| 22 | + res.writeHead(500, { "Content-Type": "text/html" }); |
| 23 | + res.end("<h1>500 Internal Server Error</h1>"); |
| 24 | + } else { |
| 25 | + // Serve the file with the appropriate content type |
| 26 | + res.writeHead(200, { "Content-Type": contentType }); |
| 27 | + res.end(content); |
| 28 | + } |
| 29 | + }); |
| 30 | + } |
| 31 | + }); |
| 32 | +}); |
| 33 | + |
| 34 | +// Determine the content type based on the file extension |
| 35 | +function getContentType(filePath) { |
| 36 | + const extname = path.extname(filePath); |
| 37 | + switch (extname) { |
| 38 | + case ".html": |
| 39 | + return "text/html"; |
| 40 | + case ".css": |
| 41 | + return "text/css"; |
| 42 | + case ".js": |
| 43 | + return "text/javascript"; |
| 44 | + default: |
| 45 | + return "text/plain"; |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +const PORT = process.env.PORT || 3000; |
| 50 | + |
| 51 | +server.listen(PORT, () => { |
| 52 | + console.log(`Server is running on port ${PORT}`); |
| 53 | +}); |
0 commit comments