On more post in our series about Node.JS . This time, we will bring you some best practices we use here at Vizir.If those, we avoid failing in some traps and do better JavaScript codes.

Have a code pattern

An old man would say “better a bad pattern, than no pattern”. So, use a Linter and a Cody Style Checker. We recommend ESLint.

If you don’t have any code style pattern, the Airbnb pattern is a good reference. Already have a package that set your ESLint automatically with Airbnb pattern.

Don’t forget to set your IDE for warning your errors during the codification. This can be done installing plugins for ESLint that exist at IDEs most used. Besides that, add the automatic static check for your Git process using a hook or through a npm task.

It will be nice to have a basic .editorconfig at the root of your application. Believe, this will help a lot you to avoid that git diffs that have only spacing, removing or adding just one new line at the end of the file.

ECMAScript 2015 is your friend

With all new functionalities at ES2015 JavaScript, you can write better code and most part is already native supported by the V8 engine.

Some interesting functionalities:

  • Classes;
  • Template Strings;
  • Promises;
  • Default Parameters.

In case you’re coding to the browser, Babel is a great transpiler to codify your JavaScript in ECMAScript 2015 for older browsers.

To finish ECMAScript 2015 subject, you can find a great overview here.

Avoid unnecessary Libs

Use the excellent anvaka to compare what lib you will add to your project. With it, you will be able to see how many dependencies your project will have. Remember: After you add one dependency, your are responsible for it.

Choose libs that have little dependencies and avoid to add libs that could easily be implemented in your code. Like the is-array.

Don’t let your README in blank

README is the “starting point” of your project and because of this, write it carefully. Keep in mind what you would like to know at the beginning of the project. There are some references to help you to decide what to add to your README.

Have an intuitive directory structure

When we begin a new project, we face ourselves with one directory with just a package.JSON file. At this moment is very important to define an intuitive directory structure that will help new developers to understand easily what is going on.

It’s recommended the use of a pattern structure (boilerplate) for applications that have similars objects.

Take advantage of npm power

Always start a new project using the command `npm init` and use npm pattern test scripts (`npm test`) and to start your application (`npm start`).

A new developer should be able to run your project by running `npm install & npm start`.

Wrappers

It’s very easy to lose yourself and start to spreading out modules dependencies installed via npm for all your application. To avoid this to happen, create wrappers of this libs when it is possible. This will make easy to change if this will be necessary one day.

Virtualize the development environment

This is the must valuable best practice. Mostly if your project needed more than Node.JS dependency and use the database, cache database etc. resources. Begin your project with a Vagrant configures or, even better, a Docker.

At the Node.JSdocumentation eit has a guide to set a Docker for your application.

Be careful with Event Emitter errors

We will always have errors. It’s up to you fix it. A good way to start is to read this article from StrongLoop.

The errors that occur at Event Emitter can break your application:

const EventEmitter = require('events');
const observable = new EventEmitter;

observable.emit('error', new Error('Catch me!'));

$ node index.js
events.js:141
 throw er; // Unhandled ‘error’ event
 ^

Error: Catch me!
 at Object. (/home/workspace/example.js:4:26)
 ...

That’s why we should treat errors with affection.

const EventEmitter = require('events');
const observable = new EventEmitter;

observable.on('error', (error) => console.log(error.message));

observable.emit('error', new Error('Catch me!'));

$ node index.js
Catch me!

Watch out and avoid to use “this”, “bind”, “call”…

Another JavaScript best practices.

Change objects this with bind/call is powerful and dangerous at the same time. Before you use, see if is really necessary.

Prefer to use pure objects when you don’t need to store object status.

One of the most common errors is presented in this video:

Clusters

We know that Node.JS use only one thread. So it will not take advantage of additional machine cores.

However, it’s possible to create process forks. Either by Node.JS API, or using an abstraction like throng. Use PM2 in production.

Simplify your code

Avoid abstractions and necessary layers in your application. Once more, think carefully before adding an abstraction/layer and talk to your team. After all, this is the kind of decision that is better taken by all involved.

Use async and lodash

Async is one of most used libs and will help you to avoid the callback hell. Lodash have a lot of useful functions that bring better reading for your code and more productivity.

Don’t go to the callback hell

Seeing that you are entering at callback hell, stop, breathe and think how to avoid it. Suddenly just changing the approach that you are using is enough to prevent. Others the use of Async can help. Also, learn how to use Promises or Generators.

Monitoring tool

A monitoring tool is very important for you to know the usage level of CPU, load, and memory. This tools also can help to tell you if errors are happening frequently in your applications and send alerts.

Good tools: Keymetrics, dfor the same people of PM2, and the New Relic.

Log, log, log!

Seriously! Use logs in your application. This was one of the hardest lessons we learned working with Node.JS.

A good lib to this is Winston.

Test your code

Another tip for any technology. Testing is the art to make sure that your software will have a peaceful life. After all, the life of a software is full of updates and, for wich one, you have to ensure that what you had before works smoothly.

For this one, use the Jasminelib.

New loops special powers

One of the most common cases in loops is that for iterate in one array. But there are much cleaner ways to work with arrays.

We hope that this best practices will be useful for yours. Enjoy to send us your tips and best practices.