10 Node.js best practices you should follow

Node.js is a platform built on Chrome’s JavaScript engine (i.e. v8 JavaScript Engine); it helps to develop fast, scalable network application. It is basically used in server side coding, handling AJAX requests, maintaining routes for different APIs and manipulating database. Node.js uses an event-driven, non blocking I/O model that makes it lightweight and efficient. Now without defining v8 the blog will remain incomplete. v8 is Google’s open source JavaScript engine which is written in C++. Best feature of v8 is: it can run independently, or can be embedded into any C++ application.

Let’s come to the main topic; here are the Node.js best practices:

1. Learn the best practices of JavaScript first:

Before starting Node.js you should learn the best practices of JavaScript first. It will make your code more decent and flexible. There is a statement code lovers always use, “A fool can write codes which only machines can understand”. So, my suggestion is follow the guidelines to make your code understandable to others.

2. Remember Node.js is Asynchronous:

I’m sure more than 60% developers faced problem for its asynchronous property, and I’m sure too that everybody knows the solution. When you are running a time consuming job like accessing database or forEach function use counter to keep track of the loop, else before completing the loop the next function will start.

3. Use library functions:

Sometimes, you need to manipulate array, object and collections because of app requirement. It will be helpful for you to use Underscore.js. This is a very interesting and useful tool.

4. Make separate util and config file:

Make a habit of using util.js file. Frequently used functions should be written in util.js file. Acquire this file as a variable in your module; this will reduce number of global variables and code length.

Also make a config file which stores your constant parameters. Suppose, the application needs to show the details of top five students. It can be increased to ten tomorrow. So, don’t hard code the limit value. Keep it in config file.

One more best practice is to maintain a ‘lang’ folder. It is useful for multilingual application.

File acquiring is simple in Node.js. You can write,

var util = require(‘./util.js’),

     englishMessages = require(‘./lang/en.js’);

5. Function structure:

When you write a function in Node.js, remember three points :-

  • Error should be the first parameter.

  • Callback should be the last parameter.

  • Be sure to use ‘return’ statement.

6. Make granular modules as much as you can:

Always try to split up your code. While using Node.js you might be working with many tables. I  suggest making different modules for different table. And make another parent module to interact within the child modules.

For Example, there are several standards in a school’s database, 3 to 5 sections make a standard and many students make a section. So, you can structure this project with four modules.

a. Student

b. Section

c. Standard and,

d. School.

Here School is the parent module and other three are child modules. The only function of school module is to pass the controller to the proper module. Suppose you are trying to update a student’s table and for that you need to update section and standard table both. Don’t acquire other modules into student module. Pass the request to School module, and then school module will transfer the request to the preferred module. It will help you to sort up your code and will make it  easy to review when error occurs.

Node.js module structure.

7. Handle errors properly:

This point is very useful for the beginners. You should keep in mind that your node can crash for one unhandled error. So, my suggestion is to handle all the error properly, and throws them with proper message. Use of try-catch block will slow your process. So, try to avoid it. And one more thing, using process.on(‘uncaughtException’) is a bad habit. It will protect your node from crashing, but the error will remain unhandled.

8. npm – a blessing:

npm is like a blessing to the Node.js developers. Speaking of managing library dependencies, the Node Package Manager deserves to be called out. Node Package Manager is the root of almost all deployment systems for Node.js. It underlies the many PaaS (Platform-as-a-Service) providers for Node.js. Its simple, dependable package management has let the Node ecosystem grow extremely well in recent time, to the point that the underlying public service now needs to scale to the next level. 62,961 npms are there till date; they can help you to do interesting stuff and keeps your code simple.

9. Event handler v/s Callback:

This is a common question comes from all the developers. The answer is: it is better to use event handler than callback. Developers often ask when an event is executing a function on success/failure of a process then why not we use callback?  I’m trying to give a simple answer.

According to wikipedia, Callback is “executable code that is passed as an argument to other code”. And the definition of the Event handler is “asynchronous callback subroutine that handles inputs received in a program”. That means Event handler is a very specific case of a callback.

10. Use of events module:

Use node’s events module, which is the part of the Node.js core. Node.js ships with a simple EventEmitter class that can be included from the ‘events’ module. Simple way to implement events in node is by encapsulating the event.

 For eaxmple:

var events = require('events'),

myEventEmitter = new events.EventEmitter();

var ringBell = function ringBell() {

   console.log('ring ring ring');


myEventEmitter.on('doorOpen', ringBell);