Created
May 27, 2014 02:18
-
-
Save kumabook/fa2e5086512244a79876 to your computer and use it in GitHub Desktop.
Simple static web server with coffee script
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
http = require 'http' | |
fs = require 'fs' | |
url = require 'url' | |
path = require 'path' | |
port = process.argv[2] || 8888; | |
mime = | |
".html": "text/html", | |
".css" : "text/css", | |
".js" : "application/javascript", | |
".png" : "image/png", | |
".jpg" : "image/jpeg", | |
".gif" : "image/gif", | |
".txt" : "text/plain" | |
http.createServer((req, res) -> | |
uri = url.parse(req.url).pathname | |
filename = path.join process.cwd(), uri | |
console.log filename | |
if fs.existsSync(filename) && fs.statSync(filename).isDirectory() | |
filename += '/index.html' | |
if fs.existsSync filename | |
renderStaticFile req, res, filename | |
else | |
renderNotFound req, res | |
).listen port | |
renderNotFound = (req, res) -> | |
res.writeHead 404, | |
'Content-Type': 'text/html' | |
res.write '404 Not Found\n' | |
res.end() | |
renderStaticFile = (req, res, filename) -> | |
ext = path.extname filename | |
res.writeHead 200, | |
'Content-Type': mime[ext] | |
fs.readFile filename, 'binary', (error, file) -> | |
res.write(file, 'binary') | |
res.end() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment