SlideShare a Scribd company logo
Department of Information Technology
2023 – 2024 (ODD SEMESTER)
Year : III IT Course Code : IT2304
Faculty Name : Dr. R. Arthy, AP/IT Course Name : Full Stack Web Development
Course code
(as per NBA)
: 21ITC304 Regulation : R2021
UNIT IV
Middleware:
 Middleware functions are the functions that access to the request and response object
(req, res) in request-response cycle.
 A middleware function can perform the following tasks:
o It can execute any code.
o It can make changes to the request and the response objects.
o It can end the request-response cycle.
o It can call the next middleware function in the stack.
Express.js Middleware
Following is a list of possibly used middleware in Express.js app:
 Application-level middleware
 Router-level middleware
 Error-handling middleware
 Built-in middleware
 Third-party middleware
Request Processing:
 Middleware functions are executed in the order they are defined.
 They process the incoming request and can modify the request object, add properties
to it, or perform validations.
Response Handling:
 Middleware functions can also modify the response object (res).
 They can set headers, send a response, or manipulate the response data before it is
sent back to the client.
Chaining Middleware:
 Express allows the chaining of multiple middleware functions.
 Each middleware function in the chain has access to the request and response objects.
The next function is used to pass control to the next middleware in the stack.
Example:
app.use((req, res, next) => {
next(); // Pass control to the next middleware
});
Error Handling:
 Middleware functions can handle errors.
 If an error occurs, the middleware with four parameters (err, req, res, next) is
triggered. This allows for centralized error handling.
Example:
app.use((err, req, res, next) => {
res.status(500).send('Internal Server Error');
});
Authentication and Authorization:
 Middleware is commonly used for authentication and authorization purposes.
 For example, a middleware function can check if a user is authenticated before
allowing access to certain routes.
Example:
const authenticate = (req, res, next) => {
if (userIsAuthenticated) {
next();
} else {
res.status(401).send('Unauthorized');
}
};
app.get('/secured', authenticate, (req, res) => {
res.send('Secured Route');
});
Static File Serving:
 Express provides built-in middleware functions for serving static files.
 This is commonly used to serve CSS, JavaScript, and image files.
Example:
app.use(express.static('public'));
Logging:
 Middleware functions are often used for logging requests, providing valuable insights
into the flow of traffic through the application.
Example:
app.use((req, res, next) => {
console.log(`[${new Date()}] ${req.method} ${req.url}`);
next();
});
Third-Party Middleware:
 Express allows the use of third-party middleware for additional functionality.
 Examples include body parsers for handling request bodies, compression middleware,
and session management middleware.
Example
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Routing:
 In Express.js, routing refers to the process of defining how an application responds to
a client request to a particular endpoint (URL) and HTTP method.
 Express provides a simple and flexible way to handle routing, allowing you to define
routes for different HTTP methods and URL patterns.
Basic Routing:
 A basic example of a route that responds to a GET request at the root URL.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Route Parameters:
 Routes can include parameters, which are specified with a colon : in the route pattern.
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
Handling Different HTTP Methods:
GET Request:
 Responds to a GET request.
app.get('/users', (req, res) => {
// Handle GET request for /users
});
POST Request:
 Responds to a POST request.
app.post('/users', (req, res) => {
// Handle POST request for /users
});
PUT Request:
 Responds to a PUT request.
app.put('/users/:id', (req, res) => {
// Handle PUT request for /users/:id
});
DELETE Request:
 Responds to a DELETE request.
app.delete('/users/:id', (req, res) => {
// Handle DELETE request for /users/:id
});
Middleware in Routing:
Middleware Function:
 Middleware functions can be used in routing to perform tasks before sending a
response.
const middlewareFunction = (req, res, next) => {
// Middleware logic
next();
};
app.get('/users', middlewareFunction, (req, res) => {
// Handle GET request for /users
});
Router Object:
 Express Router objects can be used to create modular and mountable route handlers.
