Last active
April 29, 2024 20:53
-
-
Save Belrestro/a3b328d79ea38cf83b357aede3babf62 to your computer and use it in GitHub Desktop.
Simplest Static metatech
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 path from 'node:path'; | |
import fs from 'node:fs'; | |
import http from 'node:http'; | |
const HTTP_PORT = 3000; | |
const STATIC_DIR = path.join(process.cwd(), './static'); | |
const fsExists = (filePath) => fs.promises.access(filePath).then(() => true, () => false); | |
const mimeTypes = { | |
default: 'application/octet-stream', | |
txt : 'text/plain', | |
json : 'application/json', | |
html : 'text/html', | |
jpe : 'image/jpeg', | |
jpeg : 'image/jpeg', | |
jpg : 'image/jpeg', | |
png : 'image/png', | |
css : 'text/css', | |
}; | |
const getFile = async (url) => { | |
const pathParts = [STATIC_DIR, url]; | |
if (url === '/') pathParts.push('index.html'); | |
const filePath = path.join(...pathParts); | |
const pathTraversal = !filePath.startsWith(STATIC_DIR); | |
const found = !pathTraversal && await fsExists(filePath); | |
const streamPath = found ? filePath : path.join(STATIC_DIR, '404.html'); | |
const stream = fs.createReadStream(streamPath); | |
const ext = path.extname(streamPath).substring(1).toLowerCase(); | |
return { found, ext, stream }; | |
} | |
const server = http.createServer(async (req, res) => { | |
const { method, url } = req; | |
const file = await getFile(req.url); | |
const statusCode = file.found ? 200 : 404; | |
const mimeType = mimeTypes[file.ext] || mimeTypes.default; | |
res.writeHead(statusCode, { 'Content-Type': mimeType }); | |
file.stream.pipe(res); | |
console.log(`request finished: ${method}:${url}`); | |
}); | |
server.listen(HTTP_PORT); | |
server.on('listening', () => console.log(`Server started on ${HTTP_PORT}`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment