I encountered a few gotchas that I wanted to share while hacking on Node.js this weekend. The tutorials available at nodejs.org are extremely thorough and very helpful, but you may run into some of the same issues that I did when expanding from your basic “hello world” application. First we will discuss Node.js specifically and then we will move on to deployment with Heroku.

There are several frameworks that can be used to build web applications with Node, such as Express.js and Geddy. To keep things simple, we will not be using any of them here. Instead we will be building a basic fibonacci calculator that accepts and parses a GET request using nothing but Node. Assuming your parameter is named “n”, the following code can be used within the body of http.createServer to parse the GET request:

var url = require('url');
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var n = query['n'];

Now that you are able to access the request parameter, you may notice in your debugging that the request is actually made twice each time you enter the url. If you are using Chrome, the browser will re-request favicon.ico on every single page call. The following code snippet will control for this:

if (typeof n != 'undefined') {
    res.write(fib(n) + '\n');

Here is the recursive fibonacci function which is being called:

function fib(n){
    if(n ==  || n == 1){
        return n;
    } else {
        return fib(n-1) + fib(n-2);

Feel free to skip ahead and grab the code from my GitHub repository if you would like to see the entire source. First though, let’s discuss a couple more issues which came about as I was deploying this application to Heroku. There is an excellent tutorial which will get you up to speed in no time, but I would like to emphasize a few details that may help you along the way.

You can use the “engines” section of your app’s package.json to select the version of Node.js and npm to use on Heroku. However, be careful not to specify the most recent version of Node which isn’t yet supported on Heroku. To avoid this, an empty block can be used to choose the default settings instead of defining particular engines:

  "name": "fib_node",
  "version": "0.0.1",
  "dependencies": {},
  "engines": {}

When I was developing my application locally, I hard-coded a port and an IP address, but this caused it to crash on Heroku. The port is discussed in the tutorial above, but in case you have also hard-coded an IP address, the following lines can be used to ensure that your application runs both locally and on Heroku:

var port = process.env.PORT || 5000;
var ip = '';

That is it! You can see the finished product here. Try passing different parameters in the GET request to see the resulting fibonacci number. Hopefully this fills in some of the gaps between developing a “hello world” application locally with Node.js and deploying a slightly more sophisticated application on Heroku.