Skip to content

Instantly share code, notes, and snippets.

@romyilano
Created March 27, 2020 17:21
Show Gist options
  • Save romyilano/ec1ab1a26cbf2dc17ed3e3e5079fcbba to your computer and use it in GitHub Desktop.
Save romyilano/ec1ab1a26cbf2dc17ed3e3e5079fcbba to your computer and use it in GitHub Desktop.
Basic noob web server on node.js
// from O'Reilly Web Dev with Node & Express
const http = require('http')
const fs = require('fs')
const port = process.env.PORT || 3000
function serveStaticFile(res, path, contentType, responseCode = 200) {
fs.readFile(__dirname + path, (err, data) => {
if(err) {
res.writeHead(500, { 'Content-Type': 'text/plain' })
return res.end('500 - Internal Error')
}
res.writeHead(responseCode, { 'Content-Type': contentType })
res.end(data)
})
}
const server = http.createServer((req,res) => {
// normalize url by removing querystring, optional trailing slash, and
// making lowercase
const path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase()
switch(path) {
case '':
serveStaticFile(res, '/public/home.html', 'text/html')
break
case '/about':
serveStaticFile(res, '/public/about.html', 'text/html')
break
case '/img/logo.png':
serveStaticFile(res, '/public/img/logo.png', 'image/png')
break
default:
serveStaticFile(res, '/public/404.html', 'text/html', 404)
break
}
})
server.listen(port, () => console.log(`server started on port ${port}; ` +
'press Ctrl-C to terminate....'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment