Node Lecture01
Node Lecture01
js
function add(a,b)
{
return a+b;
}
// console.log(add(2,8));
// 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]))}`)
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;
}
const operations=require('./operations')
console.log(operations.add(1,5))
console.log(operations.multiply(1,5))
Options
This problem has only one correct answer
Module Library Package Function
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
// 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
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
// 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
*/
// by url of goole passing
response.end("gothca")
response.writeHead(200,{"content-type":"text/html"})
response.end("<h1> hello world</h1>")
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')
*/
// 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>")
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
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')
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>")
Attempts left:
0/2
Options
This problem has only one correct answer
req.url() req.url req.get(url); req.get(url());
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
Attempts left:
1/2
Options
This problem has only one correct answer
Defines a routing table which can work as per HTTP Method and URL
node_modules
Send Feedback
Attempts left:
1/2
Options
This problem has only one correct answer
Install
>npm i express
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
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.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}`)
})
Attempts left:
0/2
Options
This problem has only one correct answer
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)
Ejs
i. <% for (let i=1; i<=5; i++) { %>
<%= i %>
<%}%>
ii. <% for (let i=1; i<10; i++) { %>
<% i %>
<%}%>
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>
<% } %>
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.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>
<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>
</body>
</html>
Parser?
middleware
// 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
}
*/
// 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)
// practice
app.get('/practice', function (req, res) {
return res.render('practice',
// context this part
{
array_List: contactList,
title: "ejs context"
}
)
})
})
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');
});
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
// 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')
// // 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)
// practice
app.get('/practice', function (req, res) {
return res.render('practice',
// context this part
{
array_List: contactList,
title: "ejs context"
}
)
})
// delete a contact
// app.get('/delete-contact/',function(req,res){
// console.log(req.query);
// let phone = req.query.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')
// })
if(contactindex != -1){
contactList.splice(contactindex, 1);
}
return res.redirect('back');
});
})
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>
<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>
<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