Ask HN: How do you write clean node.js code?
https://news.ycombinator.com/item?id=2539148I'm working on a smallish node.js + SproutCore app now, and I'm noticing that my node.js code has gotten really ugly, really quickly as my app has grown.
The most common cause of ugliness so far has been DB queries. Every time I want to access a DB, I have to do something to the effect of:
userDB.get(uid, function(err,doc){ if(err){ // log error } // Do something with doc });
This is fine on a small scale, but as my app grows, it gets really hard to read the code. What if I have 5 DB queries? That is 5 levels of indentation, and a lot of extra code. I would imagine the above being written in Ruby + Rails as:
userData = Users.find(:uid => uid)
which results in no indentation, and is very easy to follow.
The most common solution I've heard to this is "Well, just use named functions!" This seems to produce even uglier code: because functions have to be declared before I can use them, I have to declare the business logic in reverse order. This means that I have to read code "backwards" to get the linear flow! And, in my experience, each named function does little more than execute a DB query.
It almost seems like this problem could be resolved with a little syntactic sugar:
userDB.get(uid) -> (err, res) // Anything below here to the end of the block is part of the callback
Seasoned node.js developers: How do you write clean code that solves issues such as this?