const express = require('express');
const router = express.Router();
router.get('/users', (req, res) => {
// Handle GET request for /users
});
module.exports = router;
In your main application file:
const userRoutes = require('./userRoutes');
app.use('/api', userRoutes);
Route Middleware:
Route-Specific Middleware:
 Middleware can be applied to specific routes using the use method.
const authenticationMiddleware = (req, res, next) => {
// Authentication logic
next();
};
app.use('/admin', authenticationMiddleware);
app.get('/admin/dashboard', (req, res) => {
// Handle GET request for /admin/dashboard
});
Express Built-in Middleware:
 Express provides built-in middleware for parsing request bodies, serving static files,
and more.
const express = require('express');
const app = express();
app.use(express.json()); // Parse JSON in request body
app.use(express.static('public')); // Serve static files from the 'public' directory
Session Management:
 In Node.js with Express.js, cookies can be managed using the cookie-parser
middleware.
Install cookie-parser:
 Make sure you have express and cookie-parser installed. If not, you can install them
using npm:
npm install express cookie-parser
Configure cookie-parser in your Express app:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// Use cookie-parser middleware
app.use(cookieParser());
 Adding cookie-parser middleware to your application allows you to easily work with
cookies in your routes.
Setting Cookies:
 You can set cookies using the res.cookie() method. Here's an example:
app.get('/setCookie', (req, res) => {
res.cookie('username', 'exampleUser', { maxAge: 900000, httpOnly: true });
res.send('Cookie set!');
});
 In this example, a cookie named 'username' with the value 'exampleUser' is set. The
maxAge option is set to 900,000 milliseconds (15 minutes), and httpOnly is set to true
for added security.
Reading Cookies:
 You can access cookies through req.cookies. For example:
app.get('/getCookie', (req, res) => {
const username = req.cookies.username || 'No cookie set';
res.send(`Username: ${username}`);
});
 In this example, the value of the 'username' cookie is retrieved from req.cookies.
Clearing Cookies:
 To clear a cookie, you can use the res.clearCookie() method:
app.get('/clearCookie', (req, res) => {
res.clearCookie('username');
res.send('Cookie cleared!');
});
 This example clears the 'username' cookie.
Using Session:
Install express-session:
 Make sure you have express and express-session installed. If not, you can install them
using npm:
npm install express express-session
Configure express-session:
 Set up the express-session middleware in your Express application. This usually
involves requiring it and adding it to the middleware stack. Here's a minimal example:
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true
}));
secret: A string used to sign the session ID cookie. It should be a random, long, and secure
string.
resave: Forces the session to be saved back to the session store, even if it hasn't been
modified.
saveUninitialized: Forces a session that is "uninitialized" to be saved to the store. A session is
uninitialized when it is new but not modified.
Using Sessions in Routes:
 Once the session middleware is set up, you can use the req.session object to store and
retrieve session data. For example:
app.get('/setSession', (req, res) => {
req.session.username = 'exampleUser';
res.send('Session set!');
});
app.get('/getSession', (req, res) => {
const username = req.session.username || 'No session data';
res.send(`Username: ${username}`);
});
1. Count the number of lines and words using nodejs.
fs module:
 Node.js includes fs module to access physical file system.
 The fs module is responsible for all the asynchronous or synchronous file I/O
operations.
Method Description
fs.readFile(fileName [,options],
callback)
Reads existing file.
fs.writeFile(filename, data[,
options], callback)
Writes to the file. If file exists then overwrite the
content otherwise creates new file.
fs.open(path, flags [,mode],
callback)
Opens file for reading or writing.
fs.appendFile(file, data[,
options], callback)
Appends new content to the existing file.
fs.rename(oldPath, newPath,
callback)
Renames an existing file.
fs.unlink(path, callback); Delete a file.
fs.rmdir(path, callback) Renames an existing directory.
fs.mkdir(path[, mode], callback) Creates a new directory.
fs.readdir(path, callback) Reads the content of the specified directory.
<< Refer your Notes for coding >>
2. Custom Event with Timeout using nodejs.
events module:
 Node.js allows us to create and handle custom events easily by using events
module.
 Event module includes EventEmitter class which can be used to raise and handle
custom events.
EventEmitter Methods Description
emitter.addListener(event, listener) Adds a listener to the end of the listeners array
for the specified event. No checks are made to
see if the listener has already been added.
emitter.on(event, listener) Adds a listener to the end of the listeners array
for the specified event. No checks are made to
see if the listener has already been added. It can
also be called as an alias of
emitter.addListener()
emitter.once(event, listener) Adds a one time listener for the event. This
listener is invoked only the next time the event
is fired, after which it is removed.
emitter.removeListener(event, listener) Removes a listener from the listener array for
the specified event. Caution: changes array
indices in the listener array behind the listener.
emitter.removeAllListeners([event]) Removes all listeners, or those of the specified
event.
emitter.emit(event[, arg1][, arg2][, ...]) Raise the specified events with the supplied
arguments.
const event = require('events'); // importing events module
const e = new event(); // Instantiating the object
// Function to generate the Fibonacci numbers using recurion
function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Function to display the Fibonacci numbers with time out
Function fiboDisplay(){
for (let i = 0; i < 10; i++) {
setTimeout(function() {
const fibNumber = fibonacci(i);
console.log(`Fibonacci(${i}) = ${fibNumber}`);
}, i * 2000); // Delay 2 seconds for each number (i * 2000
milliseconds)
}
}
// Binding the event with event listener
e.on("fibo", fiboDisplay)
// Triggering the event
e.emit("fibo")
// Remove the listener
setTimeout(function(){
console.log("Operation cancelled");
e.removeAllListeners("fibo");
}, 10000)
3. HTTP Server
http module:
 Node.js has a built-in module called HTTP, which allows Node.js to transfer data
over the Hyper Text Transfer Protocol (HTTP).
 The HTTP module can create an HTTP server using createServer() that listens to
server ports and gives a response back to the client.
 If the response from the HTTP server is supposed to be displayed as HTML,
include an HTTP header with the correct content type:
Server.js
var httpObj = require('http');
function initM(req, res){
// Set the response header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send a response to the client
res.end('Hello, Welcome to NodeJSn');
}
// Create an HTTP server
var server = httpObj.createServer(initM);
// Listen on port 3000
const port = 3000;
server.listen(port, function() {
console.log(`Server is running on http://localhost:${port}`);
});
Client.js
var http = require('http');
// Options for the HTTP request
var options = {
hostname: 'localhost',
port: 3000,
path: '/',
method: 'GET',
};
// Make the HTTP request
var req = http.request(options, function(res){
let data = '';
// Receive data from the response
res.on('data', function(chunk) {
data += chunk;
});
// Handle the end of the response
res.on('end', function() {
console.log(`Response from server: ${data}`);
});
});
// Handle errors
req.on('error', function(error){
console.error(`Request error: ${error.message}`);
});
// Send the request
req.end();
4. URL
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.hostname); //returns 'localhost'
console.log(q.port); //returns '8080'
console.log(q.path); //returns 'default.htm?year=2017&month=february'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'
var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'
console.log(qdata);
5. TCP Chat
socket.io module:
 Socket.IO is a library that enables low-latency, bidirectional and event-based
communication between a client and a server.
Server.js
const io = require('socket.io')();
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const port = 3000;
io.on('connection', function(socket) {
console.log('Client connected');
socket.on('disconnect', function(){
console.log('Client disconnected');
});
socket.on('chat message', function(msg){
console.log(`Received: ${msg}`);
rl.question('Enter your response: ', function(response){
socket.emit('chat message', response);
});
});
});
io.listen(port);
console.log(`Server is listening on port ${port}`);
rl.question('Server is ready. Press Enter to start chatting:n', function(){
rl.on('line', function(msg){
io.sockets.emit('chat message', `[Server]: ${msg}`);
rl.prompt();
});
});
Client.js
const io = require('socket.io-client');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const serverUrl = 'http://localhost:3000';
const socket = io(serverUrl);
socket.on('connect', function(){
console.log('Connected to the server');
startChat();
});
socket.on('chat message', function(msg){
console.log(`Received: ${msg}`);
});
socket.on('disconnect', function(){
console.log('Disconnected from the server');
});
function startChat() {
rl.question('Enter your message (or type "exit" to quit): ', function(msg){
if (msg.toLowerCase() === 'exit') {
rl.close();
socket.disconnect();
} else {
socket.emit('chat message', msg);
startChat(); // Continuously prompt for messages
}
});
}
Ad

