Node JS (1) Final

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

Node JS

 It is an open source, cross platform, backend Javascript runtime

environment for creating a single threaded server side programs

which can handle HTTP GET and POST request generated from

Frontend.

 It is a Google Chorme’s Javascript Engine and was developed by

Ryan Dhal in 2009.

 Backend APIs can be created at ease with Node JS

Features of Node JS

 Asynchronous and Event Driven

All APIs of Node.js library are asynchronous, that is, non-blocking. It


essentially means a Node.js based server never waits for an API to return
data. The server moves to the next API after calling it and a notification
mechanism of Events of Node.js helps the server to get a response from the
previous API call.

 Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js


library is very fast in code execution.

 Single Threaded but Highly Scalable 

Node.js uses a single threaded program and the same program can provide
service to a much larger number of requests than traditional servers like
Apache HTTP Server.

 No Buffering − Node.js applications never buffer any data. These applications


simply output the data in chunks.

 License − Node.js is released under the MIT license.


Who use Node JS?

Below is the partial list of companies who use Node JS

eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins,


Yahoo!, and Yammer to name a few.

Where to Use Node.js?

Following are the areas where Node.js is proving itself as a perfect technology
partner.

 I/O bound Applications

 Data Streaming Applications

 Data Intensive Real-time Applications (DIRT)

 JSON APIs based Applications

 Single Page Applications

Where Not to Use Node.js?

It is not advisable to use Node.js for CPU intensive applications.

Software Required

Go to the following URL and download msi (installer) and install the
Node
https://nodejs.org/en/

Go to command line and you can check the Node version


 Node -v
Environmental Setup

npm init

npm install express

Express provides Web Application Framework in Node js offering


features to develop a server side of web application

npm install body-parser

Node.js body parsing middleware.

Parse incoming request bodies in a middleware before your handlers,


available under the req.body property.

npm install cors

 CORS is shorthand for Cross-Origin Resource Sharing.


It is a mechanism to allow or restrict requested resources on a web server
depend on where the HTTP request was initiated. 

npm install mongodb


Working with NoSQL – Mongodb

npm install nodemailer


Working with mail server
Version 1:
Generating HTTP GET request and GET request with Query String

const  express=require('express');
const bodyParser=require('body-parser')
const cors=require('cors')

const app=express();
app.use(cors());
app.use(express.json())
app.use(bodyParser.urlencoded({
       extended:true
}))

app.get('/home',function(req,res){

        var name=req.query.name
        console.log("TT"+req.query.name)
        res.send("<h1> Hello, "+name+"  Welcome to Sona College </h1>")
})

app.listen(5000,function(){
       console.log("Node Server is running on port 5000")
})

Version 2:
Generating GET request with parameters

const  express=require('express');
const bodyParser=require('body-parser')
const cors=require('cors')

const app=express();
app.use(cors());
app.use(express.json())
app.use(bodyParser.urlencoded({
       extended:true
}))

app.get('/home',function(req,res){
        var name=req.query.name
        console.log("TT"+req.query.name)
        res.send("<h1> Hello, "+name+"  Welcome to Sona College </h1>")
})

// Passing HTTP Get Request params

app.get('/home/:name',function(req,res)
{

    var name=req.params['name'];
    res.send("<h1> Hello, "+name+"  Welcome to Sona College -   Params concept </h1>")

})

