Tuesday, 1 March 2022

HTTP module in NodeJS(Core module of NodeJS)

 What is HTTP module in Nodejs?

To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP. To use the HTTP server in node, we need to require the HTTP module. The HTTP module creates an HTTP server that listens to server ports and gives a response back to the client.

  • How to import HTTP module


const http = require('http');// import npm module


  • Declare Port

const PORT=80; // declare port


  • Creating Server 

//Creating Server and sending response
const app = http.createServer((req, res)=>{

       res.end("First Server created");
})


using http.createserver function we create server and send response using res.end 

The http.createServer() method turns your computer into an HTTP server.

The http.createServer() method creates an HTTP Server object.

The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.

  • listen server 

//listening at port
app.listen(PORT,()=>{

       console.log(`Server listening at port ${PORT}`);
})

Syntax

  • server.listen(porthostnamebacklogcallback);
ParameterDescription
portOptional. Specifies the port we want to listen to
hostnameOptional. Specifies the IP address we want to listen to
backlogOptional. Specifies the max length of the queue of pending connections. Default 511
callbackOptional. Specifies a function to be executed when the listener has been added
  • Read HTML file and send Responsive to Server 

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

   
    fs.readFile(path.join(__dirname,'public','index.html'),(err,data)=>{
       
           
        if(err)
        {
            throw err;
        }
        res.end(data);
    })
     
})


  • Send Many HTML file (first check url.req then using this send html file)

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

console.log(req.url);
    if(req.url==='/')
    {

   
   
    fs.readFile(path.join(__dirname,'public','index.html'),(err,data)=>{
       
           
        if(err)
        {
            throw err;
        }
        res.end(data);
    })

  }

  else if(req.url==='/about/')
  {

    fs.readFile(path.join(__dirname,'public','about.html'),(err,data)=>{
       
           
        if(err)
        {
            throw err;
        }
        res.end(data);
    })

  }
     
})


//listening at port
app.listen(PORT,()=>{

       console.log(`Server listening at port ${PORT}`);
})


  • Sending CSS Javascript Html and all file on server (mini site )



const http = require('http');// import npm module
const fs = require('fs');
const path = require('path');

const PORT = 80; // declare port

//Creating Server and sending response
const app = http.createServer((req, res) => {

    //collecting path using req.url
    let filepath = path.join(__dirname, 'public', (req.url === '/' ?
'index.html' : req.url));
   
    //declare content type
    let contentType = 'text/html';
   
    // finding extension of file
    let ext = path.extname(filepath);

    //no extension in file send .html
    if (!ext) {
        filepath += '.html';
    }

    //using switch case making content type
    switch (ext) {
        case ".css": contentType = 'text/css'; break;
        case ".js": contentType = 'text/javascript'; break;
        default: contentType = 'text/html';
    }

        //reading file from filepath
        fs.readFile(filepath, (err, content) => {
            //if errr in send filepath conent
            if(err) {
                fs.readFile(path.join(__dirname, 'public', 'error.html'),
(err, data) => {
                    //if errr send error.html file
                    if(err) {
                        res.writeHead(500)
                        res.end('Error!!!')  
                    }
                    // //if errr send error.html file
                     else {
                        res.writeHead(404, {
                           'Content-Type': contentType
                        })
                        res.end(data)
                    }
                   
                })
            }
            //if no errr in send filepath conent
            else {
                res.writeHead(200, {
                    'Content-Type': contentType
                })
                res.end(content)
            }
           
   
        })
 

   

})
//listening at port
app.listen(PORT, () => {

    console.log(`Server listening at port ${PORT}`);
})



more about http module Click here



Monday, 28 February 2022

Event Module in NodeJS (Core Module in NodeJS)

 Why We use Event module in Nodejs ?

Important for  example - When user registered we want to many work for user like as store in database, send welcome mail and many work it will help you to do all the things in very good manner  


How to use it 

const emmiter = require('event'); it will return class then 

const myemmiter = new emmiter(); convert into object 

Create Event listener 


myemmiter.on('greeting',(data)=>{

    console.log("welcome to OffSection India ",data);
})

greeting= Event name 

data = recving data from emit 

Emit or Call event listener 

myemmiter.emit('greeting','AshutoshKumar');

in this emit greeting is event name and Ashutoshkumar is data 


One Real World Example

When we require a student to add database and send mail and welcome massage we use this for all .
const emmiter = require('events');

//Creating Class
class registered extends emmiter {

         registerd(username){

            console.log(`You are successfully Registered `)
            //calling event
            this.emit('registered',username);

         }

}

//making Object
const Registered = new registered();


//listen event for add to data base
Registered.on('registered',(data)=>{

         console.log(`Hey Mr/Mrs ${data}\nYou are successfully
Added to our DataBase`);
})
//listen event for welcome massage
Registered.on('registered',(data)=>{

         console.log(`Hey Mr/Mrs ${data}\nWelcome Come To Our Company`);
})
//listen event send password to email
Registered.on('registered',(data)=>{

         console.log(`Hey Mr/Mrs ${data}\nplease Check Your mail For
Password and Username`);
})

//calling object function
Registered.registerd('Ashutosh Kumar');

Core Modules in NodeJs

 Some Core Modules In Nodejs is Here :-

1.Path Module some Important function :-



















Output :-















All path module function click Here


2. FS (File System) module :-

  • Create Directory or folder using FS module 















after Running Code test folder will created if folder already exist throw error massage.

  • Create file or write in file using FS module 










after running Code in test folder test.txt file will create and data written in test.txt file 
if test.txt file already exist then data will overwrite in test.txt file 

  • if You want to write some more data(content) in already exist file then we will use :-










after running code data will added in test.txt file   

  • Read file using FS module :-











After running code you will get read data from test.txt file .


all function in FS module Click


3. Operating System Module 


























OUTPUT:-




































Next module in Core module in NodeJS 2


Nodejs Notes for Beginner

What is NodeJS ?

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.

What is NPM in NodeJS?
npm is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client, also called npm, and an online database of public and paid-for private packages, called the npm registry. 

Some Important Commands for NPM: 

  1. npm init - initialize the npm in project (you will get package.json file  );
  2. npm install package name (npm install cli-color) - you will get cli-color module 
  3. npm install - (after delete module folder ) Install all package (module folder)























what is IIFE function in JavaScript?














and in NPM module like this IIFE Function Decleare :-









How to export NPM module in our project file ? :-















How to export local module in our project? :-
















Export Two or more function from same local module :-





























Next :- Notes in NodeJS Core Module 



Sunday, 27 February 2022

How to login root user in Aws EC2 instance ?

 Run the Following Commands in login user  :

sudo -s

vi /root/.ssh/authorized_keys

👇👇👇👇



After Runing Commands Vim Editor open then delete the highlight code in vim editor

👇👇👇👇👇


After deleting press Esc then :(colon ) the wq and press Enter , Now you also login through Root

HTTP module in NodeJS(Core module of NodeJS)

 What is HTTP module in Nodejs? To make HTTP requests in Node.js, there is a built-in module  HTTP  in Node.js to transfer data over the HTT...