Geek Igor

Delaying Proxy in NodeJS

08 Jan 2015 on nodejs

It is about time to add a new tool to your toolbox.

During the Christmas holiday season I had some time to learn NodeJS. In this post I’ll show how to create a simple (but useful!) proxy server in less than 30 lines of code. I’ll also give some hints on how to start with JavaScript with no prior experience.

Delaying Proxy

To give some background. I have a piece of code calling elasticsearch via its REST api and I wanted to test how it behaves in case of various network delays. I decide to create a simple proxy to simulate it. The idea is depicted below.

Proxy to simulate network delays

The requirements for the delaying are:

An example usage may look like this.

Note This is a simple example, in practices, you’ll probably make the delay logic more complex - according to your use case.

Implementation

Its quite easy to create such a proxy in nodejs. You need the following code.

The core of the proxy is this:

setTimeout(proxy_func(req, res, proxy_to), latency * sec);

where proxy_func

proxy_func = function(req, res, target) {
      return function() {
          proxy.web(req, res, {target: target});
      };
};

It simply proxies the request after waiting the latency number of seconds. setTimeout is asynchronous so it is not a busy waiting.

This code relies on two external node modules, which we configure and pull via npm. npm is a package manager for nodejs. It can pull the dependencies and automate the build process (similarly to maven or gradle). It has a simple configuration - all you need to add a package.json file to the root directory of your project. An example file for our delaying proxy is depicted below.

Easy, right?

Learning NodeJS

I watched a presentation sent by one of my colleagues NodeJS For Java Developers by Tim Boudreau. This is a good start to get some feeling of nodejs, but you’ll need more.

I felt that my javascript knowledge is close to zero so I went though the Good Parts. The book is short and concise. I can highly recommend it. Then finally, I was ready to get a book on node - The Right Way. Again, short and to the point. The author walks you through a process of build a few apps, covering a lot of material in a fast-pace. Very good for a busy professional (we all are them, right? ;-)).

The Right Way

To sum up, I really enjoy working with NodeJS. It is a great tool to write network applications and utility scripts - node startup time is less than 1 sec plus it has a good library to deal with the file system, processes, pipes, etc. To learn the basics I did the following. It also gets a very good traction recently. Even if you are a full time java geek it’s worth to explore at least its basics.