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).
function handlePageOne(req, res) {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.
//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
}
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