Site Search

Node.Js Development Tips for Newbie to Expert Developers

  • Pratip Biswas
  • Aug 01,2014
  • 8 minutes read
Table of contents

Node.Js is the hottest trend in the tech realm, giving developers a choice of 35,000 modules to browse. Users say Node is too easy to develop a working application, which can balance without trouble. The fan base of Node.Js has started to spread their rhetoric like religion. Let us check out what makes it distinctive.

What is Node.js?

Wikipedia says, “Node.js is a packaged compilation of Google’s V8 JavaScript engine, the libuv platform abstraction layer, and a core library, which is itself primarily written in JavaScript. Used in server side coding, handling AJAX requests, maintaining routes for different APIs and manipulating database.”

How Node.js works?
Ryan Dahl, creator of Node.js was aiming to create real-time websites with push capability, inspired by applications like Gmail. So there he comes with Node.js. In the Node.js, he gave developers a tool for working in the non-blocking, event-driven I/O paradigm.

We know, in web browsers developers are restricted to use language as they have to provide security to the user. Usually in such cases, all activities aim at DOM-manipulation and asynchronous page info loading.

Here, Node.js opens up opportunity for new perspectives retaining its browser nature.

  • 1.What in Node.js developers find easy and compatible with their jobs?
  • 2.What the experts have learned over the year?
  • 3.What mistakes newbie must avoid?

Well, with time experts have become aware of various tips and tricks that can benefit both – a newbie and expert. Let us share some of those benefits to help you recap or start fresh.

    1. Node.js: It is Asynchronous

A distinguishing feature of Node.js is that it is single-threaded, designed and implemented as asynchronous from top to bottom. More than 60% of the developers have faced problems due to this asynchronous property, but today most of them person knows the solution. When you a run a time-consuming job such as accessing the database, use a counter to keep track of the loop, or else before completing the loop the next function would commence.
Bad luck exists, as it is still possible to make synchronous/blocking calls. Well, many file systems have both asynchronous and synchronous versions, such as writeFile and writeFileSync. Even if you avoid the asynchronous method in your code, it is possible to exist in an external library that has blocking call.

Look here –
GOOD PRACTICE: Write Files Asynchronously
1| fs.writeFile(‘message.txt’, ‘Hello Node’, function (err) {
2| console.log(“It’s saved and the server remains responsive!”);
3| });

BAD PRACTICE: Write Files Synchronously
1| fs.writeFileSync(‘message.txt”Hello Node’);
2| console.log(“It’s saved but you just blocked ALL requests!”);

    1. Node.Js: What’s Callback Hell, How to Handle It

What is Callback Hell? – Excessively nested asynchronous callbacks referred as Callback Hell.
It is good to keep nested callbacks to a minimum limit, as it is a simple way to untie your callbacks.

Let us begin with a typical example to explain our point –
1|function register(name, password, cb){
2| checkIfNameExists(name, function(err, result){
3| if(err){
4| return cb(“error”);
5| }
6| checkIfPasswordGood(password, function(err, result){
7| if(err){
8| return cb(“error”);
9| }
10| createAccount(name,password, function(err,result){
11| if(err){
12| return cb(“error”);
13| }
14| createBlog(name, function(err, result){
15| sendEmail(name, function(err, result){
16| callback(result);
17| });
18| });
19| });
20| });
21| });
22| }
You would come across certain asynchronous operations that lead to Callback Hell, its –

      • Chain of Asynchronous Operations: Get something from API, process it with another API and write the result into database.
      • Asynchronous Set Operations: Collection of objects, performs asynchronous operation or some other actions when all operations are complete

And to prevent callback hell you can browse the great libraries such as:

1. Async.js: Allow easy execution of functions in series without nesting them
2. Bluebird: Promises makes asynchronous logic more manageable with mapping and enqueueing
3. Q: Reveals the concept of promise just like bluebird to manage the nested calls effortlessly

    1. Node.Js: Separate Util and Config File

Developers must make it a habit of using util.js file for frequently used functions. Try to acquire this file as a variable in your module. This in turn would reduce the number of global variables and code length. Even can config files that stores constant parameters.
Suppose you require an application to show details of top five students, it can vary and become ten students. So do not be hard with your code limits. Keep it in the config file. One best practice is to maintain a ‘Lang’ folder that is useful for a multilingual application.

