Sysleaf

Introduction to Node.JS & how it differ from Browser's JS

. .
Introduction to Node.JS & how it differ from Browser's JS

Introduction

Javascript is a powerful dynamic, functional, and object-oriented language. It is very popular language because it is very easy to learn and understand. But for many years, Javascript has run only in the browser and for the same reason, Javascript has been used only for a client-side browser application. Had you ever dreamed to write a server-side application using your favorite language ‘Javascript’? If yes, then your dream comes true.

Thanks to Node.Js, now we can run our Javascript code outside the browser. Node.JS enable us to write a server-side application using Javascript. Language like PHP, Java, Python, etc has always been used for server-side application, now Javascript also joins this list. Think of Node.JS as a browser: Browser run Javascript code on client-side(front-end) while Node.JS run Javascript code on server-side(back-end).

Please note, Node.JS is not a language, it’s runtime that can understand & run code written in Javascript language.

So, Node.JS is a Javascript runtime which is used for creating a server-side application. In contrast, Browser is also javascript runtime but it is used for creating a client-side application.

Browser JS vs Node.JS JS

So we know that Node.JS is some kind of platform (which internally uses Chrome v8 engine) where we can run our Javascript code but is there any difference between “Browser-side Javascript” and “Node.JS-side Javascript”?

Yes. Javascript core feature and API(like syntax, object, function etc) will always be same in Node.JS and Browser. But there will be some API which will be available in Browser but not in Node.JS and vice-versa.

API available in Browser but not in Node.JS: for example, DOM manipulation related API like document.getElementById(), document.createElement(), etc will not available in Node.JS because Node.JS is server side technology and we don’t need HTML DOM related thing in server side.

API available in Node.JS but not in Browser.JS: for example, API to create HTTP & TCP server: http.createServer() and net.createServer will not be available in Browser because we don’t create a server in the browser.

How to Use Node.JS?

We know how to run Javascript code in Browser but how do we run it in Node.JS? Well! that is what we will see in this section.

Steps to Run:

  1. Install Node.JS in your system: the first step is to download an appropriate Node.JS binary from Node.JS Website and install it on your machine. To check if Node.JS successfully installed: open your command line terminal, type command node -v and hit the enter key, it should show some version, like v8.0.0.
  2. Write some sample Javascript code in a file: Let’s write simple add function as shown below and save it in a file called ‘add.js’.
    //add.js
    
    function add(x, y) {
      var result = x + y;
      console.log(x + "+" + y + "=" + result);
    }
    
    add(1, 2);
    
  3. Run above Javascript file using Node.JS: Now open the terminal and go to the folder where you saved above file ‘add.js’. Here in terminal type command node add.js then hit enter. Once you hit enter, Node.JS will start executing Javascript file add.js and soon you will see the output(console message) on your screen.

Module System

The module is a way to organize our code in a different unit, each unit being independent contain codes which are similar in functionality. Modules make our code portable and reusable. Every language has some sort of module concept. for example: In Java, input/output related API is put in java.io; In C, input/output related API is put in stdio.h.

Similarly, Node.JS also has a concept of module system. For example, File related API is put in fs module; HTTP related API is put in http module. There are two types of module in Node.JS: Internal and External.

Using Internal Module

To use any API of module, we first need to import that module. Every language has its own syntax to import module. For example, to import input/output related module: In Java, we use import java.io.*; In C, we use #include <stdio.h>.

Similarly, in Node.JS, we use require('module name') to import any module. Let’s take an example: Suppose we want print CPU model of a machine using Javascript. To do this we need to take help of Node.JS os module. See below code on how to import and use this module. If you run below code on your machine, it will print the CPU model of your machine.

var os = require('os');

function printCPUModel() {
  var cpus = os.cpus();
  console.log(cpus[0].model);
  //print 'Intel(R) Core(TM) i5-5250U CPU @ 1.60GHz' on my machine
}

printCPUModel();

Using External Module

Internal(inbuilt) module will always contain the core API. If you are looking for an API which is not available in Node.JS inbuilt module then you can look for an external module. External Module is written by the third party like me or you. For example: suppose we want to write an application that will calculate the loan interest of given amount, rate, and termMonths. For this, we can write the whole logic by our own but we will use the external module called loan-calc.

  1. Install the module: To install any external module use command npm install module-name. In our example, we will use npm install loan-calc. NPM is a ‘node package manager’ which comes preinstalled with Node.JS. To keep this article simple, we will not much discuss NPM.
  2. Use the module: After installing the module, simply require it like the inbuilt module. See below code on how to do this.
    var LoanCalc = require('loan-calc');
    var interest = LoanCalc.totalInterest({amount: 200000, rate: 5, termMonths: 360});
    console.log('your interest is: ', interest);
    

Creating Custom Module

We know the advantage of a module, we can create our own module in Node.JS. Once we create a module, we use it like other module using require('module file') syntax. The module in Node.JS is file-based, every file in Node.JS is treated as a module but by default, none of the code in that file is exported, they are private to their file.

If we want to reuse some of the code of that file into another file then we have to explicitly export those code using module.exports. By word ‘code’ we mean function, object, variable, or any shareable entity.

Let’s take an example: suppose we want to create our own module for logging system. Our module will be simple. Our logging module will have two method info() and error() which will print its respective message. See below code on how to do this. Notice how have attached logger object to module.exports using module.exports = logger. Also notice in ‘usage tab’, how we are importing our custom module by passing the location of module file.

  • // logger.js
    
    var logger = {
      info: function(msg){
        console.log(msg);
      },
      error: function(error){
        console.log(error);
      }
    }
    module.exports = logger;
    
  • // add.js
    var logger = require('./logger');
    
    function add(x, y) {
      if(x && y){
        var result = x + y;
        logger.info(x + "+" + y + "=" + result);
      }else{
        logger.error('please pass valid value for x and y');
      }
      
    }
    
    add(1, 2);