Skip to main content

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,

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 definition of Event handler is “asynchronous callback subroutine that handles inputs received in a program”. That means Event handler is a very specific case of callback. For more about Event and callback and when to use which visit this link.

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:

Comments

Popular posts from this blog

UpComing Features in PHP 5.3

Namespaces A subject touched and trialed many times in PHP, namespaces. This feature has been responsible for the longest discussions on PHP-DEV, but finally a consensus has arrived on how this is going to work. The biggest benefit namespaces will provide is shortening of long classnames. To make sure that your class libraries can plug into foreign code, it has always been recommended to prefix your classes, for example "Zend_DB_Connection". This can however lead to very long names. Namespaces fixes this by grouping classes together. The full-on classname becomes Zend::DB:Connection, and by placing 'use Zend::DB' on top of your code, the 'Connection' class can be referenced with just that name. Example: // The class file namespace Zend :: DB ; class Connection { function foo () { echo 'bar' ; } } ?> require 'Zend/DB/Connection.php' ; use Zend :: DB :: Connection ; $connection = new Connection (); $connection -> foo (); ?

Install PHP 5.3.0/Lighttpd On Debian (Lenny) With Imap, MySQL, Sqlite3 And ImageMagick Support

Install PHP 5.3.0/Lighttpd On Debian (Lenny) With Imap, MySQL, Sqlite3 And ImageMagick Support This tutorial covers the setup of PHP 5.3.0/Lighttpd on Debian (lenny) with imap, mysql, mysqli, sqlite3, ImageMagick and mycrypt support. For this tutorial I will assume you are logged in as root this is not advised. First we need to install the webserver: aptitude install lighttpd Now we install the packages needed for mysql and mysqli support. You will be promoted to enter a mysql root password - please use a strong password. aptitude install mysql-server mysql-client libmysqlclient15-dev Next install some packages php needs to compile. aptitude install libtidy-dev curl libcurl4-openssl-dev libcurl3 libcurl3-gnutls zlib1g zlib1g-dev libxslt1-dev libzip-dev libzip1 libxml2 libsnmp-base libsnmp15 libxml2-dev libsnmp-dev libjpeg62 libjpeg62-dev libpng12-0 libpng12-dev zlib1g zlib1g-dev libfreetype6 libfreetype6-dev libbz2-dev libxpm-dev libmcrypt-dev libmcrypt4 sqlite3 bzip2 build-essential l

Zend Framework WebServices

REST Web Services use service-specific XML formats. These ad-hoc standards mean that the manner for accessing a REST web service is different for each service. REST web services typically use URL parameters (GET data) or path information for requesting data and POST data for sending data. Zend Framework provides both Client and Server capabilities, which, when used together allow for a much more "local" interface experience via virtual object property access. The Server component features automatic exposition of functions and classes using a meaningful and simple XML format. When accessing these services using the Client, it is possible to easily retrieve the return data from the remote call. Should you wish to use the client with a non-Zend_Rest_Server based service, it will still provide easier data access. In addition to Zend_Rest_Server and