NODE JS Tutorial | Practical explaination

0

Node.js is an open-source and cross-platform javascript library that allows you to use JavaScript to develop server-side applications.

Every web browser has a JavaScript engine that takes JavaScript code and compiles it to machine code. For example, Firefox uses SpiderMonkey, and Google Chrome uses V8. Because browsers use different JavaScript engines, sometimes, you will see that JavaScript behaves differently between browsers.

In 2009, Ryan Dahl, the creator of Node.js, took the V8 engine and embedded it in an application that could execute JavaScript on the server.

Unique Features of NODE JS:-

Node.js is Single-threaded

Node.js is single-threaded. It means that each process has only one thread of execution.

The single-threaded execution model allows Node.js to handle more concurrent requests easily via the event loop. Because of this, Node.js applications typically consume comparatively less memory.

If you have not familiar with the event loop, check out this event loop tutorial. The event loop in Node.js works the same as the event loop in web browsers.

Node.js uses Non-blocking I/O

I/O stands for input/output. It can be disk access, a network request, or a database connection. I/O requests are expensive and slow and hence block other operations.

Node.js addresses blocking I/O issues by using non-blocking I/O requests.

Non-blocking means that you can make a request while doing something else, and then, when this request is finished, a callback will execute to handle the result.

In other words, the program execution can continue while other operations are taking place.

How to Install Node JS:-

Just write the download node in google it provides LTS , and download according to your o/s.

To confirm the installation, you can open Command Prompt or Windows Terminal and type the following command:

node -v

Step to create First Hello World Program in Node JS:-

1)  Create Folder

2) Open this folder in VS Code

3) Type npm init 

4) create hello.js file 

5) write following code

console.log("hello world")
6) open terminal write
node hello.js


What is Modules in NODE JS:-

It is similar to JS library, and it is used to contain predefine functionality under
NODE application.
We can create our own module also.
Node JS provide various modules, we will step all modules one by one


HTTP module in node js:-

This is the most important module to manage HttpRequest and HttpResonse.

Now I am creating one simple program to explain http module.

const http = require('http')
const hostname = '127.0.0.1'
const port = 3000
const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/html')
  res.end('<h1>Hello World</h1>')
})
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`)
  })

Another Example of an HTTP Module:-
const  http = require('http');

const port = 2000;
const host = "127.0.0.1"
const server = http.createServer((req,res)=>{
    res.statusCode=200
    var p = 120000
    var r = 5.5
    var t = 2
    var si = (p*r*t)/100
    res.setHeader('Content-Type','text/html')
    res.end(`<h1>Result is ${si} </h1>`)
})

server.listen(port,host,()=>{
    console.log(`click to execute http://${host}:${port}`)
})




Another Example of HttpModule:-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="http://127.0.0.1:3000/" method="get">
       <input type="text" name="txtnum1" placeholder="Enter First Number" />
       <br><br>
       <input type="text" name="txtnum2" placeholder="Enter First Number" />
       <br><br>
       <input type="submit" name="btnsubmit"  />

    </form>
</body>
</html>

Code for Add.js

var url = require('url');
const http = require('http')
const hostname = '127.0.0.1'
const port = 3000
const server = http.createServer((req, res) => {
//  console.log(req.url)
   var q = url.parse(req.url, true);
    var obj = q.query
    var res1 = parseInt(obj.txtnum1) + parseInt(obj.txtnum2)
    res.write(""+res1)
    res.end("<h1>Hello World</h1>")
  })
  server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`)
    })

The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client. using this we can create web server to post node script under web environment.
Use the createServer() method to create an HTTP server.


Read the query String using Http Module:-

 var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(req.url);
  res.end();
}).listen(8080);


File Module in Node JS:-

This is another important module in Node Js that is used to manage file operation.
1) Write File
2) Read File
3) Append File
4) Delete the File

This operation must be implemented using asynchronous mode

Now I am explaining using example:-

var fs = require('fs');
 fs.open('abc.txt', 'w', function (err, file) {
    if (err) throw err;
    console.log('Saved!');
  });
fs.writeFile('abc.txt', 'Hello content!', function (err) {
    if (err) throw err;
    console.log('Saved!');
  });
fs.readFile('abc.txt',(err, data) => {
    var array = data.toString().split(" ");
    console.log(data.toString());
    for(i in array) {
        // Printing the response array
        console.log(array[i]);
     }
 })

  fs.appendFile('abc.txt', ' dftrdyhtyt.', function (err) {
    if (err) throw err;
    console.log('Updated!');
  });
  fs.unlink('abc.txt', function (err) {
    if (err) throw err;
    console.log('File deleted!');
  });
  fs.rename('abc.txt', 'abcnew.txt', function (err) {
    if (err) throw err;
    console.log('File Renamed!');
  });
 
Example with Synchronous Operation:-

var data = fs.readFileSync('hello.txt');
console.log("Synchronous read: " + data.toString());


Node JS URL Module:-

The URL module splits up a web address into readable parts. To include the URL module, use the require() method.

Parse an address with the url.parse() method, and it will return a URL object with each part of the address as properties:

Now i am explaining url module using URL and Http Module Combination

var url = require('url');

const http = require('http')

const hostname = '127.0.0.1'

const port = 3000

const server = http.createServer((req, res) => {

//  console.log(req.url)

   var q = url.parse(req.url, true);

   

     console.log(q.host);

     console.log(q.pathname);

     console.log(q.search)

     console.log(q.query)

    res.end('<h1>Hello World</h1>')

  })

  server.listen(port, hostname, () => {

      console.log(`Server running at http://${hostname}:${port}/`)

    })

How to create NODE JS File Server:-

Using this we can create multiple files of Html and call using the NODE JS  Server with the help of HTTP and URL module.

Create home.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Welcome in Home Page</h1>
</body>
</html>

create About.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1>Welcome in About us page</h1>
</body>
</html>

app.js

var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
console.log(q);
var filename = "." + q.pathname;
console.log(filename);
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<a href='./home.html'>Home</a>");
res.write("<a href='./about.html'>About us</a>");
res.write(data);
return res.end();
});
}).listen(8080);

How to work with Video Streaming in Node JS Application:-

1)  create video.html file:-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <video src="http://localhost:1337" preload autoplay controls width="500" height="500"></video>
</body>
</html>

2) create video.js file

var http = require('http'),
    fs = require('fs'),
    util = require('util');

http.createServer(function (req, res) {
  var path = __dirname+'/myvideo.mp4';
  var stat = fs.statSync(path);
  var total = stat.size;
  if (req.headers['range']) {
    var range = req.headers.range;
    var parts = range.replace(/bytes=/, "").split("-");
    var partialstart = parts[0];
    var partialend = parts[1];

    var start = parseInt(partialstart, 10);
    var end = partialend ? parseInt(partialend, 10) : total-1;
    var chunksize = (end-start)+1;
    console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize);

    var file = fs.createReadStream(path, {start: start, end: end});
    res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4' });
    file.pipe(res);
  } else {
    console.log('ALL: ' + total);
    res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'video/mp4' });
    fs.createReadStream(path).pipe(res);
  }
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');


Event Module in JS:-

This is very simple module that is used to perform the action, we can attach event dynamically using this Event Module.

var events = require('events');
var eventEmitter = new events.EventEmitter();
var fun = function(){
console.log("My User Define Event Method");
}
eventEmitter.on('myclick',fun);
eventEmitter.emit('myclick');

User Define Module:-

Using this we can create a custom module that can be used in another file.

Step 1st:-

Create Module:-

exports.mymodule = function () {
    return "Welcome in user define module";
  };

exports.fun = function () {
    return "module fun2";
  };

Use Module
const um = require('./mymodule')
console.log(um.mymodule())
console.log(um.fun())
What is Blocking & Non-Blocking of Code? NODE JS API supports the Non-Blocking of the code, it is a unique feature of the NODE JS Application
and it improves the performance of the NODE Application Blocking of code means if one process is not completed then another process will be
on hold but in non-blocking features,
if one process takes more time to execute then another process can be completed.
Example of Blocking of Code:-

var fs = require("fs");
var data = fs.readFileSync('hello.txt');
console.log(data.toString());
console.log("Program Ended");

Example of Non-Blocking of Code:-

var fs = require("fs");

fs.readFile('hello.txt', function (err, data) {
   if (err) return console.error(err);
   console.log(data.toString());
});

console.log("Program Ended");

What is Stream?

Stream objects that are used to read data from the source and write data into the destination.

there are four types of streams − Readable − Stream which is used for read operation. Writable − Stream which is used for write operation. Duplex − Stream which can be used for both read and write operation. Transform − A type of duplex stream where the output is computed based on input.


The stream can be connected with Event Emitter instance and user various events to perform the operation

data − This event is fired when there is data is available to read. end − This event is fired when there is no more data to read. error − This event is fired when there is any error in receiving or writing data. finish − This event is fired when all the data has been flushed to underlying system.

Reading from Stream Example:-
var fs = require("fs");
var data = '';

// Create a readable stream
var readerStream = fs.createReadStream('hello.txt');

// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
   data += chunk;
});

readerStream.on('end',function() {
   console.log(data);
});

readerStream.on('error', function(err) {
   console.log(err.stack);
});

console.log("Program Ended");

Writing data on Stream:-
var fs = require("fs");
var data = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
   console.log("Write completed.");
});

writerStream.on('error', function(err) {
   console.log(err.stack);
});

console.log("Program Ended");

What is Socket.io?

It is used to establish client-server based communication into real-time application.it is
basically used to create chat based application.

because in chat script multiple user's connected from server and communicate with each other.


Step to implement socket.io?

1) First install socket.io

npm install socket.io --save

2) Install Express Js
npm install express --save

3) create server.js file

const express = require('express');
const socketIO = require('socket.io');
const http = require('http')
const port = process.env.PORT || 3000
var app = express();
let server = http.createServer(app);
var io = socketIO(server);
io.on('connection',
    (socket) => {
        console.log('New user connected');
        //emit message from server to user
        socket.emit('newMessage',
            {
                from: 'jen@mds',
                text: 'hepppp',
                createdAt: 123
            });
 
        // listen for message from user
        socket.on('createMessage',
            (newMessage) => {
                console.log('newMessage', newMessage);
            });
 
        // when server disconnects from user
        socket.on('disconnect',
            () => {
                console.log('disconnected from user');
            });
    });

    app.get("/",
    (req, res) => {
        res.sendFile(__dirname + "/client-side.html");
    });

    server.listen(port);

4) create html file:-

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
    <meta charset="utf-8">
    <title>ChatApp</title>
</head>

<body class="chat">
    <form id='message-form'>
        <input name='uname'
            type="text" placeholder="Enter name"
            autofocus autocomplete="off" />
        <input name='message'
            type="text" placeholder="Message"
            autofocus autocomplete="off" />
        <button type="submit">Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io();

        // connection with server
        socket.on('connect', function () {
            console.log('Connected to Server');
        });

        // message listener from server
        socket.on('newMessage',
            function (message) {
                console.log(message);
            });

        // add event listener to form
        document.getElementById('message-form')
            .addEventListener('submit',
                function (e) {
                    // prevent the form from submitting
                    e.preventDefault();

                    // emit message from user side
                    socket.emit('createMessage',
                        {
                            to:document
                            .querySelector(
                                'input[name=uname]'
                            ).value,
                            text: document
                                .querySelector(
                                    'input[name=message]'
                                ).value
                        });
                });

        // when disconnected from server
        socket.on('disconnect', function () {
            console.log('Disconnected from server');
        });
    </script>
</body>

</html>


How to connect NODE JS to Mongo DB:-
1) Install MONGODB IN Code
2) Type following command npm install mongodb

3) Create Following Code to perform Data Insertion Operation

const { MongoClient } = require('mongodb');

// Replace the following with your actual MongoDB connection string
const uri = 'mongodb://localhost:27017';
const dbName = 'phixmandb';
const collectionName = 'students';

// Sample data to be inserted
const sampleDocument = {
  rno: '1002',
  name: 'stu2',
  // add more key-value pairs as needed
};

async function insertData() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Insert a single document
    const result = await collection.insertOne(sampleDocument);
    console.log('Inserted document id:', result.insertedId);
  } catch (err) {
    console.error('Error inserting data:', err);
  } finally {
    client.close();
  }
}

// Call the insertData function to perform the insertion
insertData();


Create the Following Code for Data Selection:-

const { MongoClient } = require('mongodb');

// Replace the following with your actual MongoDB connection string
const uri = 'mongodb://localhost:27017';
const dbName = 'phixmandb';
const collectionName = 'students';



async function selectData() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Insert a single document
    var result = await collection.find({}).toArray();
    for(var r of result)
    {
        console.log(r.rno + "," + r.name);
    }
   // console.log('Inserted document id:', result.insertedId);
  } catch (err) {
    console.error('Error inserting data:', err);
  } finally {
    client.close();
  }
}

// Call the insertData function to perform the insertion
selectData();


Create Code for Data Updation:-

const { MongoClient } = require('mongodb');
// Replace the following with your actual MongoDB connection string
const uri = 'mongodb://localhost:27017';
const dbName = 'phixmandb';
const collectionName = 'students';

// Sample data to be inserted


async function updateData() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Insert a single document
    const result = await collection.updateOne({rno:'1002'},{$set:{name:"mayank"}});
 
  } catch (err) {
    console.error('Error inserting data:', err);
  } finally {
    client.close();
  }
}

// Call the insertData function to perform the insertion
updateData();


Create Code for Data Deletion:-

const { MongoClient } = require('mongodb');
// Replace the following with your actual MongoDB connection string
const uri = 'mongodb://localhost:27017';
const dbName = 'phixmandb';
const collectionName = 'students';

// Sample data to be inserted


async function updateData() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Insert a single document
    const result = await collection.deleteOne({rno:'1002'});
 
  } catch (err) {
    console.error('Error deleteing data:', err);
  } finally {
    client.close();
  }
}

// Call the insertData function to perform the insertion
updateData();

Manage Join Operation in Node Js Project

1) First Create two Collection one for the Product and Another for the Order

Product Collection contains the productid, and product name, and Order collection contains orderid, productid, status

Write Following Example:-

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const dbName = 'mydb';
async function selectData() {
    const client = new MongoClient(uri);
 
    try {
      await client.connect();
 
      const db = client.db(dbName);
     var result= await db.collection('order').aggregate([
        { $lookup:
           {
             from: 'product',
             localField: 'productid',
             foreignField: 'productid',
             as: 'orderdetails'
           }
         }
        ]).toArray();
        console.log(JSON.stringify(result))
   
    } catch (err) {
      console.error('Error inserting data:', err);
    } finally {
      client.close();
    }
  }

 
});
selectData();
Express JS:-
It is a web framework that is used to create route and server to access NODE Js features

const express = require('express')
const app = express()
app.get('/ram',(req,res)=>{
    res.send("hello world")
})
app.get('/',(req,res)=>{
    res.send("welcome")
})

app.listen(3333,()=>{
    console.log('open 33333 port')
})

NODE JS API Example:-

Now I am providing the complete Example to create Restfull API in Node js

1) npm install express
2) npm install body-parser
3) npm install cors

const Express = require("express");
const { MongoClient, Collection } = require('mongodb');
const BodyParser = require("body-parser");
//const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const CONNECTION_URL ="mongodb://localhost:27017/" ;
const DATABASE_NAME = "phixmandb";
var app = Express();
var cors = require('cors')
app.use(cors())
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
var db, collection;
app.listen(5000, () => {
         const client = new MongoClient(CONNECTION_URL);
         client.connect();

          db = client.db(DATABASE_NAME);
          collection = db.collection("students");
          console.log("Connected to `" + DATABASE_NAME + "`!");
    });
   

app.get("/studata", async (request, response) => {
        var result = await collection.find({}).toArray();
        response.send(result);
    });

app.get("/studata/:id", async (request, response) => {
        var result= await collection.findOne({"rno":request.params.id});
        response.send(result);
    });


app.post("/studata", async (request, response) => {
       var result = await collection.insertOne(request.body);
        response.send(result);
});

app.put("/studata/:id", async (request, response) => {
    var result = await collection.updateOne({"rno":request.params.id},{$set:request.body});
    response.send(result);
    });


app.delete("/studata/:id", async (request, response) => {
   var result = await collection.deleteOne({ "rno":request.params.id});
        response.send(result);
    });


RESTful API using Login and Registration:-

app.post("/register", async (request, response) => {
        var result = await collection1.insertOne(request.body);
         response.send(result);
 });
 app.post("/login", async (request, response) => {
    var result = await collection1.findOne({"email":request.body.email,"pwd":request.body.pwd});
    if (result!=null)
    {
        response.send({"status":"1","msg":"login success"})
    }
    else
    {
        response.send({"msg":"login failed"})
    }
});


Tags

Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)