Skip to content

Instantly share code, notes, and snippets.

@aronanda
Last active December 2, 2018 04:23
Show Gist options
  • Save aronanda/f5ff41bca90968007819b0b939aba38a to your computer and use it in GitHub Desktop.
Save aronanda/f5ff41bca90968007819b0b939aba38a to your computer and use it in GitHub Desktop.
Node.js Server
const http = require('http'),
url = require('url'),
fs = require('fs'),
path = require('path'),
port = process.env.PORT || 3000,
docroot = process.argv[2] || process.env.DOCROOT || '.',
log = console.log.bind(console)
http.createServer(function (req, res) {
log(`${ req.method } ${ req.url }`)
const parsedUrl = url.parse(req.url)
let pathname = path.resolve(docroot, (`.${ parsedUrl.pathname }`)
.replace(/\%2520/g, '%20')
.replace(/^(\.)+/, '.')
.replace(/(\/)$/, ''))
const ext = path.parse(pathname).ext || '.html'
const mimeTypes = {
'.css' : 'text/css',
'.html': 'text/html',
'.png' : 'image/png',
'.wav' : 'audio/wav',
'.jpg' : 'image/jpeg',
'.mp3' : 'audio/mpeg',
'.ico' : 'image/x-icon',
'.svg' : 'image/svg+xml',
'.js' : 'text/javascript',
'.pdf' : 'application/pdf',
'.json': 'application/json',
'.doc' : 'application/msword'
}
if (!fs.existsSync(pathname)) {
res.statusCode = 404
return res.end(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Page Not Found</title> <meta name="viewport" content="width=device-width, initial-scale=1"><style>*{line-height: 1.2; margin: 0;}html{color: #888; display: table; font-family: sans-serif; height: 100%; text-align: center; width: 100%;}body{display: table-cell; vertical-align: middle; margin: 2em auto;}h1{color: #555; font-size: 2em; font-weight: 400;}p{margin: 0 auto; width: 280px;}@media only screen and (max-width: 280px){body, p{width: 95%;}h1{font-size: 1.5em; margin: 0 0 0.3em;}}</style></head><body><h1>Page Not Found</h1><p>Sorry, but the page you were trying to view does not exist.</p></body></html>`)
}
if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext
fs.readFile(pathname, function(err, data){
if (err) {
res.statusCode = 500
res.end(`Error getting the file: ${err}.`)
} else {
res.setHeader('Content-type', mimeTypes[ext] || 'text/plain' )
res.end(data)
}
})
}).listen(parseInt(port))
log(`Server listening on port ${port}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment