

Ask HN: How do you write clean node.js code? - michael_miller

I'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.<p>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:<p>userDB.get(uid, function(err,doc){
  if(err){
    // log error
  }
  // Do something with doc
});<p>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:<p>userData = Users.find(:uid =&#62; uid)<p>which results in no indentation, and is very easy to follow.<p>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 <i>before</i> 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.<p>It almost seems like this problem could be resolved with a little syntactic sugar:<p>userDB.get(uid) -&#62; (err, res)
// Anything below here to the end of the block is part of the callback<p>Seasoned node.js developers: How do you write clean code that solves issues such as this?
======
m0hit
I am not a seasoned node.js developer, but have been playing around with a
small node.js + socket.io + mongodb based application over the last month or
so.

Don't think I have direct answers to your question, but here is how I have
been learning:

\- the node.js boilerplates available on github are a useful starting point
for organizing your code <https://github.com/robrighter/node-boilerplate>,
<https://github.com/mape/node-express-boilerplate> There are differences in
how the code is structured, but they are great to learn from.

\- Break up your project into libraries. In many cases the very basic examples
do not break out the code appropriately for simplicity. However, there are
some great examples within express source (i can't remember the exact name)
that organize web applications routes into multiple files (and modules).

\- node.js has tons of well written code on github. I've been pouring over the
source code of express, socket.io-node, hummingbird and many other
applications. Especially lookout for TJ Holowaychuk, Guillermo Rauch, Isaacs,
ry.

\- the #node.js channel on irc is just amazing. There are interesting
conversations, and I have had a lot of help regarding not just problems I've
run into, but also style. I've pasted bits of code, that looked ugly to me and
others have helped me think through it.

Hope this helps a bit.

Of course look at all the great guides and books about node.js such as
howtonode.org , mastering node and others. There is a good list on:
<https://github.com/joyent/node/wiki/Resources>

~~~
cezary
> \- Break up your project into libraries. In many cases the very basic
> examples do not break out the code appropriately for simplicity. However,
> there are some great examples within express source (i can't remember the
> exact name) that organize web applications routes into multiple files (and
> modules).

Sounds like route separation:
[https://github.com/visionmedia/express/tree/master/examples/...](https://github.com/visionmedia/express/tree/master/examples/route-
separation)

------
ricardobeat
I've worked on a single, medium-size app to date, but I think these might have
an impact:

\- try Coffeescript. It may look strange at first but ends up way more elegant
and readable

\- use [Step](<https://github.com/creationix/step>) to ease sequential async
calls

\- visually organise your code (formatting, lined up declarations, well
separated pieces of functionality). This can help a lot after you've moved on
from one part of the codebase to another

------
mparke
Question, How many modules is your server broken up into? Are you utilizing
exports?

~~~
michael_miller
The server is pretty monolithic; the majority of the code lives in a single
file, with two modules taking care of some code which we share between
servers.

~~~
mparke
my first suggestion is then to break your server up into more modules, which
should improve your situation. I'm fairly new to node, but currently building
a few different apps. I'd recommend reading nodebeginner.org , you can also
check out a Node Server git repo i just created tonight, implemented based on
that tutorial. <https://github.com/mparke/Node-Server-Exploration> Feel free
to contact me if you want to chat more. I'd love to hear about your
experiences with Node.

~~~
michael_miller
This definitely feels like something that will help a lot. I tend to be doing
similar things in many places of my code, like getting the current user's
document from the user DB, and handling errors in the same way(by passing
{error: "description"} and a status code of 500 back to the client). By
factoring out shared/similar code into a library, I think the code will get a
lot cleaner. Thanks for the suggestion!

