Created
May 21, 2024 07:42
-
-
Save YonatanKra/cd136ffb45a857f9e32738b8684790f4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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'; | |
const CONTENT_TYPES = { | |
'.js': 'text/javascript', | |
'.css': 'text/css', | |
'.png': 'image/png', | |
'.jpg': 'image/png', | |
'.gif': 'image/png', | |
}; | |
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'); | |
} | |
}); | |
} | |
const server = http.createServer((req, res) => { | |
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('Hello World!', '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