As for file acquiring aspect, it is simple in Node.js. You can write,
1| var util = require(‘./util.js’),
2|
3| englishMessages = require(‘./lang/en.js’);

    1. Node.js: Looking at the Monitor Performance

Ask yourself how you could monitor the application performance and profile, as you need to make sure that the app in running at optimum speed. Well, for that you would get some tools like- Nodefly, New relic, etc
Nodefly–A simple line of code that starts to monitor your application to detect memory leaks, or measure how long it takes for redis, to make mongo queries and other stuffs.
New Relic–This tool would help developers to monitor response time to server monitoring in your real-time and data-intensive Node.js application.

    1. Node.Js: Delegate using Granular Modules

You have to work with many tables in Node.js, so it is necessary to split codes. It is better to make different modules for different tables, and to interact with child modules make a separate parent module.
Well, let us demonstrate an example – There are different departments in an office database, 4 to 6 project make a department and number of employees makes a department.

Now you can structure this project with four modules –
a. Employees
b. Projects
c. Department and
d. Office

Here Office is your parent module and rest three is the child. Function of this module is to pass controller to the proper module. Suppose you tried to update the Employee table, for that, you have to update the Projects and Department as well. Do not try to acquire other modules into student module. It is better to pass on the request to Office module, and it would direct the request to preferred module, this would help you to sort code and review errors easily.

    1. Node.Js: Debugging is Easy

If you hail from a language with heavy IDE integration like Java or C#, then debugging Node.js seems to be confusing. Most new Node developers prefer to adopt debugging pattern with the use of console.log. However, you would still get some alternatives, conventional to debugging. Node.js comes with a built-in debugger that runs by calling node debug, like Node Inspector.

Node Inspector– A debugger interface for node.js using the Blink Developer Tools (earlier WebKit Web Inspector). It allows developer to debug the application using any editor and chrome web tools of their choice. With Node-Inspector, developers can do some cool stuff such as live code changing, step debugging, scope injection and other cool aspects. To follow up the aspects find out more at Github.

    1. Node.Js: Be Careful with the New Modules

You would come across more than 35,000 modules in Node.js, but some of them are dead. With Node.js changing their API repeatedly in their major versions, it is confusing to work. The module works under v0.8.x may abort under v0.10.x. Therefore, before you sprang on a new module, you should check the PR List to make sure that it is free of bugs or is it under maintenance.

    1. Node.Js: Node Package Manager is a Marvel

Node Package Manager is the root of all deployment systems for Node.js, underlying the PaaS (Platform-as-a-Service) providers eases out management of library dependencies. Node comes with amazing npm that installs modules specified min your package.json manifest file. Well, in such an instance newbie’s keeps the package.json updated with all modules they use. It painful to open the package and update dependencies property with new modules every time, but npm does this for you!

Therefore, it is better to run the npm install, save a module name, and in turn, npm would automatically update the package.json with correct module and version name.

    1. Node.js: Be Careful About Errors

For newbie’s, it is important to remember that node can crash easily for a single error. Therefore, it is our suggestion to the newbie and the experts to handle errors properly and throw a proper message against it. Use of try-catch box slows your process, so avoid it.

    1. Node.js: Do Not Forget to Return

Most of the beginners forget to return after a callback. While sometimes this has no implication at all, but there are times when you run into odd issues because you might get a callback twice.

Let us see an example for it –
1| function do(err,result, callback){
2| if(err){
3| callback(“error”);
4| }
5| callback(“good”);
6| }

The snippet does make a sense. If you find an “error”, send in the callback, if not send good. However, calling for the callback is not a good way to stop from completing the execution, it would move on to calling callback.

Node.js: Conclusion
Often today, we get down creating real-time applications with the use of Node.js. You must be looking for their future use in certain projects such as APIs or networking projects, for them Node.js is going to prove as a great model of deployment. With their, pre-formatted asynchronous code and use of language that is easy to pick, Node.js is a sheer popular choice.


icon

Pratip Biswas

Founder & CEO, Unified Infotech

"Pratip Biswas, founder and CEO of Unified Infotech, has driven the company to become a leader in next-gen digital transformation. He has a deep-rooted passion for technology and innovation. With his visionary approach and expertise, he has been transforming ideas into reality for entrepreneurs and businesses.”