More Related Content

What's hot (20)

Presentation on Hostel Management System
Presentation on Hostel Management SystemPresentation on Hostel Management System
Presentation on Hostel Management System
RohanRajMudvari
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
vikram singh
 
Android Location and Maps
Android Location and MapsAndroid Location and Maps
Android Location and Maps
Jussi Pohjolainen
 
javascript-basics.ppt
javascript-basics.pptjavascript-basics.ppt
javascript-basics.ppt
ahmadfaisal744721
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
Ravi Bhadauria
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
Session Tracking in servlets
Session Tracking in servletsSession Tracking in servlets
Session Tracking in servlets
chauhankapil
 
Air Line Management System | DBMS project
Air Line Management System | DBMS projectAir Line Management System | DBMS project
Air Line Management System | DBMS project
AniketHandore
 
Android Intent.pptx
Android Intent.pptxAndroid Intent.pptx
Android Intent.pptx
vishal choudhary
 
Final year project proposal
Final year project proposalFinal year project proposal
Final year project proposal
qadeer khan
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
MariaDB 제품 소개
MariaDB 제품 소개MariaDB 제품 소개
MariaDB 제품 소개
NeoClova
 
Web technology lab manual
Web technology lab manualWeb technology lab manual
Web technology lab manual
neela madheswari
 
Case study: Open Source Automation Framework using Selenium WebDriver
Case study: Open Source Automation Framework using Selenium WebDriverCase study: Open Source Automation Framework using Selenium WebDriver
Case study: Open Source Automation Framework using Selenium WebDriver
RTTS
 
Android contentprovider
Android contentproviderAndroid contentprovider
Android contentprovider
Krazy Koder
 
Online Medicine Store
Online Medicine StoreOnline Medicine Store
Online Medicine Store
Rohit Mondal
 
Secure Session Management
Secure Session ManagementSecure Session Management
Secure Session Management
GuidePoint Security, LLC
 
Vinay Gupta - Software QA Lead - Around 9 Years experience
Vinay Gupta - Software QA Lead - Around 9 Years experienceVinay Gupta - Software QA Lead - Around 9 Years experience
Vinay Gupta - Software QA Lead - Around 9 Years experience
Vinay Kumar Gupta
 
Web Technology UPTU UNIT 1
Web Technology UPTU UNIT 1 Web Technology UPTU UNIT 1
Web Technology UPTU UNIT 1
Abhishek Kesharwani
 
Medical Store Management System Software Engineering Project
Medical Store Management System Software Engineering ProjectMedical Store Management System Software Engineering Project
Medical Store Management System Software Engineering Project
hani2253
 
Presentation on Hostel Management System
Presentation on Hostel Management SystemPresentation on Hostel Management System
Presentation on Hostel Management System
RohanRajMudvari
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
vikram singh
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
Ravi Bhadauria
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
Session Tracking in servlets
Session Tracking in servletsSession Tracking in servlets
Session Tracking in servlets
chauhankapil
 
Air Line Management System | DBMS project
Air Line Management System | DBMS projectAir Line Management System | DBMS project
Air Line Management System | DBMS project
AniketHandore
 
Final year project proposal
Final year project proposalFinal year project proposal
Final year project proposal
qadeer khan
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
MariaDB 제품 소개
MariaDB 제품 소개MariaDB 제품 소개
MariaDB 제품 소개
NeoClova
 
Case study: Open Source Automation Framework using Selenium WebDriver
Case study: Open Source Automation Framework using Selenium WebDriverCase study: Open Source Automation Framework using Selenium WebDriver
Case study: Open Source Automation Framework using Selenium WebDriver
RTTS
 