app.get('/home/:name/:dept',function(req,res)
{

    var name=req.params['name'];
    var dept=req.params['dept'];
    res.send("<h1> Hello, "+name+" , Welcome to Sona College -   Params concept working in
"+dept+" </h1>")

})
app.listen(5000,function(){
       console.log("Node Server is running on port 5000")
})

Generating Post request and handling data in the body

const  express=require('express');
const bodyParser=require('body-parser')
const cors=require('cors')

const app=express();
app.use(cors());
app.use(express.json())
app.use(bodyParser.urlencoded({
       extended:true
}))

app.get('/home',function(req,res){
        var name=req.query.name
        console.log("TT"+req.query.name)
        res.send("<h1> Hello, "+name+"  Welcome to Sona College </h1>")
})

// Passing HTTP Get Request params

app.get('/home/:name',function(req,res)
{

    var name=req.params['name'];
    res.send("<h1> Hello, "+name+"  Welcome to Sona College -   Params concept </h1>")

})

app.get('/home/:name/:dept',function(req,res)
{

    var name=req.params['name'];
    var dept=req.params['dept'];
    res.send("<h1> Hello, "+name+" , Welcome to Sona College -   Params concept working in
"+dept+" </h1>")

})

app.post('/oddeven',function(req,res){

            var num=Number(req.body.number);
            var message="";

      
            num%2===0?message="even":message="odd"

            res.send("<h1> Given number "+num+" is "+message+"<h1>")


      

})
app.listen(5000,function(){
       console.log("Node Server is running on port 5000")
})
Lab Question

Write a Backend API in node js to check whether given string is


palindrome or not

const  express=require('express');
const bodyParser=require('body-parser')
const cors=require('cors')

const app=express();
app.use(cors());
app.use(express.json())
app.use(bodyParser.urlencoded({
       extended:true
}))

app.post('/palidnrome',function(req,res){

        var inputString=req.body.inputString;

    

        let newString = "";


    for (let i = inputString.length - 1; i >= 0; i--) {
        newString += inputString[i];
  }
        console.log(newString)

        var message=""

        newString===inputString?message="String is a palindrome":message="String is not a


palindrome"

        res.send("<h1> "+message+"</h1>")

})
app.listen(5000,function(){
       console.log("Node Server is running on port 5000")
})
Lab Question

Create React JS application that allows the user to signup with Online

Assessment System. After successful Sign Up, user should login and

upon successfull login attempt . he/she should take up a test. After

completing the test, students will be shown a result as well as mail will

be send to user email id.

Backend API to be developed

Signup

Login

Marks

const express=require('express')

const bodyParser=require('body-parser');

var nodemailer = require('nodemailer');

const app=express();

const cors=require('cors')
app.use(cors());

app.use(express.json())
app.use(bodyParser.urlencoded({

         extended:true

}))

var transporter = nodemailer.createTransport({


  service: 'Outlook365',
  auth: {
    user: 'mohanrajv@sonatech.ac.in',
    pass: ''xxxxxxxxxx”
 }
});

app.get("/",function(req,res){

        res.send("<h1> Welcome to node Js </h1>")

})

app.post("/signup",function(req,res){

        let username=req.body.username;
        let password=req.body.password;
        let mobile=req.body.mobile;

   

        var MongoClient = require('mongodb').MongoClient;


        var url = "mongodb://localhost:27017/";
    
        MongoClient.connect(url, function(err, db) {
          if (err) throw err;
          var dbo = db.db("Assessment");
          var myobj = { username: username, password:password,mobile:mobile };

          console.log("test "+myobj.username)
          dbo.collection("login").insertOne(myobj, function(err, res) {
            if (err) throw err;
            console.log("1 document inserted");
            db.close();
          });
        });
    
   

        res.send("success")

})

app.post("/signin",function(req,res){

     let uname=req.body.username;
     let password=req.body.password;

     console.log("uuuuu"+uname)

   

     var MongoClient = require('mongodb').MongoClient;


     var url = "mongodb://localhost:27017/";
   
     MongoClient.connect(url, function(err, db) {
       if (err) throw err;
       var dbo = db.db("Assessment");

       var query = { username: uname };


       dbo.collection("login").find(query).toArray(function(err, result) {
         if (err) throw err;
         console.log(result);
         console.log(result[0].username)

         if(password===result[0].password)
         {
           console.log("success")
           res.send("success")
         }
        else
    {
          console.log("Failure")        
          res.send("Failure")
    }

      
    
         db.close();

    
       });
     });

  
  
  

})

app.post('/marks',function(req,res){

    let q1=req.body.q1;
    let q2=req.body.q2;
    let username=req.body.username;
    let marks=0;
  
    marks=(q1=='fsd')?marks+1:marks;
    marks=(q2=="agile")?marks+1:marks;

    console.log(marks)

    marks=(marks/2) * 100;

    let dt=new Date();

    console.log(dt.toString())
  
    let dts=dt.toString()

    var MongoClient = require('mongodb').MongoClient;


    var url = "mongodb://localhost:27017/";
  
    MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      var dbo = db.db("Assessment");
      var myobj = {username:username,marks:marks,datetime:dts };

      console.log("test "+myobj.username)
      dbo.collection("marks").insertOne(myobj, function(err, res) {
        if (err) throw err;
        console.log("1 document inserted");
        db.close();
      });
    });

    var mailOptions = {
      from: 'mohanrajv@sonatech.ac.in',
      to: username,
      subject: 'Sending your marks for the exam taken at Sona Assessment platform',
      html: '<h1> Hai'+username +" You Secured Marks of  "+ marks+" % in the exam taken on
"+dt+"</h1>"
  }

    transporter.sendMail(mailOptions, function(error, info){


      if (error) {
        console.log(error);
      } else {
        console.log('Email sent: ' + info.response);
   }
    });

    res.send("Hai "+username +" You Secured Marks of  "+ marks+" % in the exam taken at "+dt
+" and mail has been sent to you")

}
)
 
