0% found this document useful (0 votes)
8 views

Node Lecture01

node lecture tutorial for beginner

Uploaded by

Md Nisu Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Node Lecture01

node lecture tutorial for beginner

Uploaded by

Md Nisu Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Node.

js

Get started with hello world!


console.log(`hello world! with process and argv`)

function add(a,b)
{
return a+b;
}
// console.log(add(2,8));

// nodejs run on vs engine


// global object running in node js process is a global object
// process its looks over te all the enviroment thant run al variable

// console.log(process.argv);

// output
/*
E:\node_cn_practive>node index.js 1 2
hello world!
[
'C:\\Program Files\\nodejs\\node.exe',
'E:\\node_cn_practive\\index.js',
'1',
'2'
]
*/

// slice operator
// var args=process.argv.slice(2);
// console.log(`adding proocess argv : ${args[0]} + ${args[1]} =
${add(parseInt(args[0]), parseInt(args[1]))}`)

var args=process.argv;
console.log(`adding proocess argv : ${args[2]} + ${args[3]} =
${add(parseInt(args[2]), parseInt(args[3]))}`)

// console.log("adding the numbers ",add(parseInt(args[0],parseInt(args[1]) )))

// Node uses _________ engine in core.


/*
Options
This problem has only one correct answer
SpiderMonkey
Microsoft Chakra
Chrome V8 ^
Node En
*/
// Node.js is capable of asynchronous I/O requests.

Module
Create a folder with name module
Module
operations.js
script.js
operations.js
// i need available this funcion outside this operatio so
// export it

// key =add
// value= function(a,b){return a+b;}
module.exports.add= function(a,b){
return a+b;
}

// they wont accessible from outside


// module.exports.multiply =function (a,b){
// return a*b;
// }

// reduce the size of module

exports.multiply =function (a,b){


return a*b;
}
script.js
// how to import it
// first i need store it in a variable

const operations=require('./operations')

console.log(operations.add(1,5))
console.log(operations.multiply(1,5))

Reusable Javascript File


Send Feedback
Simple or complex functionality organized in a single or multiple JavaScript files which can be
reused throughout your Node.js application is called ________ Module.

Options
This problem has only one correct answer
Module Library Package Function

Accessing Node Module Externally


Send Feedback
How Node.js modules are made available externally? module.exports
infoYou have max 2 attempts to score in this question.

Attempts left:
1/2
Options
This problem has only one correct answer
module.exports module.expose module.imports module.spread None of the
above

Including a Module
Send Feedback
Which function is used to include modules and libraries in Node Js? require
infoYou have max 2 attempts to score in this question.

Attempts left:
1/2
Options
This problem has only one correct answer
include(); require(); attach(); None of the above

Npm –Node package manager

Whenever we install node it installed by defaut by node

Check it version terminal> npm –v

Node.js : Writing Our First Server


What is server?
A sever is something which is serve which data is is share to client

Setting up our first server

// httpl module
const http=require('http')
const port=8000;
// what is a port
// any snipet of your program or software runnign on a specific port

const server= http.createServer();


// if the listen port is not run then this function run by default and pass an
err
server.listen(port,function(err){
if(err){
console.log(err);
return;
}
console.log("server re warm up and running on port:"+port)
});
// localhost is similar to 127.0.0.1 both are same synonyms

Which command will be used to set up a new or existing package?


infoYou have max 2 attempts to score in this question.

Attempts left:
0/2
Options
This problem has only one correct answer
node init node create npm init npm create

Which of the following will create an instance of HTTP module in Node.js file?
infoYou have max 2 attempts to score in this question.

Attempts left:
1/2
Options
This problem has only one correct answer
var http = require("http"); var http = new require("http"); var http = new server(); none
of the above

Request and Response

// httpl module
const http = require('http')
const port = 8000;
// what is a port
// any snipet of your program or software runnign on a specific port

// request handler because our server is loading again n again


function requestHandler(request, response) {
console.log(request.url)
/**
* server re warm up and running on port:8000
/
/
/home
/home/i_love_YOU

*/
// by url of goole passing

response.end("gothca")

const server = http.createServer(requestHandler);


// if the listen port is not run then this function run by default and pass an
err
server.listen(port, function (err) {
if (err) {
console.log(err);
return;
}
console.log("server re warm up and running on port:" + port)
});
// localhost is similar to 127.0.0.1 both are same synonyms

Write head on html page

response.writeHead(200,{"content-type":"text/html"})
response.end("<h1> hello world</h1>")

Reading and Serving HTML From a File

Index.js
// httpl module
const http = require('http')
const port = 8000;
// what is a port
// any snipet of your program or software runnign on a specific port
// reading and writing file fs
const fs= require('fs')

// request handler because our server is loading again n again


function requestHandler(request, response) {
console.log(request.url)
/**
* server re warm up and running on port:8000
/
/
/home
/home/i_love_YOU

*/
// by url of goole passing
response.writeHead(200,{"content-type":"text/html"})
fs.readFile('index.html',function(err,data){
if(err){
console.log(err);
return;
response.end("<h1> error occured</h1>")
}
response.end(data)

})
// response.end("<h1> hello world</h1>")

const server = http.createServer(requestHandler);


// if the listen port is not run then this function run by default and pass an
err
server.listen(port, function (err) {
if (err) {
console.log(err);
return;
}
console.log("server re warm up and running on port:" + port)
});
// localhost is similar to 127.0.0.1 both are same synonyms

Index.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>load server</title>
<style>
body{
align-items: center;
text-align: center;
margin: 0;
background-color: midnightblue;
}
</style>
</head>
<body>
<h1>I am khan</h1>
</body>
</html>
Output

Which HTTP status code signifies the client does not have access rights to the content, the server is
refusing to give the requested resource. You can visit the following link for exploring different HTTP
Status codes.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Answer

Correct Answer

Which of these sends a Response HTTP Status Code 200 to the browser?
infoYou have max 2 attempts to score in this question.

Attempts left:
0/2
Options
This problem has only one correct answer
res.sendHeader(200, {'content-type': 'text/html'});
res.write(200, {'content-type': 'text/html'});
res.writeHead(200, {'content-type': 'text/html'});
res.writeHeader(200, {'content-type': 'text/html'});
check_circleHurray! Correct Answe

Which of the following modules can be used for file specific operations?
infoYou have max 2 attempts to score in this question.

Attempts left:
1/2
Options
This problem has only one correct answer
path fs http None of the above

If a file named 'file.txt' exists and an error occurred while reading a file using the code below -
fs.readFile('./file.txt', (err, data)=>{
if(err) {
console.log("Inside gets printed.");
}
console.log("Outside gets printed.");
});
What will be the output shown in the terminal/console?
infoYou have max 2 attempts to score in this question.

Attempts left:
1/2

Options
This problem has only one correct answer

Inside gets printed. Outside gets printed. Inside gets printed. Outside gets printed.
error occurs and gets printed on the console

What is the first parameter of the callback function inside the 'readFile' function of 'fs' module?
infoYou have max 2 attempts to score in this question.

Attempts left:
1/2
Options
This problem has only one correct answer
Data of the file Error Any of the two None of them

The code below is used to select the file to display according to the requested URL . -
Suppose you have assigned port number: 8000)
switch(request.url) {
case '/home':
filePath = './index.html';
break;
case '/profile':
filePath = './profile.html';
break;
default:
filePath = './404.html';
}
What will happen if the URL -‘127.0.0.1: 8000' gets hit?
infoYou have max 2 attempts to score in this question.

Attempts left:
1/2

Options
This problem has only one correct answer
'index.html' file gets displayed on the browser 'profile.html' file gets displayed in the browser
'404.html' file gets displayed in the browser the code will not work, so nothing is displayed in
the browser

check_circleHurray! Correct Answer

Extending to Multiple Pages

404.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>Requested not found</title>
<style>
body{
color: brown;
}
</style>
</head>
<body>
<h1>o m g how'd you reach this path?</h1>
<p>Just kidding , this page doesn't exixt</p>
</body>
</html>

Index.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>load server</title>
<style>
body{
align-items: center;
text-align: center;
margin: 0;
background-color: midnightblue;
}
</style>
</head>
<body>
<h1>I am khan</h1>
<h2>I am khan</h2>
</body>
</html>

profile.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>Requested not found</title>
</head>
<body>
<ul>
<li><h3>Md nishu ahamd</h3>
<p>full stack mern developer</p>
</li>
<li><h3>md Uvais ahamd</h3>
<p>full stack developer</p>
</li>
<li><h3>Musharrah Shaykh</h3>
<p>full stack mern developer</p>
</li>

</ul>
</body>
</html>

index.js

// httpl module
const http = require('http')
const port = 8000;
// what is a port
// any snipet of your program or software runnign on a specific port
// reading and writing file fs
const fs= require('fs')

// request handler because our server is loading again n again


function requestHandler(request, response) {
console.log(request.url);
response.writeHead(200,{"content-type":"text/html"})

let filePath;
switch(request.url){
case '/':
filePath='./index.html'
break;
case '/profile':
filePath='./profile.html'
break;
default:
filePath='./404.html'
}

fs.readFile(filePath,function(err,data){
if(err){
console.log("any err:"+err);
return response.end('<h1>Error!</h1>')
}
return response.end(data)
})
// response.end("<h1> hello world</h1>")

const server = http.createServer(requestHandler);


// if the listen port is not run then this function run by default and pass an
err
server.listen(port, function (err) {
if (err) {
console.log(err);
return;
}
console.log("server re warm up and running on port:" + port)
});
// localhost is similar to 127.0.0.1 both are same synonyms
How to get the requested URL, if req is the request variable.
infoYou have max 2 attempts to score in this question.

Attempts left:
0/2
Options
This problem has only one correct answer
req.url() req.url req.get(url); req.get(url());

Q) Difference between package.json and package-lock.json?

What is web framework?


Handling our static pages

What is MVC structure?


Model View Controller

MVC Framework The MVC (Model-View-Controller) is an architectural pattern that separates an


application into three main logical components: the model, the view, and the controller. Each of these
components are built to handle specific development aspects of an application. MVC is one of the most
frequently used industry-standard web development frameworks to create scalable and extensible
projects.

Models
The Model component corresponds to all the data-related logic that the user works with. It is the
representation of information or data that you want to display to user. Model gets all these data from
database and data can be read, updated and deleted.

View
It is all the front end code via which the website is presented in front of the user. It includes all the CSS,
HTML and JavaScript. Any ajax is called in view. Using view, the user interacts with the website.

Controller
It acts as the interface between the Model and View. The controller responds to the user input and
performs interactions on the data model objects. The controller receives the input, optionally validates
it and then passes the input to the model. For example, if a user wants to see their profile, view will
send the request to controller, in controller the code to read the profile will execute and send a request
to model. After this model will return the requested data by controller will display the data via view to
the user. These are some extra links to read. (Some concepts might be difficult to understand right now,
but don’t worry. These are just for giving you brief idea of other frameworks and how they work) MVC
Real Life Example https://medium.freecodecamp.org/simplified-explanation-to-mvc-5d307796df30
MVC MVP and MVVM Frameworks https://medium.com/@ankit.sinhal/mvc-mvp-and-mvvm-design-
pattern-6e169567bbad

Core Features Express


Send Feedback

What are core features of Express framework?


infoYou have max 2 attempts to score in this question.

Attempts left:
1/2

Options
This problem has only one correct answer

Allows to set up middlewares to respond to HTTP Requests

Defines a routing table which can work as per HTTP Method and URL

Dynamically render HTML Pages


All of the above

node_modules
Send Feedback

What does the 'node_modules' folder contain?


infoYou have max 2 attempts to score in this question.

Attempts left:
1/2

Options
This problem has only one correct answer

Libraries that Node.js requires

Install

>npm i express

Contact list app


Basics

const express=require('express');
const port=8000;
const app=express()

// type request
// 1 get() already present in data base
// 2 post() already present in data base and change done in databse
// below using ajax using asynchronos
// 3 put() put some data in databse fill any info
// 4 patch() put some data in databse fill any info
// 1 delete() put some data in databse

// app.get('/',function(req,res){
// res.send("hello")
// console.log(req)
// })
// return some pages
app.get('/',function(req,res){
res.send("cool it is running")
})
// template engine
// mvc

app.listen(port,function(err){
if(err)
console.log("err:"+err)
console.log(`yup my first express Serrver is runnin on port ${port}`)

})

Template Engine?

Ans

Provide features

Fetch an html

Template Engine

1 handlebars <hbs>

2 ejs embedded js

3 pug

Setting a template engine engine

Contact list
View folder
Home.ejs

<!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>Ejs</title>
</head>
<body>
<h1>Rendered from ejs!</h1>
</body>
</html>

Index.js

const express=require('express');
const path=require('path')
const port=8000;
const app=express()
// app has multiple property
/**
app=>{
propertes
propertes
propertes
}
*/

// app has view engine property with ejs below code


app.set('view engine','ejs')

// let choose our view or template directory as public


// create a new folder for view

app.set('views',path.join(__dirname,'views'))

app.get('/',function(req,res){
// to see wheree our directory
// console.log(__dirname)
// res.send("cool it is running")
// since we have renderweing so returned stament is use
return res.render('home')
})

app.listen(port,function(err){
if(err)
console.log("err:"+err)
console.log(`yup my first express Serrver is runnin on port ${port}`)
})

________ prints the value of x into the ejs template (HTML)


infoYou have max 2 attempts to score in this question.

Attempts left:
0/2

Options
This problem has only one correct answer

<% x %> <%_ x %> <%= x %> <%# x %>

Revise
1) Install ejs
2) App.set
a. App.set view engine
b. App.set view path
3) Views folder
4) Rendered using res.render(‘home’)
How to debug
1) Either not including library
2) Syntax error
a. brackets close
b. coats “ ” ‘ ’
3)

Rendering our first page

Ejs
i. <% for (let i=1; i<=5; i++) { %>
<%= i %>
<%}%>
ii. <% for (let i=1; i<10; i++) { %>
<% i %>
<%}%>

iii. <%= for (let i=1; i<10; i++) { %>


<%= i %>
<%}%>

iv. <% for (let i=1; i<10; i++) { %>


<%= i %>
<%=}%>
infoYou have max 2 attempts to score in this question.

Attempts left:
1/2
Options
This problem has only one correct answer
i ii iii iv
i. <% if true{ %>
<h1>It's true!</h1>
<% }else{ %>
<p>It's false :(</p>
<% } %>

ii. <% if (true){ %>


<h1>It's true!</h1>
<% else %>
<p>It's false :(</p>
<% } %>

iii. <% if (true){ %>


<h1>It's true!</h1>
<% }else{ %>
<p>It's false :(</p>
<% } %>

iv. <%= if (true){ %>


<h1>It's true!</h1>
<% }else{ %>
<p>It's false :(</p>
<% } %>
infoYou have max 2 attempts to score in this question.

Attempts left:
0/2
Options
This problem has only one correct answer
i ii iii iv
Locals
Locals is a global object and this local is available globaly to all my virews irrespective which
templaye engine we are using
Body parser
Npm I body-parser
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: false}));

index.js

const express=require('express');
const path=require('path')
const port=8000;
const app=express()
var arrayList=[
["css"],
["html"],
["js"],
["python"],
["node"],
["react"],
]

var contactList=[
{
name:"md nishu Ahmad",
phone:"+91 9122812078"
},
{
name:"MD Uvais Ahmad",
phone:"+91 8452145752"
},
{
name:"Musarraf Shaikh",
phone:"+91 9563215485"
},
{
name:"Kiran Kumar",
phone:"+91 8123548652"
},
]
// app has multiple property
/**
app=>{
propertes
propertes
propertes
}
*/

// app has view engine property with ejs below code


app.set('view engine','ejs')

// let choose our view or template directory as public


// create a new folder for view

app.set('views',path.join(__dirname,'views'))

// home
app.get('/',function(req,res){
// to see wheree our directory
// console.log(__dirname)
// res.send("cool it is running")
// since we have renderweing so returned stament is use
return res.render('home',{title:"my contact list"})
})

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

return res.render('practice',
// context this part
{array_List:contactList,
title:"ejs context"}
)
})
app.listen(port,function(err){
if(err)
console.log("err:"+err)
console.log(`yup my first express Serrver is runnin on port ${port}`)

})
practice.js

<!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>
<%= title%>
</title>
</head>

<body>

<h1> this is a array forEach</h1>


<ul>
<% array_List.forEach(function(result){ %>
<li>
<h4><%= result.name %></h4>
<h5><%= result.phone %></h5>
</li>
<% }); %>
</ul>

<h1> play with ejs</h1>


<h4>for(let i=0;i< 6;i++) </h4>

<ul>
<% for(let i=0;i< array_List.length;i++){ %>
<li>
<p><%= i %> </p>
<%= array_List[i].name %> <br>
<%= array_List[i].phone %> <br>
</li>
<% } %>
</ul>
<h4>if else in ejs</h4>

<% if (true){ %>


<h4>true</h4>
<%}
else{%>
<h4>false</h4>
<% }%>

</body>

</html>

Parser?

// it takes data fromt he browser


/**
* {
* name: nishu
* phone: 94212
* }
* this is parser
* create req key as
* req= body:{
* name: "value"
* phone:" value"
* }
*/

It is a middleware beacouse it is put in middle of req and receive


App.use() // sigmigy it is middleware
What is middleware?
Is a function which aloso has access a request response and it can anayliaze yoyr data
It has capability to access a form data and convert them into key and value pair
Figure:-

Browser===- mw1==mv2==-mw3===- home.ejs===controller


When form is submit it saves the data and goes gome and after it goest to post of get it
redirect again at home page so home page is run twice so therefore middleware run twice

middleware

const express = require('express');


const path = require('path')
const port = 8000;
const app = express()

// parser ?
// it takes data fromt he browser
/**
* {
* name: nishu
* phone: 94212
* }
* this is parser
* create req key as
* req= body:{
* name: "value"
* phone:" value"
* }
*/
var arrayList = [
["css"],
["html"],
["js"],
["python"],
["node"],
["react"],
]

var contactList = [
{
name: "md nishu Ahmad",
phone: "+91 9122812078"
},
{
name: "MD Uvais Ahmad",
phone: "+91 8452145752"
},
{
name: "Musarraf Shaikh",
phone: "+91 9563215485"
},
{
name: "Kiran Kumar",
phone: "+91 8123548652"
},
]
// app has multiple property
/**
app=>{
propertes
propertes
propertes
}
*/

// app has view engine property with ejs below code


app.set('view engine', 'ejs')

// let choose our view or template directory as public


// create a new folder for view

app.set('views', path.join(__dirname, 'views'))


// middle ware here
app.use(express.urlencoded())
// another middle ware
app.use(function(req,res,next){
req.name="khan kahn"
console.log("middle ware 1 called");
// it stuck on loading so use next()
next()//it stop stucking
})

// another middleware2
app.use(function(req,res,next){
console.log("my name from mw2: ",req.name)
console.log("middle ware 2 called");
// it stuck on loading so use next()
next()//it stop stucking
})
// home
app.get('/', function (req, res) {
console.log("my name from get : ",req.name)

// to see wheree our directory


// console.log(__dirname)
// res.send("cool it is running")
// since we have renderweing so returned stament is use
return res.render('home',
{
array_List: contactList,
title: "ejs context"
}
)
})

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

return res.render('practice',
// context this part
{
array_List: contactList,
title: "ejs context"
}
)
})

// create contact controller


app.post('/create-contact', function (req, res) {

// access request data


console.log(req.body.name)
console.log(req.body.phone)
// contactList.push({
// name:req.body.name,
// phone:req.body.phone
// })
// return res.redirect('/')
contactList.push(req.body)
return res.redirect('back')
})
app.listen(port, function (err) {
if (err)
console.log("err:" + err)
console.log(`yup my first express Serrver is runnin on port ${port}`)

})
Middleware functions are functions that have access to the request object (req), the response object
(res), and the next function in the application’s request-response cycle. The next function is a function in
the Express router which, when invoked, executes the middleware succeeding the current middleware.

Middleware functions can perform the following tasks: ⚫ Execute any code. ⚫ Make changes to the
request and the response objects. ⚫ End the request-response cycle. ⚫ Call the next middleware in the
stack.

Tasks of Middleware
Send Feedback
Which among these are the task that a middleware function can perform?
infoYou have max 2 attempts to score in this question.

Attempts left:
1/2
Options
This problem has only one correct answer
Execute any code. Make changes to the request and the response objects. End the
request-response cycle. Call the next middleware function in the stack. All of the Above

What will get printed in the console if http://localhost:8000/ is visited and these are the middlewares
defined in index.js?
app.use(function(req, res, next){
console.log('middleware 1 called');
});

app.use(function(req, res, next){


console.log('middleware 2 called');
next();
});

app.use(function(req, res, next){


console.log('middleware 3 called');
next();
});
infoYou have max 2 attempts to score in this question.

Attempts left:
0/2
Options
This problem has only one correct answer
middleware 1 called middleware 1 called middleware 2 called middleware 1 called
middleware 2 called middleware 3 called None of the Above

Solution Description
Before the controller, all the middlewares get executed in chronological order. So first middleware -1 is called.
But since we haven’t called the next() function in it, the next middleware doesn’t get triggered. That is why only
“middleware 1 is called” is printed.

fontAwesone
cdn content delivery network
Static files
Asstes middleware

Quick Revision
1) Index.js
2) Npm init
3) Npm I express
a. Server
4) Npm I ejs
a. Use ejs (app.set())
b. Path of views
c. Ejs file as home.ejs
5) Create route app.get(‘route’,callBackControllerFunction(req,res){return
res.(“which_route”,{Context:”data_of_context”});});
6) Form +post-req
7) Static files (assests)
a. Image
b. Script
c. Css

Contact list
File structure

Index.js

const express = require('express');


const path = require('path')
const port = 8000;
const app = express()

// parser ?
// it takes data fromt he browser
/**
* {
* name: nishu
* phone: 94212
* }
* this is parser
* create req key as
* req= body:{
* name: "value"
* phone:" value"
* }
*/
var arrayList = [
["css"],
["html"],
["js"],
["python"],
["node"],
["react"],
]

var contactList = [
{
name: "md nishu Ahmad",
phone: "919122812078"
},
{
name: "MD Uvais Ahmad",
phone: "918452145752"
},
{
name: "Musarraf Shaikh",
phone: "919563215485"
},
{
name: "Kiran Kumar",
phone: "918123548652"
},
]
// app has multiple property
/**
app=>{
propertes
propertes
propertes
}
*/
// app has view engine property with ejs below code
app.set('view engine', 'ejs')

// let choose our view or template directory as public


// create a new folder for view

app.set('views', path.join(__dirname, 'views'))


// middle ware here
app.use(express.urlencoded())
// it is another middleware that load the static files
app.use(express.static('assets'))
// another middle ware
// app.use(function(req,res,next){
// req.name="khan kahn"
// console.log("middle ware 1 called");
// // it stuck on loading so use next()
// next()//it stop stucking
// })

// // another middleware2
// app.use(function(req,res,next){
// console.log("my name from mw2: ",req.name)
// console.log("middle ware 2 called");
// // it stuck on loading so use next()
// next()//it stop stucking
// })
// home
app.get('/', function (req, res) {
console.log("my name from get : ",req.name)

// to see wheree our directory


// console.log(__dirname)
// res.send("cool it is running")
// since we have renderweing so returned stament is use
return res.render('home',
{
array_List: contactList,
title: "ejs context"
}
)
})

// practice
app.get('/practice', function (req, res) {
return res.render('practice',
// context this part
{
array_List: contactList,
title: "ejs context"
}
)
})

// create contact controller


app.post('/create-contact', function (req, res) {

// access request data


console.log(req.body.name)
console.log(req.body.phone)
// contactList.push({
// name:req.body.name,
// phone:req.body.phone
// })
// return res.redirect('/')
contactList.push(req.body)
return res.redirect('back')
})

// delete a contact
// app.get('/delete-contact/',function(req,res){
// console.log(req.query);
// let phone = req.query.phone

// let contactindex = contactList.findIndex(contact => contact.phone ==


phone);

// if(contactindex != -1){
// contactList.splice(contactindex, 1);
// }
// return res.redirect('back');

// // contactList=contactList.filter(function(itme){
// // // console.log("by filetr"+tyitme.phone)
// // return itme.phone!=deleted_phone

// // })
// // return res.redirect('back')
// })

app.get('/delete-contact/', function(req, res){


console.log(req.query);
let phone = req.query.phone

let contactindex = contactList.findIndex(contact => contact.phone == phone);

if(contactindex != -1){
contactList.splice(contactindex, 1);
}

return res.redirect('back');
});

app.listen(port, function (err) {


if (err)
console.log("err:" + err)
console.log(`yup my first express Serrver is runnin on port ${port}`)

})

Home.ejs

<!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">
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/6.2.0/css/all.min.css"
integrity="sha512-
xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXlo
TyT2A=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<title>
<%= title %>
</title>
</head>

<body>

<div class="list-container">
<span>
<h1 id="page-heading"><i class="fa-solid fa-address-book"></i> Contact
list</h1>
</span>
<ul>
<% array_List.forEach(function(result){ %>
<li>
<div class="list">
<p> <%= result.name %></p>

<p > <%= result.phone %></p>


</div>

<div class="delete-button">
<!-- <a href="/delete-contact/<%= result.phone %> "><i
class="fas fa-window-close"></i> -->
<a href="/delete-contact/?phone=<%= result.phone %>">
<i class="fas fa-window-close"></i>
</a>
</div>
</li>
<% }); %>
</ul>

<form id="form-container" action="/create-contact" method="post">


<input type="text" name="name" id="" placeholder="Enter Name"
required>
<input type="number" name="phone" id="" placeholder="Enter Phone"
required>
<button type="submit" id="submit-button">Create Contact</button>
</form>
</div>
<!-- <h3>Create new contact here</h3> -->

<!-- form filled -->


<!-- submit -->
<!-- action route -->
<!-- redirect -->

<script src="/js/script.js"></script>
</body>

</html>

Style.css

body{
margin: 0;
/* text-align: center; */
background-color: azure;
font-family: sans-serif;
}

ul li{
color: rgb(255, 255, 255);
width: 100%;
list-style: none;
text-transform: capitalize;
padding: 0px 15px;
background-color: rgb(23, 211, 211);
/* margin-left: 0; */
border-bottom: .35rem solid white;
}

ul li:hover{
background-color: rgb(161, 140, 140);

#page-heading{
text-align: center;
margin-top: 25px;
color: gray;
}
.list-container{
margin-left: 28%;
max-width: 520px;
display: flex;
justify-content: center;
flex-direction: column;

#submit-button{
background-color: gray;
color: rgb(250, 250, 250);
border-style: none;
height: 35px;
width: 120px;
}

input{

border-top: none;
border-left: none;
border-right: none;
/* border: none; */
border-bottom: 1px solid grey;
width: 200px;
height: 30px;
/* border-bottom: 2px solid rgb(159, 159, 219) ; */
/* border-right: 2px solid rgb(159, 159, 219) ; */
}

.list{
display: flex;
justify-content: space-between;
}

#form-container{
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
justify-content: space-between;
margin-left: 33px;
max-width: 600px;
float: left;
}

.delete-button i{
color: rgb(206, 0, 0);
}
.delete-button i:hover{
color: rgb(253, 0, 0);
}

Intro to database
-Stroring flies
Types od databases
1) Tables format
2) Json format
Table format
Mysql ,postGRES
json format
firebase,redis,mongoDB

MongoDB
1) Ease to use
2) Do not need to tabular structure
3) Very structre of organizing data
Why mongodb
1) Mean stack
2) Mern stack
A= angular R- react
M=mongodb N= node E= express

You might also like