Node.js 20 line proxy server ported to 15 lines of CoffeeScript
May 6, 2011 Leave a comment
I only recently discovered CoffeeScript which seems like it could be a nicer way of writing simple JavaScript code.
After seeing, and being impressed by A HTTP Proxy Server in 20 Lines of node.js Code around a year ago I thought it might be a suitable piece of code to try porting to CoffeeScript. More complicated than the “Hello World” on the Node.js homepage but still fairly simple.
http = require 'http'; http.createServer( (request, response) -> proxy = http.createClient 80, request.headers['host'] proxy_request = proxy.request request.method, request.url, request.headers; proxy_request.addListener 'response', (proxy_response) -> proxy_response.addListener 'data', (chunk) -> response.write chunk, 'binary' proxy_response.addListener 'end', -> response.end() response.writeHead proxy_response.statusCode, proxy_response.headers request.addListener 'data', (chunk) -> proxy_request.write chunk, 'binary' request.addListener 'end', -> proxy_request.end() ).listen(8080)
The port was incredibly simple, just some search/replace type modification and the five line saving is only on lines closing functions with });
. I’m not entirely convinced that it’s nicer to read for the moment but maybe it’s because I’m not very used to it yet. This code doesn’t exactly use many of the nice tricks that it can do.
I’ll definitely give CoffeeScript a go for with a small project in the future to evaluate it but for the moment the jury’s out.