Skip to content

Instantly share code, notes, and snippets.

@jena-th
Last active December 16, 2015 17:39
Show Gist options
  • Select an option

  • Save jena-th/5471477 to your computer and use it in GitHub Desktop.

Select an option

Save jena-th/5471477 to your computer and use it in GitHub Desktop.
Quick and simple Node.js Server writen in Coffeescript
http = require 'http'
path = require 'path'
fs = require 'fs'
port = 80
sysout = console.log
CONTENT_TYPES =
html : 'text/html'
js : 'application/javascript'
css : 'text/css'
png : 'image/png'
jpg : 'image/jpeg'
gif : 'image/gif'
json : 'application/json'
mp3 : 'audio/mpeg'
swf : 'application/x-shockwave-flash'
httpReturn = (req, res, code..., content)->
if code.length is 0
code = [content]
content = ''
sysout code[0] + ' | ' + code[1]['Content-Type'] + ' | ' + req.url
res.writeHead.apply res, code
if content.length > 0
res.end content, 'utf-8'
else
res.end()
myServer = http.createServer((request, response)->
filePath = '.' + request.url;
if filePath == './' then filePath = './index.html'
extname = path.extname filePath
contentType = CONTENT_TYPES[extname.substring(1)]
fs.exists filePath, (exists)->
if exists
fs.readFile filePath, (error, content)->
if error
httpReturn request, response, 500
else
httpReturn request, response, 200, { 'Content-Type': contentType }, content
else
httpReturn request, response, 404
).listen port
sysout 'Server running at http://127.0.0.1:' + port + '/'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment