Node.js Best practices


From my personal experience of Node.js I am writing some of the best practices you should follow while writing node.js APIs.
Naming Variables/callback function parameters

I think this will apply to any language and it is probably most obvious one, but still you should name your variables in such a manner that it will make some sense while reading it.
As they say
“Good naming of variables saves a lot of documentation”.
This is true in case of callback function parameters also, let’s look at an example below

Code like this will surely cause you headache while debugging.Instead we can write as follows –

2.Use named functions instead of anonymous functions for callback.
Let’s take same example again

Here we are using anonymous function for callback , instead we can use named functions like below.

This will surely help to avoid nested code.
3) Never hard code anything
Make use of config, it may come from file or database. Ideally all urls,ips that you will require in your code should come from some config db document.
In short, write code in such way that you don’t need to change it with environment.

4) Make use of es6 destructuring
Es 6 destructuring is really good feature you should surely make use of that.
Look at following code difference before and after destructuring.
Before –

After –

Much cleaner isn’t it?

5)Use es6 destructuring while parameter passing
There are some cases when you want to call a particular function with some number of arguments.
Like –

In function definition if you need to access this params you must remember the sequence of arguements.
Instead we can pass an object to a function and then we can use destructuring in definition so that we don’t need to worry about their sequence.
E.g –

6) Avoid nesting of code
If you are using callbacks within callbacks then at one point code becomes really hard to debug. So you can do either of following things.
i) Use Promises. — It will remove nesting from your code
ii) Modularize code — Refer point 2 for this.
iii)Use async/await

7) You must use async/await at least for background jobs(eg. scripts)
async/await is really good feature it makes your code very neat, as it will run our program synchronously you will not have to worry about callbacks or errors.
Actually I don’t know about it’s performance as compared to normal node.js code but in case of background jobs where time is not an important factor, you should use it.
There is good article I found about this –

Do comment if you feel I’ve made a mistake or if you want to add something.

Share post-