Skip to content

Instantly share code, notes, and snippets.

@mcarneiro
Last active May 3, 2021 14:45
Show Gist options
  • Save mcarneiro/618af9384d2251df1ab189b29a40d20e to your computer and use it in GitHub Desktop.
Save mcarneiro/618af9384d2251df1ab189b29a40d20e to your computer and use it in GitHub Desktop.
nodejs simple static vanilla server (for dev/homolog reasons)
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)
@mcarneiro
Copy link
Author

mcarneiro commented May 2, 2021

$ curl https://gist.githubusercontent.com/mcarneiro/618af9384d2251df1ab189b29a40d20e/raw/app.js > app.js
$ node app.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment