Last active
May 3, 2021 14:45
-
-
Save mcarneiro/618af9384d2251df1ab189b29a40d20e to your computer and use it in GitHub Desktop.
nodejs simple static vanilla server (for dev/homolog reasons)
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 port = process.env.PORT || process.env.npm_config_port || process.env.npm_package_config_port || 3000 | |
const typeList = { | |
html: 'text/html', | |
svg: 'image/svg+xml', | |
json: 'application/json', | |
js: 'application/javascript', | |
css: 'text/css', | |
jpg: 'image/jpeg', | |
png: 'image/png' | |
} | |
http.createServer((req, res) => { | |
console.log(req.url) | |
const filePath = __dirname + '/www' + (/\/$/.test(req.url) ? req.url + 'index.html' : req.url) | |
fs.readFile(filePath, (err, data) => { | |
if (err) { | |
res.writeHead(404) | |
res.end(JSON.stringify(err)) | |
return | |
} | |
let type = typeList[(req.url.split('.').pop() || 'html')] | |
if (type) { | |
res.setHeader('Content-Type', type); | |
} | |
res.writeHead(200) | |
res.end(data) | |
}) | |
}).listen(port) | |
console.log('Listening to port', port) |
Author
mcarneiro
commented
May 2, 2021
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment