A Node crisis of confidence

After over ten years of PHP, I've spent the last couple of years almost exclusively developing using Node.JS. I consider myself pretty proficient. Happy with prototypal inheritance, Promises, and much of the new ES6 stuff.

However, today I started to get the feeling that I'd been doing something wrong for a long time. It concerns the sharing of resources across modules.

The question being, should a shared resource be required once and passed to modules, or can we rely on Node's caching (and pseudo-singleton implementation) to prevent duplicating resources. Consider the following two approaches:

One

// app.js
require('db');  
require('module_one')(db);  
require('module_two')(db);

// module_one.js
module.exports = function(db){  
  return {
    func_one : function(){
      ...
    }
  }
}

// module_two.js
module.exports = function(db){  
  return {
    func_two : function(){
      ...
    }
  }
}

Two

// app.js
require('module_one');  
require('module_two');

// module_one.js
require('db');  
module.exports = {  
  func_one : function(){
    ...
  }
}

// module_two.js
require('db');  
module.exports = {  
  func_two : function(){
    ...
  }
}

In the first approach, only one instance of db is ever created and used. This is explicitly clear. Though it does introduce dependency injection. The module itself cannot stand alone.

In the second approach, the db module is loaded twice, though because it's cached by Node, the second time gets the same instance as the first time. But the node developers acknowledge this is not guaranteed. If this fails, memory consumption could shoot up and database connections could grind to a halt.

I much prefer the second approach, the one I've used for two years without incident. But now I'm concerned it may be the wrong approach for larger projects.

If you've any thoughts, contact me on Twitter.

Update

After reading Liam Kaufman's article, How AngularJS Made Me a Better Node.js Developer and this thread on Stack Overflow I've come to the conclusion that the answer to the above is, it depends. Both approaches are equally valid and have different use-cases. I'd still be keen to see if there is any performance benefit to one approach over the other.

Key only SSH

To cut back on the hacking attempts and make things just that little bit more secure, it's a good idea to disable the use of passwords to login via SSH.

Of course you'll need a way to access it so make sure you're public key is in your ~/.ssh/authorized_keys file.

To disable the use of passwords with SSH edit the sshd_config config file using something like nano. You'll need to run this as sudo.

sudo nano /etc/ssh/ssh_config  

Find the following lines and change them, or add them if they're missing:

RSAAuthentication yes  
PubkeyAuthentication yes  
ChallengeResponseAuthentication no  
PasswordAuthentication no  
UsePAM no  

One caveat here. I found on Ubuntu 12.04 that when I turn off UsePAM the banner I usually see when connecting with SSH is not shown.

To fix this I uncommented and ammended the line which reads #Banner /etc/issue.net:

Banner /etc/motd  

Of course you'll need to restart sshd, depending on what service management system you use, enter the following:

sudo service ssh restart  
or  
sudo /etc/init.d/sshd restart  

Important Don't lose your private keys which match the public keys you've used, or you'll never get back in!

The elegance of optimised syntax

The following is an article I wrote on Medium back in September 2014. I just discovered it again and liked it so I thought I'd 'reprint' it here.


While staring at some code recently (code that wasn’t working) I was struck by how my code has improved over time by simple changes of syntax. As an example I’ll use toggling the value of a boolean variable: myvar

For those that don’t know a boolean value can only be either true or false. Some languages also permit the use of 1 or 0.

So when I first started out I would have explicitly compared the value to true in an if statement. If the variable is true, set it to false. Otherwise, set it to true:

if(myvar === true){  
   myvar = false;
} else {
   myvar = true;
}

After learning that anything other than a ‘falsey’ value always equates to true I omitted the explicit comparison:

if(myvar){  
   myvar = false;
} else {
   myvar = true;
}

An embarrassingly long time went by before I discovered the ternary operator making simple conditional assigns very concise:

myvar = (myvar) ? false : true;  

I thought this was as elegant as it could get. A single line, a single declaration of the variable to be assigned and the two options separated by simple punctuation.

