On
NodeJS Best Practices

In this post, we will look into some NodeJS Best Practices, as we know that Node.js, a platform built on Chrome’s JavaScript engine helps to develop fast, scalable network application. It uses an event-driven, non-blocking I/O model which makes node.js lightweight and efficient. Node.js has become one of the most popular platforms over the last couple of years.

Let us look at a few of the best Node.js practices that can protect you from the common Node.js traps:
1. There should be one config.json file for all the globals(environment variables) we use like SQL password, username, mail account credentials, etc. This should be encrypted so that no one can get info from git and file.
2. Separate server and routes(app.js) code.
3. Create message (language) file and data models.
4. Error handling using try catch and process.on for uncaughtException.
5. Errors: Always return an error string with Standard (HTTP) error code.
6. Response structure should be changed like {status: true/false, data {}, message: ''}
7. Keep lines shorter than 130 characters.
8. Keep your functions short.
A good function fits on a slide that the people in the last row of a big room can comfortably read.
So don't count on them having perfect vision and limit yourself to ~30 lines of code per function.

9. Curly braces belong on the same line as the thing that necessitates them.
/* Bad: */
function ()
{
 //Some stuff
}

/*Good: */
function () {
//Some stuff
}

10. Choosing Wisely Among Event Handler And Callback. Generally, developers are confused which is better to use, event handler or callback?
Usually, developers face a dilemma that when an event is executing a function on success or failure of a process then why not use callback?
Let us have a deep discussion on Callbacks and Event Handlers.

(a) Callbacks
Callbacks are used when you have an asynchronous operation which needs caller a notification about its’ completion.
function greeting(name) {
  alert('Hello ' + name);
}
function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}
processUserInput(greeting);

The above example is an asynchronous callback, as it is executed immediately.
Note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. A good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. This structure is used in many modern web APIs, such as fetch().

(b)- Event Handler
An event handler is a type of callback. The event handler is called whenever an event occurs. Such phrase of the event handler is normally used in terms of user interfaces where events are like clicking somethings, moving the mouse and so on.
A callback is a procedure which you pass as an argument to another procedure. An event handler is a procedure which is called when an event happens. Such an event can be a callback also. The events and callback can be comprehended in a better way.

Events – Think of a Server (as Employee) and Client (as Boss). One Employee can have many Bosses. Whenever a task is finished, the employee raises the event and the bosses may decide to listen to the employee event or not. Here the employee is the publisher and the bosses are a subscriber.

Callback – Here in the callback, the Boss specifically asks an employee to do a task and once the task is done, the Boss wants to be notified. In this employee, must make sure that once the task is done, he notifies only to the boss who requested, not necessary all the bosses. The employee will not notify the boss if the job is partially done. If only one boss has requested the information an employee will post a reply to one boss only and the notification is sent to the boss only when all the task is done.
Therefore, after having a clear understanding of event and callback, developers must decide wisely which to use when.

11. Use named functions. They make stack traces a lot easier to read.
12. Trailing whitespace
13. Quotes
Use single quotes, unless you are writing JSON
/* Right: */
var foo = 'bar';

/* Wrong: */
var foo = "bar";

14. Variable declarations
Declare one variable per var statement, it makes it easier to re-order the lines. Ignore Crockford on this, and put those declarations wherever they make sense.
/* Right: */
var keys = ['foo', 'bar'];
var values = [23, 42];

var object = {};
while (keys.length) {
var key = keys.pop();
object[key] = values.pop();
}

/* Wrong: */
var keys = ['foo', 'bar'],
values = [23, 42],
object = {},
key;

while (keys.length) {
key = keys.pop();
object[key] = values.pop();
}

15. Case, naming, etc.
Use lowerCamelCase for multiword identifiers when they refer to functions, methods, properties, or anything not specified in this section.
Use UpperCamelCase for class names (things that you'd pass to "new").
Use all-lower-hyphen-css-case for multiword filenames and config keys.
Use CAPS_SNAKE_CASE for constants, things that should never change and are rarely used.

16. null, undefined, false, 0
Boolean variables and functions should always be either true or false. Don't set it to 0 unless it's supposed to be a number.
When something is intentionally missing or removed, set it to null.
Don't set things to undefined. Reserve that value to mean "not yet set to anything."

17. Avoid console.log().
18. Conditions
Any non-trivial conditions should be assigned to a descriptive variable:
Right:
var isAuthorized = (user.isAdmin() || user.isModerator());
if (isAuthorized) {
 console.log('winning');
}

Wrong:
if (user.isAdmin() || user.isModerator()) {
 console.log('losing');
}

19. To avoid deep nesting of if-statements, always return a function's value as early as possible.
Right:

function isPercentage(val) {
 if (val < 0) {
  return false;
 }
 if (val > 100) {
  return false;
 }
 return true;
}

Wrong:
function isPercentage(val) {
 if (val >= 0) {
 if (val < 100) {
 return true;
} else {
 return false;
}
} else {
return false;
}
}

20. Named closures
Feel free to give your closures a name. It shows that you care about them, and will produce better stack traces:
Right:
req.on('end', function onEnd() {
 console.log('winning');
});

Wrong:
req.on('end', function() {
 console.log('losing');
});

21. Automatic Restart Of node.js Application.
Even after following all the best practices of handling errors there could be a chance some error may bring your application down. This is where it is important to ensure you must use a process manager to make sure the application recovers gracefully from a runtime error.
The other scenario is when you need to restart it, is when the entire server you are running on went down. In that situation, you want minimal downtime and for your node.js application to restart as soon as the server is alive again!

Under this here are a few Node JS development tools

Gulp
A toolkit which allows launching several apps simultaneously. It might be useful if you’d like to run several services at the same time with one command/request.

Nodemon
Hot reload feature for Node.js. This tool automatically updates/ resets your project after any code change is made. A quite handy tool during the  Node.js project architecture development.

Forever,  pm2
These two packages ensure the app’s launch during the (OC) system’s start.

Winston
Provides with the opportunity to record app’s logs to the primary source (file or database). The package comes to help when you need the app to work remotely and don’t have the full access to it.

Threads
A tool designed for better work with threads.


22. Testing Is Crucial
On production applications, it is quite critical to get notified if something goes wrong. It could happen that you do not want to check your feeds and thousands of angry users tells you that your server is down and your node.js application is broken since last few hours.
Hence, it is imperative to tool for alerting you for your critical behavior. Some of the best performance monitoring tools for node.js are Loggly and NewRelic. Developers must have handy tools for monitoring the performance of node.js applications.