app.listen(5000,function(){
    console.log("Server is running on port number 5000")
})
MongoDB

SQL Vs NoSQL

 relational (SQL) or non-relational (NoSQL) data structure

SQL NoSQL

RELATIONAL DATABASE
MANAGEMENT SYSTEM Non-relational or distributed database
(RDBMS) system.

These databases have fixed or


static or predefined schema They have dynamic schema

These databases are not suited These databases are best suited for
for hierarchical data storage. hierarchical data storage.

These databases are best suited These databases are not so good for
for complex queries complex queries

Vertically Scalable
Horizontally scalable

you handle more traffic by sharding, or


This means that you can adding more servers in your NoSQL
increase the load on a single database.
server by increasing things like
RAM, CPU or SSD.

Follows ACID property Follows CAP(consistency, availability,


partition tolerance)

Consistency (C): Every client sees the


same data. Every read receives the data
from the most recent write.

Availability (A): Every request gets a non-


error response, but the response may not
SQL NoSQL

contain the most recent data.

Partition Tolerance (P): The system


continues to operate despite one or more
breaks in inter-node communication
caused by a network or node failure.

Examples: MySQL, PostgreSQL, Examples: MongoDB, GraphQL, HBase,


Oracle, MS-SQL Server etc Neo4j, Cassandra etc

Document

“name”:”mohanraj”

“mobile”:9789999

MONGODB – CURD Operations

Download the mongdb community edition locally

https://www.mongodb.com/try/download/community

Creating a Database

 use Sona
Show All the Databases

 show dbs

Drop a Database

 db.dropDatabase()

Create Collection (Alias for Table)

db.createCollection(“Sona”);

and Insert a record into it.

db.Sona.insert(
{name:'Mohanraj',
email:'vm@gmail.com',
Designation:'Professor',
Depat:'IT',
YearofExperience:22,
mobile:9786123706}
)

{ acknowledged: true,
insertedIds: { '0':

Object
("62a6ccb3a16b192d233d82ef") } }
The _id which is provided by MongoDB is a 12-byte value of ObjectId which is
prepared from the following values:

 a 4-byte value denoting the seconds as Unix epoch,


 a 3-byte device identifier value,
 a 2-byte processing id,
 a 3 byte counter which is a random value.

