Node: Best Practices

When writing code, especially any large project, such as a CMS or social network, it's very important to keep your code organized and readable. This helps new developers understand what the hell is going on, makes it easier to scale, and is just good practice.

I always find it hard to write code fast and good. Usually my day consists of eight or so hours of writing code and a few hours going back and refactoring, but I'm working on it.

Here's a few things on Node organization and practices that are easy to implement and will help you out a lot in the future.

Everything as a Module

This is one that I find most developers in the community know about but don't use. Creating groups of functions as modules instead of just out in the open allows your code to be much more organized, easier to add to, and makes it simple to adapt to other uses.

Here's what I mean. Instead of writing:

function getUsers(callback) {  
    var users = []; // get users here
    callback(users);
}

function addUser(user, callback) {  
    db.users.save(user, function(errors) {
        callback();
    });
}

You can instead write:

exports.get = function(callback) {  
    var users = []; // get users here
    callback(users);
}

exports.add = function(user, callback) {  
    db.users.save(user, function(errors) {
        callback();
    });
}

From there you can require the module and boom! Instant organization and simplicity.

Commenting

This one you'd think would be the most obvious, but far too many times have I seen code with either no comments or comments on only half the functions. Here's the rules of thumb I use...

Multi-Line Comments

Use these when defining a function's purpose.

/**
 * Gets all users
 */
exports.get = function(callback) {

}
Single-Line comments

Use these when explaining chunks of code inside a function.

exports.get = function(callback) {  
    // gets users object from database
    var users = [];

    callback(users);
}

Callbacks. Callbacks. Callbacks.

This one is huge in Node, especially with thousands of users on the site at the same time. Many functions and packages have asynchronous functions that require you to use callbacks, though, as a rule on thumb, I always use callbacks for any function, regardless of what it does.

Of course, you don't want to get into callback hell. If I know I'm going to be nesting callbacks more than two levels, I'll switch over to a package like async, use q, or write my own function quene module to help me out.

App.js ≠ Logic

This one is more so personal preference, but I still think it should always be used.

When creating a Node project, try to remove all the logic you can from your app.js file. It should only call other modules that do all the heavy lifting and split up the work. For example, don't put your routes in your app.js file. Instead, create a separate directory called routes with an index.js file in it. Then, in your app.js file, call it with something like:

require("./routes")(variable, variable);  

You're getting pretty good at this.

Conclusion

Almost every developer you meet will tell you "you're doing it wrong!". Try and take that with a grain of salt. You'll never be able to please everybody.

It's a common sore point in online comment threads, notably Reddit, for developers to argue over best practices, and in the end, 99% of the time, nobody changes their habits: good or bad.

This article is meant to be a nudge in the step of a system most developers can agree on, though I know I've already made some people angry, and I'm okay with that.

Update

A few people have written in about the paragragraph regarding callbacks. The reason I always choose to use callbacks is so I can adapt them to asyncronous methods in the future, without rewriting a ton of code.

This is much easier to manage (at least for me), and you're not out anything by doing so.


Did you enjoy this post? Sign up for my weekly email with tips, freebies, and other shit!