Lets Understand Nodejs code as a Beginner

Lets Understand Nodejs code as a Beginner

Caution: If you are a beginner Please check out my last blog on nodejs- Lets Install And Get Started With Node.JS (LINK)

HTML code

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="/css/style.css">
  </head>
  <body>
    <h1>Hello, world! (index.html)</h1>
    <input id="userName" type="text" name="" placeholder="Enter Name">
    <button id="clickMe" type="button" name="button">Click Me</button>
    <h2 id="personName"></h2>
    <h2 id="personStatus"></h2>
    <h2 id="personOccupation"></h2>
    <script type="text/javascript" src="/js/main.js"></script>
  </body>
</html>

Client-side JavaScript code

document.querySelector('#clickMe').addEventListener('click', makeReq)

async function makeReq(){

  const userName = document.querySelector("#userName").value;
  const res = await fetch(`/api?student=${userName}`)
  const data = await res.json()

  console.log(data);
  document.querySelector("#personName").textContent = data.name
  document.querySelector("#personStatus").textContent = data.status
  document.querySelector("#personOccupation").textContent = data.currentOccupation
}

Server-side JavaScript code

const http = require('http');
const fs = require('fs')
const url = require('url');
const querystring = require('querystring');
const figlet = require('figlet')

const server = http.createServer((req, res) => {
  const page = url.parse(req.url).pathname;
  const params = querystring.parse(url.parse(req.url).query);
  console.log(page);

  //Looks same(1)
  if (page == '/') {
    fs.readFile('index.html', function(err, data) {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write(data);
      res.end();
    });
  }

  //Looks same(2)
  else if (page == '/otherpage') {
    fs.readFile('otherpage.html', function(err, data) {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write(data);
      res.end();
    });
  }

  //Looks same(3)
  else if (page == '/otherotherpage') {
    fs.readFile('otherotherpage.html', function(err, data) {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write(data);
      res.end();
    });
  }
//when page is API its check what its pass Leon or other Name
  else if (page == '/api') {
    if('student' in params){
      if(params['student']== 'leon'){
        res.writeHead(200, {'Content-Type': 'application/json'});
        const objToJson = {
          name: "leon",
          status: "Boss Man",
          currentOccupation: "Baller"
        }
        res.end(JSON.stringify(objToJson));
      }//student = leon
      else if(params['student'] != 'leon'){
        res.writeHead(200, {'Content-Type': 'application/json'});
        const objToJson = {
          name: "unknown",
          status: "unknown",
          currentOccupation: "unknown"
        }
        res.end(JSON.stringify(objToJson));
      }//student != leon
    }//student if
  }//else if
  else if (page == '/css/style.css'){
    fs.readFile('css/style.css', function(err, data) {
      res.write(data);
      res.end();
    });  
  }
  //Looks same(4)
  else if (page == '/js/main.js'){
    fs.readFile('js/main.js', function(err, data) {
      res.writeHead(200, {'Content-Type': 'text/javascript'});
      res.write(data);
      res.end();
    });
  }else{
    figlet('404!!', function(err, data) {
      if (err) {
          console.log('Something went wrong...');
          console.dir(err);
          return;
      }
      res.write(data);
      res.end();
    });
  }
});

server.listen(8000);

Let's understand above code

  1. http, fs url, querystring, figlet - These are modules which do all heavy lifting

  2. const http = require('http'); - It listen request and respond to network

  3. const fs = require('fs'); - Its helps us to access the disk.

  4. const url = require('url'); const querystring = require('querystring'); - A query string is part of the URL and URL is interface which we send to server as a request.

    For ex: fetch(`/api?student=${userName}`)

  5. const figlet = require('figlet') - Figlet is used to give ASCII 4040, To install figlet we write in terminal (npm install figlet)

    In above code if your server don't understand the url what you asking for then it return figlet 404

     else{
         figlet('404!!', function(err, data) {
           if (err) {
               console.log('Something went wrong...');
               console.dir(err);
               return;
           }
           res.write(data);
           res.end();
         });
       }
    
  6. Note: when we type URL + hit enter on the browser then we aspect something back from the server i.e. how web applications work

  7. if (page == '/')

     if (page == '/') {
         fs.readFile('index.html', function(err, data) {
           res.writeHead(200, {'Content-Type': 'text/html'});
           res.write(data);
           res.end();
         });
       }
    

    its means frontend wants html file so its sends request via URL and the server check the condition and responds with HTML

  8. If (page == '/css/style.css')

     else if (page == '/css/style.css'){
         fs.readFile('css/style.css', function(err, data) {
           res.write(data);
           res.end();
         });  
       }
    

    It means frontend wants css file and the server responds with the css file

  9. if (page == '/js/main.js')

     else if (page == '/js/main.js'){
         fs.readFile('js/main.js', function(err, data) {
           res.writeHead(200, {'Content-Type': 'text/javascript'});
           res.write(data);
           res.end();
         });
       }
    

    It means frontend wants JavaScript File and the server respond with a Javascript file

  10. The server hear request and its first check and respond with different things

  11. if (page == '/api')

    else if (page == '/api') {
    //fetch(`/api?student=${userName}`)-> here student is queryparameter that came with URL
        if('student' in params){
          if(params['student']== 'leon'){
            res.writeHead(200, {'Content-Type': 'application/json'});
            const objToJson = {
              name: "leon",
              status: "Boss Man",
              currentOccupation: "Baller"
            }
            res.end(JSON.stringify(objToJson));
          }//student = leon
          else if(params['student'] != 'leon'){
            res.writeHead(200, {'Content-Type': 'application/json'});
            const objToJson = {
              name: "unknown",
              status: "unknown",
              currentOccupation: "unknown"
            }
            res.end(JSON.stringify(objToJson));
          }//student != leon
        }//student if
      }
    

    Frontend send API request and the server respond with JSON Back

  12. How does the server know what Kind of request is coming in?

    const server = http.createServer((req, res) => {
      const page = url.parse(req.url).pathname; 
      const params = querystring.parse(url.parse(req.url).query); 
      console.log(page);
    }
    
    1. const page = url.parse(req.url).pathname; //(set path name of url i.e. LocalHost:8000/(here / is path)

    2. const params = querystring.parse(url.parse(req.url).query); //query string came with URL

An optimized version of Server-side JavaScript code

const http = require('http');
const fs = require('fs')
const url = require('url');
const querystring = require('querystring');
const figlet = require('figlet')

const server = http.createServer((req, res) => {
  const page = url.parse(req.url).pathname;
  const params = querystring.parse(url.parse(req.url).query);
  console.log(page);
  //use function readWrite for Looks same(1)(2)(3)(4) to make readable
  const readWrite=(file,contentType)=>{
    fs.readFile(file, function(err, data) {
    res.writeHead(200, {'Content-Type':contentType });
    res.write(data);
    res.end();
  });
}  
  switch(page){
    //Looks same(1)
    case '/':
      readWrite('index.html','text/html');
      break;
    //Looks same(2)
    case '/otherpage':
      readWrite('otherpage.html','text/html');
      break;
    //Looks same(3)
    case '/otherotherpage':
      readWrite('otherotherpage.html','text/html');
      break;
    case '/api':
      let personName='unknown';
      let personOccupation='unknown';
      let personStatus='unknown';
      if(params['student']== 'leon'){
        res.writeHead(200, {'Content-Type': 'application/json'});
        const objToJson = {
          name: "leon",
          status: "Boss Man",
          currentOccupation: "Baller"
      }
      res.end(JSON.stringify(objToJson));
      }
      res.writeHead(200, {'Content-Type': 'application/json'});
        const objToJson = {
          name: personName,
          status: personStatus,
          currentOccupation: personOccupation
        }
        res.end(JSON.stringify(objToJson));
      break;
    case '/css/style.css':
      fs.readFile('css/style.css', function(err, data) {
        res.write(data);
        res.end();
      });
      break;
    case '/js/main.js':
      readWrite('js/main.js','text/javascript');
      break;
    default:
      figlet('404!!', function(err, data) {
        if (err) {
            console.log('Something went wrong...');
            console.dir(err);
            return;
        }
        res.write(data);
        res.end();
      });

  }
});

server.listen(8000);

//first server intract with this file and write on the browser
//-> /(HTML), /css/style.css(CSS), /js/main.js(JS)
//-> /api(API) JSON to string and then it parse by fetch and write into DOM
//-> main.js run browser side and server.js run server side

//1. Building our own API and then fetch from main.js
//2. In HTML, there is only one script tag i.e. connect with only main.js doesn't care about server.js
// 3. Depend on which page we hit(what file access) depend on that we tell a server what to write i.e. display on browser


//Looks same(1)(2)(3)(4)->write once and make code reusable->we use function with two parameter i.e. we remove much of the redundant code using function and nows its more readable