Skip to content

i-m-prabhat/Node-notes

Repository files navigation

Node js Notes

FS Module


JavaScript Interview tricky questions
React Interview Questions
JavaScript DSA
JavaScript interview questions
JavaScript Clean Code
funny and tricky JavaScript examples
You Don't Know -JS

How to create a Node server

To crate a node server in Node js we need two things

  1. Request Object : handle client

  2. Response Object : handle server.

Steps to crete node server:-
create a file server.js/index.js : : most important file which intialises the server or which set-ups server.

No Application is possible without node-server file.

step1:-
create const reference for http module.

const http = require('http');

step2 :-
using http Object createServer Interface.

    http.createServer((request,response)=>{

    });

step3:-
Now set up a port where you want Your server launch.
Never use following
port => 80 => Apache
port => 3000 => React
port => 5000 => Django
Note :: Never use reserved Port

Use other port like 👇🏻
8080 => by-default port.(mostly used)
7080
7000
const PORT=8080;

http.listen(PORT,()=>{
    console.log("Server started successfully at port"+PORT);
});

Complete Code 👇🏻

//http require
const http = require('http');
// port 
const PORT=8080;

//create server using http Object
const server = http.createServer((request,response)=>{

    response.writeHead(200,{"Content-Type":"text/plain"});
    response.write("<h1>Hello Coders</h1>")
    response.end();
});

//listen to the port;
server.listen(PORT,function(){
    console.log('Server Started at PORT ='+PORT);
}); //Asynchronous : callback

in sort for use below command

require('http').createServer((rq,rs)=>{
    rs.write("<h1>Hello Baccho</h1>")
    rs.end();
}).listen(8080,function(){
    console.log("Server Started");
})

How to send Json Response to the Browser

  1. You should have a Array of Json Object which can be send as response to server.
  2. set the Content-Type : application/json
  3. use JSON.stringify() to encode the json to string : Serialization.

Note : : Why we are using JSON.stringify, because of two reasons

  1. response.write() only takes string input
  2. Browser only Understand text or tag.

Code 👇🏻

let student = [

    {
        "id": 1,
        "name": "XYZ",
        "class": "10th",
        "email": "[email protected]",
        "mobile": "9999999990"
    },
    {
        "id": 2,
        "name": "ABC",
        "class": "12th",
        "email": "[email protected]",
        "mobile": "9999999990"
    },
    {
        "id": 3,
        "name": "Raj",
        "class": "Naam to suna hi hoga",
        "email": "[email protected]",
        "mobile": "9999999990"
    }
];

require('http').createServer((rq, rs) =>
{
    rs.writeHead(200, { "Content-Type": "application/json" });
    rs.write(JSON.stringify(student));
    rs.end();
}).listen(8080, () =>
{
    console.log("Server Started at port 8080");
})

How to send html Response to the Browser :-

1. response.writeHead(200,{"Content-Type":"text/html"});
2. response.write("<h1>This is Heading</h1>");

Note here is problem :-
You cannot write lot of html code.
You can use template string and Write the web-page code and you can then pass that variable as response to write();

Problem:-


Right now we are writting all data level code and design level code in server.js

data level => model
design level => View
hence we must organise the data in mvc design pattern to follow modular approach.

Project structure of MVC Node Application:-

Controller
model
View
index.js or server,js
.env => configuration or Environment variable.
.gitIgnore
package.json
package-lock.json

This project structure is common for all, projects.

controller => folder mkdir
model => folder mkdir
view => folder mkdir
index.js => js file touch
package.json => npm init -y
package-lock.json => npm install mvc

Note : : package.json will install node_modules folder if any dependencies are added in package.json

& please make use of git bash terminal

Making a Node Module:-

  1. module.exports = {}
  2. exports.var = var;

Note :: module.exports/exports both referes to global empty Object
this => {} => global empty Object.

	   module = {exports : {x:10}}
	   module.exports = {x:10}
	   module.exports.x=10
	   
	   var x=10;
	   module = {exports:x}
	   module.exports = x;

In flexible there is no difference B/w module.exports and exports.
but in strict mode we cannot use exports directly.
it is because module is a mendatory, Object in strict mode.
but since module refer to this Object. you can pass varaible in following
        1. module.exports = x;
		2. this.exports = x;
		3. exports.x=x;
		   |
		   this => module.
		   
		   exports === module.exports : strict mode : off 
		   exports != module.exports : strict mode : on

Implementation modularity in mvc:-

We know that,
m => model
v => view
c => controller

It is always better approach, to keep the different Js file with in different associated folder such that modularity of the project can be maintained.
StudentModel.js Model suffix => pascal case
StudentController.js Controller suffix => pascal case.
students.js =>view lovwecase suffix.
Note :: Template Engine
pug : students.pug
EJS : student.ejs
jade : student.jd
handlebars : student.hbs
mustaches : mts

These template files on views are called as partials. Views
| partials ....template Engines.

| layouts index.html,index.js

StudentModel.js
data of the Student model =>
Api call => student data.

var studentModel = {
    students:[
        {
            "id":1001,
            "name": "Prabhat",
            "class": "Btech",
            "stream": "CS"
        },
        {
            "id":1002,
            "name": "virat",
            "class": "Btech",
            "stream": "IT"
        },
        {
            "id":1003,
            "name": "Salmon",
            "class": "BA",
            "stream": "Hindi"
        },
        {
            "id":1004,
            "name": "Akash",
            "class": "MBA",
            "stream": "IT"
        },
    ]
}

module.exports = studentModel

StudentController.js
const studentModel = require("./studentModel");

  1. data from model to controller

Response Object it must contain
1. code : 201
2. data : it can be array or object [], {}
3. status : true or false
4. message or comment : "Login Successfull","Oops something, went wrong".
5. error : by-default it will be false, if any error error message will be raised

        let response = {};

        try and catch.
        let promise = fetch(url).then().then.catch((error)=>{
            let responseError = error
        });

        JsonResponse = {
            "code" : 404,
            "message" : "Runtime Exception cannot Post data",
            "data" : [],
            "status" : false
            "error" : responseError
        }

        response.writeHead(200,{"Content-Type":"application/json"})
        or
        response.writeHead(200,{"Content-Type":"application/json;Charset=utf-8"})
        response.write(JSON.stringify(JsonResponse));

Generating Pretty JSON Response :-

by default when you will be using express module. you will get json() method, to print the output in pretty mode. but we are not using "express" module hence, we need to use JSON.stringify() to print the output in pretty mode.
pretty mode in JSON.stringify() :-

JSON.stringify({name:"prabhat",class:"Diploma"})

output :

    {name:"prabhat",class:"Diploma"}

pretty Output :-
you need to increase padding width or pretty width
JSON.stringify(object,null,Pwidth)
Pwidth = 1,2,..................n
standard : 4

JSON.stringify({name:"prabhat",class:"Diploma"},null,4)

Output :

{name:"prabhat",class:"Diploma"}
{
    name:"prabhat",
    class:"Diploma"
}