Last active
October 23, 2016 17:50
-
-
Save Billy-/1dd830949614a98ee55b13a74d1f2153 to your computer and use it in GitHub Desktop.
Node static server handler
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
const http = require('http'), | |
staticServerHandler = require('./staticServerHandler'), | |
port = 8080 | |
let server = http.createServer(staticServerHandler) | |
server.listen(port) | |
console.log('Static server listening on port ' + port) |
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
const fs = require('fs'), | |
url = require('url'), | |
path = require('path'), | |
staticServerHandler = (req, res) => { | |
// parse URL | |
const parsedUrl = url.parse(req.url) | |
// extract URL path | |
let pathname = `.${parsedUrl.pathname}` | |
// based on the URL path, extract the file extention. e.g. .js, .doc, ... | |
let ext = path.parse(pathname).ext | |
// maps file extention to MIME type | |
const map = { | |
'.ico': 'image/x-icon', | |
'.html': 'text/html', | |
'.js': 'text/javascript', | |
'.json': 'application/json', | |
'.css': 'text/css', | |
'.png': 'image/png', | |
'.jpg': 'image/jpeg', | |
'.wav': 'audio/wav', | |
'.mp3': 'audio/mpeg', | |
'.svg': 'image/svg+xml', | |
'.pdf': 'application/pdf', | |
'.doc': 'application/msword' | |
} | |
if (ext === '') { | |
pathname += '/index.html' | |
ext = '.html' | |
} | |
// read file from file system | |
fs.readFile(pathname, (err, data) => { | |
if (err) { | |
if (err.code === "ENOENT") { | |
// if the file is not found, return 404 | |
res.statusCode = 404 | |
res.end(`File ${pathname} not found!`) | |
} else { | |
res.statusCode = 500 | |
res.end(`Error 500: ${err}.`) | |
} | |
} else { | |
// if the file is found, set Content-type and send data | |
res.setHeader('Content-type', map[ext] || 'text/plain' ) | |
res.end(data) | |
} | |
}) | |
} | |
module.exports = staticServerHandler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment