Wednesday, 12 February 2020

node JS


Node JS

Node JS is a server side platform build up on Google chrome JavaScript Engine (V8 Engine) which was developed by Ryan Dahl in 2009. The official node JS document provides definition of node JS document provides definition of node JS is as follow.
à Node JS is a platform build on V8 engine for easily building fast and scalable applications.
à Node JS uses non-blocking, asynchronous event driven IO modules which makes it efficient and light weight. Node JS perfect for single page data incentive real time applications that run across distributed devices.
à Node JS is an open source cross platform server side runtime environment for developing network applications.
à Node JS applications are written in JavaScript and can be run with in the Node JS runtime or run any OS like Windows, Linux, Mac etc.
à Node JS also provides rich libraries for various JavaScript modules which simplifies the development of web application.
Node JS= Runtime Environment + JavaScript libraries.

Features of Node JS:
à Single thread and light weight.
à Asynchronous and Event driven.
à Very fast and no buffering.
à Open source and Licensed.
Open Source – Is nothing but we can add some predefined functions/modules to use developing.

Event Driven Programming/Method:
Node JS is a single thread application but it support concurrency (executing at same time) via concept of events and call backs every API of Node JS is asynchronous and being single thread they use asynchronous function calls to maintain concurrency and Node JS uses observer pattern.
Node JS uses events heavily this is also one reason for pretty faster than other technologies. Event driven uses observer pattern that means a Node JS application starts its server then all the variables and functions get initiated and they are ready/waiting for events.

                                                                                    
Text Box: Event driven                                                                                          
                                                                       Event                          Event
                                          Events                    loop                         Handlers

Events Driven has a main event loop which is used to organize all events by this we can implements asynchronous programming style and callbacks also very essential for implement asynchronous style callbacks are called when the function is written and callback is nothing but a function contains another function as parameter or function.

Example for callback function:
Example-1
Synchronous callback function

function a (x,callback){
    let b=x/10;
    callback(b);
}
a(1000,(b)=>{
    console.log(b);
});
Output: 100

Example-2
Asynchronous callback function

function a (){
    console.log(123);
}
function b (){
    console.log(321);
}
setTimeout(()=>{
    a();
},500);
b();

Output: 321
123

In the above examples we observe that in Example-1, we didn’t use any pre-defined asynchronous function that’s why the execution flow of Example -1 is like synchronous.
We observe that in Example-2, we used pre-defined asynchronous function that’s why the execution flow of Example -2 is like asynchronous.

Importing/ using predefine modules in Node JS:
Working with Node JS file system:
Node JS provides a predefine module called filesystem (fs) with the help of this module or by importing this module we can perform different actions on filesystem like Reading a file,
Creating a file, Update a file, Delete a file.
In order to perform above modules like this
const file=require('fs');

Note: In the above line we used ‘const’ it is fixed (don’t change).
We can use let, var in ‘const’ place use var the value is changed means not fixed.
Here require('') is used for importing modules in Node JS.

To create a file:
In Node JS to create a file we use writeFile('') asynchronous function.
Write File:
const file=require('fs');
file.writeFile('aa.txt','Hi.',(error)=>
{
    if(error) throw error;
})

Read File:
const file=require('fs');
file.readFile('aa.txt',(error,data)=>
        {
              if(error) {
                console.log(error);
               }else{
                  console.log(data.toString())
               }      
        }) 

Update File:
const file=require('fs');
file. appendFile ('aa.txt', 'Welcome', (error)=>
        {
              if(error) throw error;
                console.log('Updated');   
        }) 

Delete File:
const file=require('fs');
file. unlink('aa.txt',(error)=>
        {
              if(error) throw error;
                console.log('Deleted');   
        }) 

Example File:
const file=require('fs');
// file.writeFile('aa.txt','Hi.',(error)=>
// {
//     if(error) throw error;
// })
////Output:- Hi.
file.readFile('aa.txt',(error,data)=>
{
      if(error) {
        console.log(error)
       }
       else{
        console.log(data.toString())
       }      
}) 
file.appendFile('aa.txt','Node JS',(error)=>
        {
              if(error) {
                console.log(error)
       }
       else{
        console.log('Updated')
       }  
    }) 

Output:
1st time: Updated
               Hi.
But in aa.txt file test is: - Hi.Node JS
2nd time: Updated
                Hi.Node JS
But in aa.txt file test is: - Hi.Node JSNode JS
3rd time: Updated
               Hi.Node JSNode JS
But in aa.txt file test is: - Hi.Node JSNode JSNode JS

Web Server (or) http Server:
Web server/http servers are helpful to provide http services or handle http client service request by providing response generally a web application contain 4  layers
(1) Client layer
(2) Server layer
(3) Business layer
(4) Data layer

Text Box: DB,
File System,
Cloud
Text Box: Logic
(or)
Program
(or)
API’s

Text Box: Browser (or)
Postman
(or)
Application
            Client                        Server                            Business                      Data
 





To create web server/http server in Node JS:
In Node JS in order to create a web server we have to import a module called http like below
const http=require ('http');

Here http is a constant variable which is used for hold http module object and also we used require method for importing node modules here http after that we have to create a server and we have to assign a port for listening the server in order to do this we have to use “createserver()” and “listen()”.
Applying/Using to create server:
const server=http.createServer((req,res)=>
{
res.end("Welcome")
});
Here “server” is the server object.

Assigning/Add port to server:
server.listen('8080',()=>
{
    console.log('server started at 8080 port');
})
Here 8080 is the port number of server.
const http=require('http');
const server=http.createServer((req,res)=>
{
res.end("Welcome")
});
server.listen('8080',()=>
{
    console.log('server started at 8080 port');
})

In the above example “createServer” and “listen” are predefine functions (asynchronous function) every asynchronous function contain callback functions.
In “createServer” function we used a callback function with two parameters req, res (request and response).
Which are helpful to handle the httpreq and httpres.
const xyz=require('http');
const file=require('fs');
const server=http.cretaeServer((req,res)=>{
    if(req.method=='GET' && req.url=='/hi')
    {
        file.readFile('A.txt',(error,data)=>{
           if(error)
                   {
                    res.end(error)
                    }
                    else{
                        res.end(data.toString());
                    }
        });
    }
    else if(req.method=='GET' && req.url=='/hello')
    {
        file.readFile('B.txt',(error,data)=>{
            if(error)
                    {
                     res.end(error)
                     }
                     else{
                         res.end(data.toString());
                     }
         });
    }
    else{
        res.end('Node JS');
    }
});
server.listen('8080',()=>
{
    console.log('server started at 8080 port');
})
Note: Click terminalàSelect Open newTerminal
PS C:\Users\Desktop\Node JS> node c.js 

Here we used “req.method” for knowing type of httptype and we used “req.url” to know (or) get the end point.
We can request only GET http request without application with browser it is impossible to req to other kind of http request/services. So, that we need a fake application to do other request for this purpose we are using postman web/http client.

Handling GET, POST, PUT and DELETE request with Postman:

c.js:-
const http=require('http');
const filesystem=require('fs');
const server=http.createServer((req,res)=>{
    if(req.method=='POST' && req.url=='/writeFileA')
    {
        filesystem.writeFile('A.txt','Hi Welcome A',(error)=>
        {
           if(error) {
            res.end(error)
           }
           else{
            filesystem.readFile('A.txt',(error,data)=>
            {
                  if(error) {
                    res.end(error)
                   }
                   else{
                       res.end(data.toString())
                   }      
            })   
           }      
        })
    }
    else if(req.method=='GET' && req.url=='/writeFileA')
    {
        filesystem.readFile('A.txt',(error,data)=>
        {
              if(error) {
                res.end(error)
               }
               else{
                   res.end(data.toString())
               }      
        })   
    }
  
    else if(req.method=='PUT' && req.url=='/writeFileA')
    {
        filesystem.appendFile('A.txt','Node JS',(error)=>
        {
              if(error) {
                res.end(error)
               }
               else{
           
                filesystem.readFile('A.txt',(error,data)=>
                {
                      if(error) {
                        res.end(error)
                       }
                       else{
                           res.end(data.toString())
                       }      
                })   
               }      
        })   
    }
   
    else if(req.method=='DELETE' && req.url=='/writeFileA')
    {
        filesystem.writeFile('A.txt','',(error)=>
        {
              if(error) {
                res.end(error)
               }
               else{
                filesystem.readFile('A.txt',(error,data)=>
                {
                      if(error) {
                        res.end(error)
                       }
                       else{
                           res.end(data.toString())
                       }      
                })   
               }      
        })   
    }
   
    else{
        res.end('You are entered bad url')
    }
})
server.listen('8080',()=>
{
    console.log('server started at 8080 port');
})

Note: Click terminalàSelect Open newTerminal
PS C:\Users\Desktop\Node JS> node c.js 
server started at 8080 port
||

Output:-

Description: C:\Users\ANIL BABU\Pictures\Screenshots\Screenshot (204).png

Web Services:
à Web service is a technology or concept or software.
à Web services are used for to transfer data between two or more applications, which are written in same or different technologies.
à Web services are independent data format transformers.
à Web services are mainly 2 types that mean we can transfer data between 2 applications with 2 technologies/ways.
(1) SOAP – Simple Object Access Protocol.
(2) RESTful Services -- REpresentational State Transfer.

In SOAP communication or services used XML data format to transfer the data.
In RESTful Services uses JSON data format to transfer the data.
The main use of services transfer data between different applications and developed in different technologies.
 













REST API’s:
REST API’s uses RESTful Services (REpresentational State Transfer) which are easy to maintable and very fast to communicate and scalable because of REST API’s transfer data in the form of JSON format.

JSON Format:
JSON stands for JavaScript Object Notation. It is looks like JavaScript Object/ it is based on JavaScript object means it transfer data with pair of property and value in object format, but JSON is a string/ plain text.
{
“Name”: “Anil”;
“Age”: 23;
“Id”: 12
}
It is very easy to convert JavaScript object into JSON object and vice versa (JSON to JavaScript) with the help of below methods
JSON.pass();
JSON.stringfi();

Express JS:
Express is a framework of Node JS which is used to create dynamic web applications.
In previous version (http node module) there is only one handler for all type of http requests. So, that we used method property to identify the http request type. Its need extra code/ logic in order to provide response to request.
This (http module) version decreases the efficiency of an application to avoid this we are going to use next version called Express module with the help of Express we can create RESTful API’s and Express module provides different handlers for different type of http request.
            http request                 Handlers
            GET                            get()
            POST                          post()
            PUT                             put()
            DELETE                     delete()

Creation of Express Application:
Step (1): - In order to create Express application we have to import express module.
In order to import express module we have to install express module externally.
npm init         //package.json will appear
npm install express --save
With the help of this command install express externally.
Step (2): - Importing express module.
var Express= require('express');
Here “Express” is a function of express module.
Step (3): - Creating object of Express.
var app=Express();
app object contain an internal http server. So, we need to create a server but we have to assign a port to the internal http server.
Step (4): - Assigning port to express server
app.listen('8080',()=>{
});
Step (5): - Handling http requests.
Express contain predefine http handlers generally the handlers syntax look like below
Express_object.httpmethod/handler(path,request_handler_callback);

For Example:
get handler à app.get('/path',(req,res)=>{ });
post handler à app.post('/path',(req,res)=>{ });
put handler à app.put('/path',(req,res)=>{ });
delete handler à app.delete('/path',(req,res)=>{ });

Step (6): - We can send the response to client with the help of below methods.
res.send();
res.json();

Express Example:
Express.js
var Express= require('express');
var app=Express();
app.get('/',(req,res)=>{
    res.send("Welcome to Express App")
});
app.get('/aa',(req,res)=>{
    res.send("Welcome to Express aa")
});
app.post('/aa',(req,res)=>{
    res.send("Welcome to Express with post request")
});
app.put('/aa',(req,res)=>{
    res.send("Welcome to Express with put request")
});
app.delete('/aa',(req,res)=>{
    res.send("Welcome to Express with delete request")
});
app.listen('8080',()=>
{
    console.log('server started at 8080 port')
});
PS C:\Users\ANIL BABU\Desktop\Node JS> node Express.js
server started at 8080 port
Output:
Description: C:\Users\ANIL BABU\Pictures\Screenshots\Screenshot (209).png
Description: C:\Users\ANIL BABU\Pictures\Screenshots\Screenshot (210).png
Welcome to Express with put request
Welcome to Express with delete request

Difference between http and Express:

http
Express
Performance is slow
Performance is high/fast.
We can create server.
Server is default in express.
res.end() is manually end the response and close httpconnection.
res.send() is sends the response and closes the connection.


No comments: