Created
May 6, 2024 13:14
-
-
Save moriarty99779/5f6e67f5dfe2388bc4879e56f25e608e to your computer and use it in GitHub Desktop.
Simple nodejs Webserver
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
const http = require('http'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const server = http.createServer((req, res) => { | |
let filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url); | |
const ext = path.extname(filePath); | |
let contentType = 'text/html'; | |
switch (ext) { | |
case '.css': | |
contentType = 'text/css'; | |
break; | |
case '.js': | |
contentType = 'text/javascript'; | |
break; | |
case '.json': | |
contentType = 'application/json'; | |
break; | |
} | |
fs.readFile(filePath, (err, content) => { | |
if (err) { | |
if (err.code === 'ENOENT') { // Page not found | |
fs.readFile(path.join(__dirname, 'public', '404.html'), (err, content) => { | |
res.writeHead(404, { 'Content-Type': 'text/html' }); | |
res.end(content, 'utf-8'); | |
}); | |
} else { // Some server error | |
res.writeHead(500); | |
res.end(`Server Error: ${err.code}`); | |
} | |
} else { // Success | |
res.writeHead(200, { 'Content-Type': contentType }); | |
res.end(content, 'utf-8'); | |
} | |
}); | |
}); | |
const PORT = 3000; | |
server.listen(PORT, () => { | |
console.log('Running http://localhost:${PORT}/'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment