Static constructor in NodeJS objects

It's not hard to create an object in JavaScript and therefore in NodeJS. However, if you're an advanced user, you probably devil a little with static objects (Factories will be the definite example). Since JavaScript doesn't really comes with static constructors, we need to take advantage of NodeJS require feature.

About require

require is a nodejs specific. The cool thing about it, is that it is only called once. so, every code that executed there, is executed only once, what's making it a perfect place for static initialization.  Lets take a look at some code:

function Counter()
{
this.counter=0;
Counter.__counters++;
}

What we have here is a simple increase of the number of objects created. However, since Counter.__counters is not defined, we will get an error. sure, we can check that this variable exists in the object constructor, and currently this is not a big issue, but if the test is a timely manner or a costly one, we have a problem. Using NodeJS feature, we can solve it easily:


Counter.__counters=0;

function Counter() 
{ 
this.counter=0;
Counter.__counters++; 
}

The first line will be called only once, and thus make it a static constructor. This line can be replace in a function call, if we wish to make it neater, and the effect will remain the same.

Installing chef gems

This might sounds strange, but your regular gem location is not the location that chef is using. This is important in case you are trying to install any knife plugins, where regular gem just won’t work.

The usual location is:/opt/chef/embedded/bin/gem , but you might have it some place else. Generally, look for gem|chef|more, and this should do the trick.