NodeJS + MongoDB = TinyURL

Last week I started playing with NodeJS.

NodeJS is an evented IO for V8 JavaScript. It uses asynchronous processing for all operations. If you want to open file, you pass in the callback function as argument to file open function, which then gets executed when the file is opened and available.

The aforementioned approach leads a much higher number of requests with a much less execution and, most importantly, wait times. And since its all JavaScript, we’re not surprised, because that is how JavaScript essentially works in the browser window. Think about it, the browser needs to re-draw its ui every time you a change occurs, staying responsive to user interactions at the same time, the only way to do this is by executing event/callback loops.

So where would you use NodeJS. In real-time data processing. The perfect example of such usage is HummingBird, which uses NodeJS and MongoDB for producing real-time usage analytics and statistics for Gilt Groupe website, you can fork it on github.

Now I was installing NodeJS under Cygwin which was a bit tricky at first (the python version that comes with Cygwin needed to be ‘rebased’).

To run a rebase command on Windows, you need to close all Cygwin processes, open C:\cygwin\bin\ash.exe, and run:


In order to compile NodeJS, you would need the following:

After all the above dependencies were installed, cd to /path/to/your/nodejs, and run:

make install

To run tests, execute:

make test

Now that you have NodeJS installed, the first step is to create a ‘Hello World!’ application, to do this, create example.js with the following content:

When the file is created, go to the directory its located and run:

node example.js

If everything is correct, you should see something like this:

I used NodeJS and MongoDB to create a simple TinyURL application - you give it the url, it shortens it. The shortening algorithm is simple, each new url is assigned an auto-incrementing numeric index, which is then base 36 encoded to produce url key. Whenever url key is received, its base 36 decoded to get the numeric index, which is used to get the target location and send a 301 redirect header.

The application is very simple and lacks any kind of validation or error handling. The source code is open and available on github. Please feel free to fork it and use it. Feedback is much appreciated.

  1. avalanche123 posted this
Blog comments powered by Disqus