Wednesday, February 9, 2011

Web server in CoffeeScript and Node

So, here's a first stab at a web server using CoffeeScript and Node:

# Imports.
{createServer} = require 'http'
{parse: parseUrl} = require 'url'
{readFile} = require 'fs'
{resolve} = require 'path'

# Setup.
base = "#{resolve('.')}/"
log = console.log

# Server definition.
server = createServer (request, response) ->
reqPath = parseUrl(request.url).pathname
filePath = ".#{reqPath}"
status = 500
respond = (content) ->
response.writeHead status,
'Content-Length': content.length
'Content-Type': 'text/html'
response.end content
log "#{request.method} #{reqPath} #{status}"
# Verify the path is local to the base!!!
# TODO Better startsWith
if resolve(filePath).indexOf base
# TODO status = forbidden?
# Handle the request.
if request.method is 'GET'
readFile filePath, (err, data) ->
if err
if err.errno is 2
status = 404
data = ""
status = 200

# Start the server.
port = 8080
server.listen port, ->
log "Running on #{port} from #{base} ..."

Not so bad. Probably could be cleaned up. I get tangled in CoffeeScript sometimes, but usually it's straightforward.

I don't drink coffee, but this is nice little scripting all right.

No comments:

Post a Comment