Saturday, November 10, 2012

Source Saturday: In which I learn node

Earlier this week I saw a job posting for my dream position with one caveat: They wanted a node.js guy.  Rather than ignore the fact that this once-in-a-lifetime opportunity had opened up, I decided to use this as an opening to demonstrate how proactive I am.  (This also explains why I've got so many job application posts lately.)  After going through

One of the nice things (or so I've heard) about node is that there's a LOT of features I have access to through npm.  I prefer to learn by doing so simply slapping together all the parts of a blog makes me no better than someone who codes exclusively in jQuery without understanding the JavaScript underneath.  In fact, I could pull an entire blog platform if I so wished.

Building the basics in node.js was actually a pleasure.  I really enjoyed the callback model and found it easy to wrap my head around what was going on stack-wise.  The project also introduced me to the noSQL movement (specifically mongodb).  

There's a lot of things I like about mongodb but I found one irritating issue.  Simply put, my code looked something like this:
function handlePageOne(req, res) {
    //Open database connection
    //Put something in the database
function handlePageTwo(req, res) {
    //Open database connection
    //Pull something from the database and add it to response
Simple?  Yes.  Correct?  Not a chance.  As it turns out, one actually needs to close the database connection as well (this is very important in a single thread environment like node.js).  What I ended up doing was adding a db.close() statement at the end of every database block.  You can view an example on GitHub.

This was only a toy application intended to help me learn the basics, so I stopped there.  On second thought, there are much better ways we could manage this.

We could (like Poet) not use a database at all for managing posts but rather store them as separate files.  This would eliminate any database issues and open new ones, mostly configuration.  Another option would to be to abstract the database calls into a separate function, ensuring to keep callbacks managed correctly.
EDIT: Another alternative would be to use an object modeling system like mongoose instead of rolling your own.

No comments:

Post a Comment