Wad Unit4
Wad Unit4
• Course Outcomes: -
On completion of the course, students will be able to–
CO3: Develop web application with Front End & Back End Technologies.
Node.JS
• NodeJS is an open source server environment.
• Node.js is free.
• Using Node.js we can run JavaScript on the server.
• It runs on various platforms such as Windows, Linux, Unix and
MacOS.
Why Node.js
• Node.js uses asynchronous programming!
• A common task for a web server can be to open a file on the server and
return the content to the client.
console1.js
var emp_name = "ABC",
emp_depts = {
dept1:"Sales",dept2:"Accounts"
};
console.log("Name:%s"+"\n"+"Departments:%j",emp_name,emp_depts);
Methods of console object
Methods of console object
2) console.info([data ][, ...]) : This method is similar to console.log.
console2.js
var emp_name = "ABC",
emp_depts = {
dept1:"Sales",dept2:"Accounts"
};
console.info("Name:%s"+"\n"+"Departments:%j",emp_name,emp_depts);
Methods of console object
3) console.error ([data][, ...]) : This method prints to stderr with newline.
console3.js
var code = 401
console.error("Error",code);
Methods of console object
4) console.warn([data][, ...]): This method is similar to console.error()
method.
• Consider following example - in which using the fs module we open a
text file. If the file does not open successfully then console.warn() method
displays the warning message.
console4.js
var fs = require("fs");
fs.open("input.dat","r",function(err,fs){
if(err)
console.warn("Warning message:",err);
else
console.log("File opening successful!");
})
Node.JS Built-in Modules
• Consider modules to be the same as JavaScript libraries.
• A set of functions you want to include in your application.
• Node.js has a set of built-in modules which you can use without any
further installation.
• To include a module, use the require() function with the name of the
module:
var fs = require("fs");
Node.JS Built-in Modules
(1) assert : This module is used during the testing of expressions. If an
expression evaluates to 0 or false, an error is thrown and program gets
terminated.
app1.js Note that as the 10 is not less than 2, the code
var assert = require("assert"); will raise the error named AssertionError
assert(10 < 2);
Node.JS Built-in Modules
(2) cluster : The cluster module helps in creating a child process. Both
the main and child processes can run simultaneously and share the
same server port. For example -
var cluster = require("cluster");
if(cluster.isWorker){
console.log("Child process");
}
else{
console.log("Main process");
cluster.fork();
cluster.fork(); fork(): Creates a new worker, from a master
cluster.fork(); isWorker: Returns true if the current
process is worker, otherwise false
}
Node.JS Built-in Modules
(3) os : The os module provides the information about operating
system of your computer.
var os = require("os");
console.log("Platform on my computer:"+os.platform());
console.log("Architecture of my computer:"+os.arch());
File System
• File system fs is implemented in the node.js using require function.
var fs = require('fs');
• The common operations used with the file system module are -
1. Read Operation
• The read file operation can be performed synchronously or
asynchronously.
• For reading the file synchronously we use readFileSync method. And
for reading the file asynchronously readFile.
• Normally while reading the file using asynchronous form we use
callback function as the last parameter to the readFile function.
File System
• The form of this callback function is ,
function(err, data){
//function body
}
Example code
var fs = require("fs");
fs.readFile("myfile.txt",function(err,data){
if(err)
console.log(err);
console.log(data.toString());
});
File System
myfile.txt
NodeJS is an open source technology for server.
Using Node.js we can run JavaScript on server.
It runs on various platform such as Windows, Linux, Unix and MacOS.
File System
2. Create File Operation
• We can create an empty file using the command open()
• Syntax:
Open(path.flags[,mode],callback)
Where
path : It is the path of the filename.
flag : It indicates, the behaviour on opening a file. That means "r" is open file
for reading, "w" is for writing, "rs'' is for synchronous mode,"r+" or 'w+"
means open a file for both read and write purpose and so on.
mode : It indicates readable or writable mode.
Callback: It is basically a function which has two argµments(err,data)
File System
2. Create File Operation
• Example:
var fs = require("fs");
fs.open("myfile.txt","w",function(err,file){
if(err)
console.log(err)
console.log("File created!");
});
File System
3. Update / Write File Operation
• For writing to the file two operations are used most commonly –
1. appendf ile() and 2. writeFile()
• The appendFile() method is used to write the contents at the end of
the specified file.
var fs = require("fs");
str = "This line is written to the file.";
fs.appendFile("myfile.txt",str,function(err){
if(err)
console.log(err)
console.log("File appended!");
});
File System
3. Update / Write File Operation
• The writeFile() method is used to write the contents to the file.
var fs = require("fs");
str = "This line is replacing the previous contents.";
fs.writeFile("myfile.txt",str,function(err){
if(err)
console.log(err)
console.log("File writing done!");
});
Node.JS Callback Functions
• Callbacks is a function which is usually passed as an argument to
another function and it is usually invoked after some kind of event.
• The callback function is passed as an argument to another function.
When particular event occurs then only it is invoked.
• By the time callback function is executing another task gets executed.
• Hence execution of callbacks is asynchronous execution.
Node.JS Callback Functions
• Step 1 : Create a simple text file named "myfile.txt" as follows –
//myfile.txt
Event-Driven Architecture
Node.JS Events
• Every time when useir nteracts with the webpage, event occurs when
user clicks mouse button or presses some key on the keyboard.
• When events are triggered, some functions associated with these
events get executed.
• Event driven programming makes use of the following concepts -
i) When some events occur, an event handler function is called. This is
basically a call back function.
ii) The main program listens every event getting triggered and calls the
associated event handler for that event.
Node.JS Events
Concept of Event Emitter :
• EventEmitter is a class which can be used to raise and handle custom
events.
• The Eventmitter is a module that facilitates communication between
objects.
• The emitter objects performs following tasks -
1) It emits named events.
2) Registers and unregisters listener functions.
Node.JS Events
• Steps for using event handling in Node.js
• Step 1 : Import the 'events' module and create an instance of it using
following code –
var events = require(“events”);
• Step 2 : Then create an instance of EventEmitter() class. This, instance is
created because we have to call on() and emit() functions using this
instance.
• Step 3 : Then define a callback function which should be called on
occurrence of event. This function is also called as event listener funciton.
• Step 4 : Then register the event using on() function. To this function name
of the event and callback function is passed as arguments.
• Step 5 : Finally raise the event using emit() function.
Node.JS Event Example Code
eventDemo.js
// get the reference of events module
var events = require("events");
//create an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
var myfunction = function() {
console.log("When event occurs, My Function is called")
}
//Bind FirstEvent with myfunction
em.on('FirstEvent', myfunction);
// Raising FirstEvent
em.emit('FirstEvent');
Node.JS Event Loop
• Various phases of event loop are -
Node.JS Event Loop
1) Timers : This is the first phase in the event loop. It finds expired timers in
every iteration (also known as Tick) and executes the timers callbacks
created by setTimeout and setlnterval.
2) Pending callbacks : It handles I/O callbacks deferred to the next iteration,
such as handling TCP socket connection error.
3) Idle, prepare : It is used internally.
4) Poll : The Poll phase calculates the blocking time in every iteration to
handle I/O callbacks.
5) Check : This phase handles the callbacks scheduled by setlmmediate(), and
the callbacks will be executed once the Poll phase becomes idle.
6) Close callback : This phase handles callbacks if a socket or handle is closed
suddenly and the 'close' event will be emitted.
NPM
• A package in Node.js contains all the files you need for a module.
• Modules are JavaScript libraries you can include in your project.
• The NPM stands for node package manager.
• NPM consists of two main parts :
1) A CLI (command-line interface) tool for publishing and downloading
packages,
2) An online repository that hosts JavaScript packages.
• NPM gets installed along with the installation of node.js.
Web Module Application
• The web module is mainly controlled by a web server that handles the
requests and provides the responses. These requests and responses are
handled by HTTP(Hyper Text Transfer Protocol) protocol.
• The user submits the request using web browser. Thus the communication
between web server and web browser is handled by HTTP protocol.
• Following steps explain this communication –
- when user submits a request for a web page, he/she is actually demanding
for a page present on the web server.
- when web browser submits the request for a web page, the web server
responds this request by sending back the requested page to the web
browser of the client's machine.
Web Module Application
• step 1 : Web client requests for the
desired web page by providing the IP
address of the website.
• Step 2 : The web server locates the
desired web page on the website and
responds by sending back the
requested page. If the page doesn't
exist, it will send back the appropriate
error page.
• Step 3 : The web browser receives the
page and renders it as required.
Client-Server communication
Web Module Application
• Node.js has a built in module named http which allows us to transfer
data over the Hyper Text Transfer Protocol(HTTP).
• A web server using http module, is as follows -
var http = require("http");
var server = http.createServer(function(request,response){
response.writeHead(200,{"Content-Type":"text/plain"});
response.end("Welcome to this Web Module Application!");
});
server.listen(8082);
console.log("Server is running on port 8082 port...");
Socket Server
• Socket : A socket is basically an endpoint of a two-way
communication link between two programs running on the network.
Typically these programs are Server program and Client program.
• Thus socket is OS-controlled interface into which the applications can
send or receive messages to and fro from another application.
Socket Server
Client Server Communication in node.js :
• Server is a device which has resources and from which the services
can be obtained. For example·: there are various types of servers such
as web server which is for storing the web pages, there are print
servers for managing the printer services or there are database
servers which store the databases.
• Client is a device which wants to get service from particular server.
• First of all server starts and gets ready to receive the client
connections, The server-client communications occurs in following
steps
Client Server Communication in node.js
Client Server
Creates TCP socket. Creates TCP socket.
Client initiates the communication. Creates another socket for listening
client.
Communicate. Accept message from client and
repeatedly communicate.
Close the communication. Close the communication.
Socket Server
• We have two build to node.js programs - One for server and other for
client.
TCP Server Program
• To build the TCP server program we have to follow the steps as given below
Step 1 : We use "net' module by adding following line at the beginning of
both the programs –
var net = require(“net”);
Step 2 : Now we use the createServer() method for creating the stream
based TCP server. For that purpose we have to add following code in the
program.
var server = net.createServer();
Socket Server
Step 3 : We use the event handler on for the server when any client gets
connected to it. In this event handling code we use the socket class. The
attributes remoteAddress and remotePort will return the remote address
and port number of the client which is connected currently to the server.
Step 4 : Then using socket instance we can handle three events such as data,
close and error.
O For data event, the data received from the client is displayed on the
console using cosole.log nethod.
O For close event, the connection closing message is displayed to the client
O If any error occurs during establishment of connection, the error event is
fired, and error message is displayed o the console.
Socket Server
Step 5 : During this entire, client server communication Server must be
in listening mode. This can be done using listen method. To this
method, the port number is passed. The same port number must be
used in the client program, so that both the server and client can
communicate on the same port number.
Server.js
var net = require("net");
var server = net.createServer();
server.on('connection', function(socket){
var clientAddress = socket.remoteAddress+":"+socket.remotePort;
console.log("Connection with the client %s is established!",clientAddress);
socket.on('data',function(mydata){
console.log("\n Data received from client is: %s", mydata.toString());
socket.on('error',function(err){
console.log("Connection error %s", err.message);
});
});
server.listen(8082, function(){
console.log("Server is listening to %j", server.address()); });
Socket Server
• TCP Client Program
• Following is a client program, in which we are getting some input
from the user through command prompt and sending that data to the
server. For reading the input from keyboard we need to install
readline-sync module. For installation of this module, open the
command prompt. The installation of this module is as follows -
npm install readline-sync;
Socket Server
• To build the TCP client program we have to follow, the steps as given
below -
• Step 1 : We use "net" module by adding following l1ne at the
beginning of the client program.
var net = require(“net”);
• Step 2 : As our server is running on port number 8082 and the
localhost as the host, the client must run on the same for establishing
the communication between server and the client. The instance of
socket class is created and it is named as var client.
const client = new net.Socket();
Socket Server
• Step 3 : Now it is possible to establish a connection with the server
using connect method. For establishing the connection we should
pass the same hostname and port number as parameter.
• Step 4 : Client can send the data to the server using write method.
• Here we are getting the data when user enters some data through
keyboard. For getting the data from the console, we use the readline-
sync module's question method. The required code for this operation
is -
Socket Server
• Step 5: Two more events can be handled by the client program those
are - data and end.
• On the data event, the data received from the server is displayed on
the console window, using console.log
• On the end event, the we can acknowledge the server than now
client is going to end.
client.js
var net = require("net");
var read_line = require("readline-sync");
const PORT = 8082;
const HOST = 'localhost’;
4.If no middleware ends the cycle, the route handler is reached, and a
final response is sent.
Steps to Implement Middleware in Express
Step 1: Initialize the Node.js Project
npm init –y
Step 2: Install the required dependencies.
npm install express
Steps to Implement Middleware in Express
Step 3: Set Up the Express Application
// Filename: index.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
Step 4: Start the Application:
node index.js
Output:
When you navigate to http://localhost:3000/, you will see:
Serving Static Files
• Static files can be simple html, css or JavaScript files. It is possible to
invoke those files usinge expressJS code.
• For serving the static file, expressJS makes use of app.use() method.
• The app.use() method mounts the middleware express.static for
every request. The express.static middleware is responsible for
serving the static assets of an Express.js application. Inside the
express.static method the path for the desired static file must be
specified.
Example of the express.static() Function
const express = require('express');
const app = express();
const path = require('path');
const PORT = 3000;
// Static Middleware
app.use(express.static(path.join(__dirname, 'public')))
app.get('/', function (req, res, next) {
res.render('home.ejs');
})
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
<!DOCTYPE html>
<html>
<head>
<title>express.static() Demo</title>
</head>
<body>
<h2>Greetings </h2>
<img src="Demo.jpg" width="150" height="100" />
</body>
</html>
Note: Demo.jpg is placed in the public folder, as the public folder is now being served as static to
the server.
REST HTTP Method APIs
• REST stands for Representational State Transfer. It is a set of rules that
developers follow while creating their API.
• Each URL made by the client is a request and data sent back to the
client is treated as response.
• A RESTful API uses HTTP methods to interact with resources.
• Common HTTP Methods: GET, POST, PUT, DELETE.
• Setting Up Express.js
• Install Express:
npm init -y
npm install express
• Create a new app.js file and set up the Express server:
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
• Understanding RESTful Methods
• GET: Retrieve data
• POST: Create new data
• PUT: Update existing data
• DELETE: Remove data
Example: GET & POST Routes
// GET all users
app.get('/users', (req, res) => {
res.json(users); // Send all users as JSON
});
• Install Express:
npm init -y
npm install express
• Create an app.js file and set up the Express server:
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Creating the Basic Authentication Middleware
• Middleware checks the Authorization header.
• Decode the credentials from Base64 and compare them with the
stored values.
• If valid, proceed; otherwise, return 403 Forbidden.
const basicAuth = (req, res, next) => {
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).send('Access Denied: No Credentials Provided');
}
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8');
const [username, password] = credentials.split(':');
const validUsername = 'admin';
const validPassword = 'password123';
if (username === validUsername && password === validPassword) {
return next();
} else {
return res.status(403).send('Forbidden: Invalid Credentials');
}
};
Applying the Middleware
• Apply the basicAuth middleware to protect specific routes (e.g.,
/secure).
const users = {
admin: { username: 'admin', password: 'password123' }
};
Login Route
• Handle POST requests for logging in:
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (users[username] && users[username].password === password) {
req.session.user = { username: users[username].username };
res.send('Login successful! <a href="/protected">Go to protected
page</a>');
} else {
res.status(401).send('Invalid credentials');
}
});
Protected Route
• The /protected route is accessible only to logged-in users:
app.get('/protected', (req, res) => {
if (req.session.user) {
res.send(`<h1>Protected Page</h1><p>Hello,
${req.session.user.username}!</p>`);
} else {
res.status(401).send('You must be logged in to access this page');
}
});
Logout Route
• Destroy the session and log the user out:
app.get('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).send('Could not log out.');
}
res.send('You have been logged out. <a href="/">Go back to
login</a>');
});
});
Example Flow
1. Login: User enters username and password.
2. Create Session: Server creates a session and stores user info.
3. Send Session Cookie: Server sends a session ID to the client as a
cookie.
4. Protected Route: On future requests, the session ID is sent by the
client to authenticate.
Testing the Authentication
1. Login:
• Open the login page (/).
• Enter credentials: admin and password123.
2. Protected Route:
• After login, visit /protected.
• See the protected content if logged in.
3. Logout:
• Click on the logout link to destroy the session.
Syllabus
• Node.JS: Introduction to Node.JS, Environment Setup, Node.JS
Events, Node.JS Functions, Node.JS Built- in Modules, File System,
NPM, Install External Modules, Handling Data I/O in Node.JS, Create
HTTP Server, Create Socket Server, Microservices- PM2.
• ExpressJS: Introduction to ExpressJS, Configure Routes, Template
Engines, ExpressJS as Middleware, Serving Static Files, REST HTTP
Method APIs, Applying Basic HTTP Authentication, Implement Session
Authentication.
• MongoDB: NoSQL and MongoDB Basics, MongoDB-Node.JS
Communication, CRUD Operations using Node.JS, Mongoose ODM for
Middleware, Advanced MongoDB.
NoSQL and MongoDB Basics
• NoSQL stands for not only SQL.
• It is nontabular database system that store data differently than
relational tables. There are various types of NoSQL databases such as
document, key-value, wide column and graph.
• Using NoSQL we can maintain flexible schemas and these schemas
can be scaled easily with large amount of data.
NoSQL and MongoDB Basics
Need :
The NoSQL database technology is usually adopted for following reasons -
1) The NoSQL databases are often used for handling big data as a part of
fundamental architecture.
2) The NoSQL databases are used for storing and modelling structured,
semi-structured and unstructured data.
3) For the efficient execution of database with high availability, NoSQL is
used.
4) The NoSQL database is non-relational, so it scales out better than
relational databases and these can be designed with web applications.
5) For easy scalability, the NoSQL is used.
NoSQL and MongoDB Basics
Features:
1) The NoSQL does not follow any relational model.
2) It is either schema free or have relaxed schema. That means it does not
require specific definition of schema.
3) Multiple NoSQL databases can be executed in distributed fashion.
4) It can process both unstructured and semi-structured data.
5) The NoSQL have higher scalability.
6) It is cost effective.
7) It supports the data in the form of key-value pair, wide columns and
graphs.
MongoDB
• MongoDB is an open source, document based database.
• All the modern applications require Big data, faster development and
flexible deployment. This need is satisfied by the document based
database like MongoDB.
Features of MongoDB
• It is a schema-less, document based database system.
• It provides high performance data persistence.
• It supports multiple storage engines.
• It has a rich query language support.
• MongoDB provides high availability and redundancy with the help of
replication. That means lt creates multiple copies of the data and
sends these copies to a different server so that if one server fails,
then the data is retrieved from another server.
Features of MongoDB
• MongoDB provides horizontal scalability with the help of sharding.
Sharding means to distribute data on multiple servers.
• In MongoDB, every field in the document is indexed as primary or
secondary. Due to which data can be searched very efficiently from
the database.
MongoDB-Node.JS Communication
• For connecting Node.js with MongoDB we need MongoClient. This
can be created using following code.
Connect.js
var MongoClient = require('mongodb'). MongoClient;
var url = "mongodb://localhost:27017/";
//create database
MongoClient.connect(url, function(err, db) {
if (err)
throw err;
var dbo = db.db("studentDB");
console.log("Connected with Database");
});
MongoDB-Node.JS Communication
Program Explanation : in above code,
• First of all, we have to import the module ‘mongodb’ using require.
Thus we are creating MongoDB client.
• Then specify the URL for MongoDB by means of hostname(localhost)
and port number on which MongoDB is running (27017). This is a
path at which we are going to create a database.
• Then we are using connect method by passing the above URL. Inside
this function a database object is created by a database name
“studentDB”.
CRUD Operations using Node.JS
• The CRUD operations are performed in collaboration with Node.js
and MongoDB. The CRUD stands for Create, Read, Update and Delete
operations.
CRUD Operations using Node.JS
• create.js var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
//create database
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("studentDB");
dbo.createCollection("Student_Info",function(err, res) {
if(err)
throw err;
console.log("Collection Created")
});
db.close();
});
CRUD Operations using Node.JS
Insertion of Data
We can insert one document or multiple document at a time.
CRUD Operations using Node.JS
insert.js var MongoClient = require('mongodb'). MongoClient;
var url ="mongodb://localhost:27017/";
//Insert
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("studentDB");
var mydata = { name: "AAA", city: "Pune" };
dbo.collection("Student_Info").insertOne(mydata,function(err, res) {
if(err)
throw err;
console.log(“One document Inserted!");
db.close();
});
});
CRUD Operations using Node.JS
Read Data
We can read all the documents of the collection using find method.
Following is a simple Node.js code that shows how to read the contents
of the database.
CRUD Operations using Node.JS
display.js var MongoClient = require('mongodb'). MongoClient;
var url ="mongodb://localhost:27017/";
//Read
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("studentDB");
var cursor = dbo.collection("Student_Info").find({})
cursor.each(function(err, doc) {
console.log(doc);
db.close();
});
});
CRUD Operations using Node.JS
Updating Data
We can change one or more fields of the document using updateOne
method.
CRUD Operations using Node.JS
update.js var MongoClient = require('mongodb'). MongoClient;
var url ="mongodb://localhost:27017/";
//Update
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("studentDB");
var mydata = {name:”DDD”};
var newdata = {$set:{name:”TTT”, city:”Jaipur”}}
dbo.collection("Student_Info"). updateOne(mydata, newdata, function(err, res) {
if(err) throw err;
console.log(“One document Updated!");
db.close();
});
});
CRUD Operations using Node.JS
Deleting Data
This is the operation in which we are simply deleting the desired
document. Here to delete a single record we have used deleteOne
method.
CRUD Operations using Node.JS
delete.js
var MongoClient = require('mongodb'). MongoClient;
var url ="mongodb://localhost:27017/";
//Delete
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("studentDB");
var mydata = {name:”TTT”};
dbo.collection("Student_Info"). deleteOne(mydata, function(err, res) {
if(err) throw err;
console.log(“One document Deleted!");
db.close();
});
});
Mongoose ODM for Middleware
• ODM stands for Object Data Modelling.
• Mongoose is a MongoDB Object Data Modelling (ODM) tool or library
designed to work in an asynchronous environment with node.js.
• It allows us to connect to the MongoDB database.
• Besides the data modelling in Node.JS Mongoose also provides a layer
of CRUD features on top of MongoDB.
Mongoose ODM for Middleware
• It manages relationships between data, provides schema validation
and is used to translate between objects in code and the
representation of those objects in MongoDB.