db.Sona.insert(
{name:'YSuresh',
email:'Ys@gmail.com',
Designation:'Professor',
Depat:'IT',
YearofExperience:25
Landline:4272216874
}
)

Dropping a Collection

db.collectionname.drop()
Insert Documents

1. insert()
2. insertOne()
3. insertMany()

db.creatCollection(‘movie’)

db.movie.insert(
[
{ name: ‘petta’,lead:’rajini },
{ name: ‘vikram’,lead:’kamal’ }
]
)

db.movie.insertOne(
{

name:’Beast’,
lead:’Vijay’,
year:2022
}
)

db.movie.insertMany(
[
{
_id:100
name:’kaithi’,
lead:’Karthcik’,
year:2020
},
{
_id:200
name:’Annathe’,
lead:’Rajini’,
year:2021
}
]
)

Querying the Database

Find() method

db.collectionname.find()

Filtering Crieteria

db.movie.find({lead:’Suriya’})

And operator

db.movie.find({lead:’Suriya’,year:2022})

Or operator

db.movie.find({$or: [ { lead: "Suriya" }, { year:2021 }


]})
Select Queries

db.movie.find({year:2022},{_id:0,name:1,lead;1})

Limiting the result

db.movie.find().limit(2)

Update the Document

db.movie.update{{name:’suriya’},{$set:{year:2021}})

Save method is used to replace the document

Delete the document

1. db.collection.deleteOne()
2. db.collection.remove()
3. db.collection.deleteMany()

db.movie.deleteOne({name:’Bhaubali’})
db.movie.remove({})

db.movie.deleteMany({year:{$in:[2019,2020]}})

CRUD Operations in Mongodb

Dictionary Database

 use Dictionary

 db.createCollection(“words”)

Create Methods

 db.words.insertOne(

‘word’:’dean’,
‘meaning’:’head of academics’

db.words.insertMany(
[
{'word':'love','meaning':'affectio
n'},
{'word':'whistle','meaning':'sound
made through air'}])

db.words.insert(
{'word':'friend','mean':'co
mpanion'})

Different Schema

db.words.insert(
{
'word':'sona',
'mean':'gold',
"grammer":"noun"
}
)

Read Operations

 db.words.find() [ select * from words]

 db.words.find({‘word’:’sona’}) [ where word=’sona’]

db.words.find({'word':'sona','gr
ammer':'noun'})

 OR

db.words.find({$or:[{'word':'sona'},
{'grammer':'verb'}]})

 Limiting the result

db.words.find().limit(2)
Projections

db.words.find({'word':'sona'},
{_id:0,word:1,meaning:1})

Update

db.words.update({"word":"sona"},
{$set:{"mean":"Gold is
precious"}})

Delete

Delete the document

1. db.collection.deleteOne()
2. db.collection.remove()
3. db.collection.deleteMany()

db.words.deleteOne({"word":"fr
iend"})
db.words.deleteMany({"word":{$in:
["dean","sona"]}})

db.words.remove({})

Drop the collection

db.words.drop()

Drop the DB

db.dropDatabase()
Creating Dictionary Search Backend API to find

the meaning for the given word.

const express=require('express')

const bodyParser=require('body-parser');

const app=express();
const cors=require('cors')
app.use(cors());
app.use(express.json())

app.use(bodyParser.urlencoded({
    extended:true
}))

app.post("/dictsearch",function(req,res){

    let word=req.body.word;
  
    console.log("uuuuu"+word)

  

    var MongoClient = require('mongodb').MongoClient;


    var url = "mongodb://localhost:27017/";
  
    MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      var dbo = db.db("Dictionary");

      var query = { word: word };


      dbo.collection("words").find(query).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
      res.send("<h1> Meaning of the  word "+word+" is "+result[0].meaning+"</h1>");

     
   

        db.close();

    
      });
    });

  
  
  

})

 
app.listen(5000,function(){
    console.log("Server is running on port number 5000")
})

You might also like