Android contentprovider
Android contentproviderAndroid contentprovider
Android contentprovider
Krazy Koder
 
Online Medicine Store
Online Medicine StoreOnline Medicine Store
Online Medicine Store
Rohit Mondal
 
Vinay Gupta - Software QA Lead - Around 9 Years experience
Vinay Gupta - Software QA Lead - Around 9 Years experienceVinay Gupta - Software QA Lead - Around 9 Years experience
Vinay Gupta - Software QA Lead - Around 9 Years experience
Vinay Kumar Gupta
 
Medical Store Management System Software Engineering Project
Medical Store Management System Software Engineering ProjectMedical Store Management System Software Engineering Project
Medical Store Management System Software Engineering Project
hani2253
 

Similar to NodeJS and ExpressJS.pdf (20)

Express JS
Express JSExpress JS
Express JS
Alok Guha
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.js
FDConf
 
express of full stack web development notes
express of full stack web development notesexpress of full stack web development notes
express of full stack web development notes
JeneferAlan1
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
Aaron Stannard
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
Jeetendra singh
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
nbuddharaju
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
Express node js
Express node jsExpress node js
Express node js
Yashprit Singh
 
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
Gianluca Carucci
 
SenchaTouch 2 and Sencha.io
SenchaTouch 2 and Sencha.ioSenchaTouch 2 and Sencha.io
SenchaTouch 2 and Sencha.io
Nils Dehl
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
Anil Allewar
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
How to use Cypress Intercept to Stub API Responses.pdf
How to use Cypress Intercept to Stub API Responses.pdfHow to use Cypress Intercept to Stub API Responses.pdf
How to use Cypress Intercept to Stub API Responses.pdf
Steve Wortham
 
nodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java scriptnodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.js
FDConf
 
express of full stack web development notes
express of full stack web development notesexpress of full stack web development notes
express of full stack web development notes
JeneferAlan1
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
Aaron Stannard
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
Jeetendra singh
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
nbuddharaju
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
Gianluca Carucci
 
SenchaTouch 2 and Sencha.io
SenchaTouch 2 and Sencha.ioSenchaTouch 2 and Sencha.io
SenchaTouch 2 and Sencha.io
Nils Dehl
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
Anil Allewar
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
How to use Cypress Intercept to Stub API Responses.pdf
How to use Cypress Intercept to Stub API Responses.pdfHow to use Cypress Intercept to Stub API Responses.pdf
How to use Cypress Intercept to Stub API Responses.pdf
Steve Wortham
 
nodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java scriptnodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
Ad

More from ArthyR3 (20)

Unit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfUnit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdf
ArthyR3
 
VIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfVIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdf
ArthyR3
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
ArthyR3
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
ArthyR3
 
REACTJS.pdf
REACTJS.pdfREACTJS.pdf
REACTJS.pdf
ArthyR3
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
ArthyR3
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
ArthyR3
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
ArthyR3
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit v
ArthyR3
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit v
ArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
ArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
ArthyR3
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit i
ArthyR3
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
ArthyR3
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)
ArthyR3
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography Workbook
ArthyR3
 
Cns
CnsCns
Cns
ArthyR3
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network security
ArthyR3
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bank
ArthyR3
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question key
ArthyR3
 
Unit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfUnit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdf
ArthyR3
 
VIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfVIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdf
ArthyR3
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
ArthyR3
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
ArthyR3
 
REACTJS.pdf
REACTJS.pdfREACTJS.pdf
REACTJS.pdf
ArthyR3
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
ArthyR3
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
ArthyR3
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
ArthyR3
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit v
ArthyR3
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit v
ArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
ArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
ArthyR3
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit i
ArthyR3
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
ArthyR3
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)
ArthyR3
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography Workbook
ArthyR3
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network security
ArthyR3
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bank
ArthyR3
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question key
ArthyR3
 
Ad

Recently uploaded (20)

Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 