However, the application of simple logic and the use of the not operator (!) can make the original five line, forty-seven character if statement in to a single line, thirteen character piece of poetry:

myvar = !myvar;  

In case this doesn’t make sense to you, it sets the variable to whatever it is not. So if myvar is true it becomes not true, or false. If false it becomes not false, or true.

Each code block above does exactly the same thing and probably has similar performance impact. Yet the effect it has on code readability and source code file size are surely significant.

Flexbox space-between and the last row

I'm smitten with flexbox. To really get to grips with it I built a comprehensive, minimum styling site to really grasp how to do layout with it.

I created a 'card' layout with eight cards and had two rows of four. Looked great:

Two rows of four cards

So I tested the responsiveness and at my desired breakpoint the rows change to three cards (thanks to flex-wrap) and I was struck something that didn't look good:

Eight cards across three rows

Despite a lot of playing around with flexbox properties and margins etc. I could not find a pure css solution so I had to embrace some 'progressive enhancement' and turn to JavaScript.

It struck me that in order to shift the last element along I would need an invisible element. Since I couldn't be certain of how many cards there would be, I'd need to add enough invisible elements to bring the total up to a number divisible by both three and four. The smallest number that divides by both is twelve.

The first function called takes an ID of the element that contains the cards. It then counts the child elements and passes that to the checkCount() function:

var container = document.getElementById(container_id);  
var card_count = container.children.length;  
checkCount(card_count, ...  

The checkCount() function takes the total number of cards and a callback function as arguments. By using the modulus operator (%) we can test to see if any remainder exists after dividing by twelve. Since a remainder other than zero is treated as true we know when we hit the right number when the if statement is false.

So if we do get a remainder, we increment the count and pass that to the same function. Hurrah for recursion!

function checkCount(current_total, next){  
  if(current_total % 12){ // 12 is smallest number that 3 and 4 go in to
    current_total += 1; // Proper way to do ++
    checkCount(current_total, next); // Recursion!
  } else {
    next(current_total);
  }
}

With the final count returned we can find the number of extra elements required by subtracting the original card count from it. Using this in a for loop we create elements with the class dummy_card and append them to the original container.

var dummy_element;  
for(i=0; i<(final_count-card_count); i++){  
  dummy_element = document.createElement('div');
  dummy_element.className = 'dummy_card';
  container.appendChild(dummy_element);
}

By giving the dummy_card a height of zero in the CSS it won't affect the look of the page. Although this approach does pollute the DOM a bit, by using empty div elements we don't affect the semantics. Seems to work.

Eight cards across three rows, fixed

Here's the full code:

function checkCount(current_total, next){  
  if(current_total % 12){ // 12 is smallest number that 3 and 4 go in to
    current_total += 1; // Proper way to do ++
    checkCount(current_total, next); // Recursion!
  } else {
    next(current_total);
  }
}
function addDummyElementsToCards(container_id){  
  var container = document.getElementById(container_id);
  var card_count = container.children.length;
  checkCount(card_count, function(final_count){
    var dummy_element;
    for(i=0; i<(final_count-card_count); i++){
      dummy_element = document.createElement('div');
      dummy_element.className = 'dummy_card';
      container.appendChild(dummy_element);
    }
  });
}
addDummyElementsToCards('cards');  

Internet Explorer EOL

I no longer support any version of Internet Explorer prior to version 11. Microsoft has, as of today, ended their support for them. This means that no bug-fixes, compatibility fixes, and more important security updates will be forthcoming.

There is no longer any compelling reason to use one of these old browsers. Security alone should justify moving to IE11, Edge, or one of the other free browsers.

I pulled up the analytics of the sites I have access to. And after a quick bit of tabulation and some maths I can say that on average 3% of visitors to the sorts of sites I build use IE with a version number less than 11.

Who knows what proportion of that 3% actually convert to completing some goal. Frankly, it's not worth the effort supporting them.