Last active
May 21, 2024 13:51
-
-
Save YonatanKra/12e55900b4664337950a6e0a83fb5999 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import http from 'http'; | |
import fs from 'fs'; | |
import path from 'path'; | |
import * as routes from './routes/index.mjs'; | |
const CONTENT_TYPES = { | |
'.js': 'text/javascript', | |
'.mjs': 'text/javascript', | |
'.css': 'text/css', | |
'.png': 'image/png', | |
'.jpg': 'image/png', | |
'.gif': 'image/png', | |
'.ico': 'image/png', | |
}; | |
const server = http.createServer(async (req, res) => { | |
function returnFileContent(filePath, contentType) { | |
fs.readFile(filePath, (err, content) => { | |
if (err) { | |
if (err.code === 'ENOENT') { | |
res.writeHead(404); | |
res.end('File not found'); | |
} else { | |
res.writeHead(500); | |
res.end(`Server Error: ${err.code}`); | |
} | |
} else { | |
res.writeHead(200, { 'Content-Type': contentType }); | |
res.end(content, 'utf-8'); | |
} | |
}); | |
} | |
let filePath = '.' + req.url; | |
if (filePath === './') { | |
filePath = 'HomePage'; | |
} | |
const extname = path.extname(filePath); | |
let contentType = CONTENT_TYPES[extname] ?? 'text/html'; | |
if (contentType === 'text/html') { | |
res.writeHead(200, { 'Content-Type': contentType }); | |
res.end(await routes[filePath].template, 'utf-8'); | |
} else { | |
returnFileContent(filePath, contentType); | |
} | |
}); | |
const PORT = 3000; | |
server.listen(PORT, () => { | |
console.log(`Server running on http://localhost:${PORT}/`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment