BAM Weblog

node.js via CGI

Brian McKenna2010-04-27

Hi everyone! I've decided to create a new blog for myself. As many programmers do, I used this blog as an excuse to learn a new platform.

I wrote this blog engine from scratch using node.js. What makes this site different to the others running node.js is that this one is running completely off of a shared server (DreamHost, specifically).

When I was looking into using node.js, I found that most developers are deploying it by using the built-in web server and then optionally proxying it to Apache or Nginx. Those options just aren't possible when using cheap shared hosting. At this point I could:

  1. Rent a virtual machine to deploy a node.js website (costs money)
  2. Hack up a custom solution to make node.js server on a shared server (takes time)

I chose the latter and now I am the proud creator of the node-cgi monster. It's a CGI adaptor for node.js that mimmicks the node.js http library.

To use the adaptor you must create a .htaccess file that redirects paths to a CGI script. This blog uses:

Options +ExecCGI
AddHandler cgi-script cgi

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) server.cgi

Where server.cgi contains:

#!/usr/bin/env node

var blog = require('./blog'),
    cgi = require('./cgi');

var server = cgi.createServer(blog.requestListener);

For people not familiar with node.js, using this library is very similar to the standard way of creating a HTTP server:

var blog = require('./blog'),
    http = require('http');

var server = http.createServer(exports.requestListener);
server.listen(5000, "localhost");

This means that some applications will only have to change require('http') to require('cgi') to create a CGI version!

The library is up on GitHub for those that want to take a look. I'd like to know if anyone finds it useful!

Please enable JavaScript to view the comments powered by Disqus.