NodeJS and ExpressJS.pdf

  • 1. Department of Information Technology 2023 – 2024 (ODD SEMESTER) Year : III IT Course Code : IT2304 Faculty Name : Dr. R. Arthy, AP/IT Course Name : Full Stack Web Development Course code (as per NBA) : 21ITC304 Regulation : R2021 UNIT IV Middleware:  Middleware functions are the functions that access to the request and response object (req, res) in request-response cycle.  A middleware function can perform the following tasks: o It can execute any code. o It can make changes to the request and the response objects. o It can end the request-response cycle. o It can call the next middleware function in the stack. Express.js Middleware Following is a list of possibly used middleware in Express.js app:  Application-level middleware  Router-level middleware  Error-handling middleware  Built-in middleware  Third-party middleware Request Processing:  Middleware functions are executed in the order they are defined.  They process the incoming request and can modify the request object, add properties to it, or perform validations. Response Handling:
  • 2.  Middleware functions can also modify the response object (res).  They can set headers, send a response, or manipulate the response data before it is sent back to the client. Chaining Middleware:  Express allows the chaining of multiple middleware functions.  Each middleware function in the chain has access to the request and response objects. The next function is used to pass control to the next middleware in the stack. Example: app.use((req, res, next) => { next(); // Pass control to the next middleware }); Error Handling:  Middleware functions can handle errors.  If an error occurs, the middleware with four parameters (err, req, res, next) is triggered. This allows for centralized error handling. Example: app.use((err, req, res, next) => { res.status(500).send('Internal Server Error'); }); Authentication and Authorization:  Middleware is commonly used for authentication and authorization purposes.  For example, a middleware function can check if a user is authenticated before allowing access to certain routes. Example: const authenticate = (req, res, next) => { if (userIsAuthenticated) { next(); } else { res.status(401).send('Unauthorized'); }
  • 3. }; app.get('/secured', authenticate, (req, res) => { res.send('Secured Route'); }); Static File Serving:  Express provides built-in middleware functions for serving static files.  This is commonly used to serve CSS, JavaScript, and image files. Example: app.use(express.static('public')); Logging:  Middleware functions are often used for logging requests, providing valuable insights into the flow of traffic through the application. Example: app.use((req, res, next) => { console.log(`[${new Date()}] ${req.method} ${req.url}`); next(); }); Third-Party Middleware:  Express allows the use of third-party middleware for additional functionality.  Examples include body parsers for handling request bodies, compression middleware, and session management middleware. Example const bodyParser = require('body-parser'); app.use(bodyParser.json()); Routing:  In Express.js, routing refers to the process of defining how an application responds to a client request to a particular endpoint (URL) and HTTP method.
  • 4.  Express provides a simple and flexible way to handle routing, allowing you to define routes for different HTTP methods and URL patterns. Basic Routing:  A basic example of a route that responds to a GET request at the root URL. const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); Route Parameters:  Routes can include parameters, which are specified with a colon : in the route pattern. app.get('/users/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); }); Handling Different HTTP Methods: GET Request:  Responds to a GET request. app.get('/users', (req, res) => { // Handle GET request for /users }); POST Request:  Responds to a POST request. app.post('/users', (req, res) => { // Handle POST request for /users }); PUT Request:  Responds to a PUT request.
  • 5. app.put('/users/:id', (req, res) => { // Handle PUT request for /users/:id }); DELETE Request:  Responds to a DELETE request. app.delete('/users/:id', (req, res) => { // Handle DELETE request for /users/:id }); Middleware in Routing: Middleware Function:  Middleware functions can be used in routing to perform tasks before sending a response. const middlewareFunction = (req, res, next) => { // Middleware logic next(); }; app.get('/users', middlewareFunction, (req, res) => { // Handle GET request for /users }); Router Object:  Express Router objects can be used to create modular and mountable route handlers. const express = require('express'); const router = express.Router(); router.get('/users', (req, res) => { // Handle GET request for /users }); module.exports = router; In your main application file: const userRoutes = require('./userRoutes');
  • 6. app.use('/api', userRoutes); Route Middleware: Route-Specific Middleware:  Middleware can be applied to specific routes using the use method. const authenticationMiddleware = (req, res, next) => { // Authentication logic next(); }; app.use('/admin', authenticationMiddleware); app.get('/admin/dashboard', (req, res) => { // Handle GET request for /admin/dashboard }); Express Built-in Middleware:  Express provides built-in middleware for parsing request bodies, serving static files, and more. const express = require('express'); const app = express(); app.use(express.json()); // Parse JSON in request body app.use(express.static('public')); // Serve static files from the 'public' directory Session Management:  In Node.js with Express.js, cookies can be managed using the cookie-parser middleware. Install cookie-parser:  Make sure you have express and cookie-parser installed. If not, you can install them using npm: npm install express cookie-parser Configure cookie-parser in your Express app: const express = require('express');
  • 7. const cookieParser = require('cookie-parser'); const app = express(); // Use cookie-parser middleware app.use(cookieParser());  Adding cookie-parser middleware to your application allows you to easily work with cookies in your routes. Setting Cookies:  You can set cookies using the res.cookie() method. Here's an example: app.get('/setCookie', (req, res) => { res.cookie('username', 'exampleUser', { maxAge: 900000, httpOnly: true }); res.send('Cookie set!'); });  In this example, a cookie named 'username' with the value 'exampleUser' is set. The maxAge option is set to 900,000 milliseconds (15 minutes), and httpOnly is set to true for added security. Reading Cookies:  You can access cookies through req.cookies. For example: app.get('/getCookie', (req, res) => { const username = req.cookies.username || 'No cookie set'; res.send(`Username: ${username}`); });  In this example, the value of the 'username' cookie is retrieved from req.cookies. Clearing Cookies:  To clear a cookie, you can use the res.clearCookie() method: app.get('/clearCookie', (req, res) => { res.clearCookie('username'); res.send('Cookie cleared!'); });  This example clears the 'username' cookie. Using Session:
  • 8. Install express-session:  Make sure you have express and express-session installed. If not, you can install them using npm: npm install express express-session Configure express-session:  Set up the express-session middleware in your Express application. This usually involves requiring it and adding it to the middleware stack. Here's a minimal example: const express = require('express'); const session = require('express-session'); const app = express(); app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true })); secret: A string used to sign the session ID cookie. It should be a random, long, and secure string. resave: Forces the session to be saved back to the session store, even if it hasn't been modified. saveUninitialized: Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified. Using Sessions in Routes:  Once the session middleware is set up, you can use the req.session object to store and retrieve session data. For example: app.get('/setSession', (req, res) => { req.session.username = 'exampleUser'; res.send('Session set!'); }); app.get('/getSession', (req, res) => { const username = req.session.username || 'No session data';
  • 9. res.send(`Username: ${username}`); }); 1. Count the number of lines and words using nodejs. fs module:  Node.js includes fs module to access physical file system.  The fs module is responsible for all the asynchronous or synchronous file I/O operations. Method Description fs.readFile(fileName [,options], callback) Reads existing file. fs.writeFile(filename, data[, options], callback) Writes to the file. If file exists then overwrite the content otherwise creates new file. fs.open(path, flags [,mode], callback) Opens file for reading or writing. fs.appendFile(file, data[, options], callback) Appends new content to the existing file. fs.rename(oldPath, newPath, callback) Renames an existing file. fs.unlink(path, callback); Delete a file. fs.rmdir(path, callback) Renames an existing directory. fs.mkdir(path[, mode], callback) Creates a new directory. fs.readdir(path, callback) Reads the content of the specified directory. << Refer your Notes for coding >> 2. Custom Event with Timeout using nodejs. events module:  Node.js allows us to create and handle custom events easily by using events module.  Event module includes EventEmitter class which can be used to raise and handle custom events. EventEmitter Methods Description emitter.addListener(event, listener) Adds a listener to the end of the listeners array
  • 10. for the specified event. No checks are made to see if the listener has already been added. emitter.on(event, listener) Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. It can also be called as an alias of emitter.addListener() emitter.once(event, listener) Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed. emitter.removeListener(event, listener) Removes a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener. emitter.removeAllListeners([event]) Removes all listeners, or those of the specified event. emitter.emit(event[, arg1][, arg2][, ...]) Raise the specified events with the supplied arguments. const event = require('events'); // importing events module const e = new event(); // Instantiating the object // Function to generate the Fibonacci numbers using recurion function fibonacci(n) { if (n <= 1) { return n; } return fibonacci(n - 1) + fibonacci(n - 2); } // Function to display the Fibonacci numbers with time out Function fiboDisplay(){ for (let i = 0; i < 10; i++) { setTimeout(function() { const fibNumber = fibonacci(i);
  • 11. console.log(`Fibonacci(${i}) = ${fibNumber}`); }, i * 2000); // Delay 2 seconds for each number (i * 2000 milliseconds) } } // Binding the event with event listener e.on("fibo", fiboDisplay) // Triggering the event e.emit("fibo") // Remove the listener setTimeout(function(){ console.log("Operation cancelled"); e.removeAllListeners("fibo"); }, 10000) 3. HTTP Server http module:  Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).  The HTTP module can create an HTTP server using createServer() that listens to server ports and gives a response back to the client.
  • 12.  If the response from the HTTP server is supposed to be displayed as HTML, include an HTTP header with the correct content type: Server.js var httpObj = require('http'); function initM(req, res){ // Set the response header res.writeHead(200, { 'Content-Type': 'text/plain' }); // Send a response to the client res.end('Hello, Welcome to NodeJSn'); } // Create an HTTP server var server = httpObj.createServer(initM); // Listen on port 3000 const port = 3000; server.listen(port, function() { console.log(`Server is running on http://localhost:${port}`); }); Client.js var http = require('http'); // Options for the HTTP request var options = {
  • 13. hostname: 'localhost', port: 3000, path: '/', method: 'GET', }; // Make the HTTP request var req = http.request(options, function(res){ let data = ''; // Receive data from the response res.on('data', function(chunk) { data += chunk; }); // Handle the end of the response res.on('end', function() { console.log(`Response from server: ${data}`); }); }); // Handle errors req.on('error', function(error){ console.error(`Request error: ${error.message}`); }); // Send the request
  • 14. req.end(); 4. URL var url = require('url'); var adr = 'http://localhost:8080/default.htm?year=2017&month=february'; var q = url.parse(adr, true); console.log(q.host); //returns 'localhost:8080' console.log(q.hostname); //returns 'localhost' console.log(q.port); //returns '8080' console.log(q.path); //returns 'default.htm?year=2017&month=february' console.log(q.pathname); //returns '/default.htm' console.log(q.search); //returns '?year=2017&month=february' var qdata = q.query; //returns an object: { year: 2017, month: 'february' } console.log(qdata.month); //returns 'february' console.log(qdata); 5. TCP Chat socket.io module:  Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server. Server.js const io = require('socket.io')();
  • 15. const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const port = 3000; io.on('connection', function(socket) { console.log('Client connected'); socket.on('disconnect', function(){ console.log('Client disconnected'); }); socket.on('chat message', function(msg){ console.log(`Received: ${msg}`); rl.question('Enter your response: ', function(response){ socket.emit('chat message', response); }); }); }); io.listen(port); console.log(`Server is listening on port ${port}`);
  • 16. rl.question('Server is ready. Press Enter to start chatting:n', function(){ rl.on('line', function(msg){ io.sockets.emit('chat message', `[Server]: ${msg}`); rl.prompt(); }); }); Client.js const io = require('socket.io-client'); const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const serverUrl = 'http://localhost:3000'; const socket = io(serverUrl); socket.on('connect', function(){ console.log('Connected to the server'); startChat(); }); socket.on('chat message', function(msg){
  • 17. console.log(`Received: ${msg}`); }); socket.on('disconnect', function(){ console.log('Disconnected from the server'); }); function startChat() { rl.question('Enter your message (or type "exit" to quit): ', function(msg){ if (msg.toLowerCase() === 'exit') { rl.close(); socket.disconnect(); } else { socket.emit('chat message', msg); startChat(); // Continuously prompt for messages } }); }