0% found this document useful (0 votes)
20 views89 pages

Node.js Basics and Application Development

Uploaded by

r21921924
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views89 pages

Node.js Basics and Application Development

Uploaded by

r21921924
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

UBCA301L – Full Stack


Application Development
[Link].K
PROFESSOR GRADE 1
SCORE

[Link].K 9/16/2025
2 MODULE 6 : NodeJS
Getting Started with [Link]
Using Events
Listeners
Timers and Callbacks in [Link]
Handling data I/O in [Link]
Accessing the File System from [Link]
Implementing HTTP Services in [Link]

[Link].K 9/16/2025
3 Traditional Web Server Model
 In the traditional web server model, each request is handled by a
dedicated thread from the thread pool.
 If no thread is available in the thread pool at any point of time then the
request waits till the next available thread.
 Dedicated thread executes a particular request and does not return to
thread pool until it completes the execution and returns a response.
4 [Link] Process model
 [Link] processes user requests differently when compared to a traditional
web server model.
 [Link] runs in a single process and the application code runs in a single
thread and thereby needs less resources than other platforms.
 All the user requests to your web application will be handled by a single
thread and all the I/O work or long running job is performed asynchronously
for a particular request.
 So, this single thread doesn't have to wait for the request to complete and is
free to handle the next request.
 When asynchronous I/O work completes then it processes the request
further and sends the response.
 An event loop is constantly watching for the events to be raised for an
asynchronous job and executing callback function when the job
completes.
5 [Link] Process model
 [Link] uses libev for the event loop which in turn uses internal C++ thread
pool to provide asynchronous I/O.
6 Example - Real time scenario
7 Differentiate between Traditional web
server and [Link] Server
 A common task for a web server can be to open a file on the server and return the content to the
client
 Traditional web server
 Sends the task to the computer's file system,
 Waits while the file system opens and reads the file
 Return the content to the client
 Ready to handle the next request.
 [Link] Server
 Sends the task to the computer file system.
 Ready to the handle the next request
 When the file system has opened and read the file, the server returns the content to the client.
 [Link] eliminates the waiting and simply continues with the next request.
 [Link] runs single threaded, non blocking, asynchronously programming which is very memory
efficient.
8 Node JS - Introduction
 Basically, [Link] is a run-time environment based on
JavaScript, that can be used as frontend and backend.
 [Link] platform, then it was created by the developer
Ryan Dahl in the year 2009.
 Considering the popularity of the [Link] development
on SimilarTech website, around 175k websites are
developed using the [Link].
 The highest number of [Link] websites are developed
in the United States followed by India and UK.
9 Node JS – Use cases
 Nodejs has gained immense popularity among developers for the fantastic
development of web applications.
 [Link] development is special for backend developers.
 Most of the Node js Development Company use the nodejs for
development is that it is an open-source, and community-loved engine.
 As we all know, Nodejs is a runtime built on the popular Chrome V8
JavaScript engine.
 Nodejs comes from the JavaScript family that allows the developers to use
the same programming on both the front-end and back-end.
 [Link] development is not only limited to web applications but also
includes the development in the microcontrollers, REST APIs, static file
servers, chatbots, queued I/O inputs, etc.
10 Node JS – Use cases
11 Top World famous companies using
[Link]
12 Important features of [Link]
 [Link] can generate dynamic page content.
 [Link] can create, open , read, write, delete and close
files on the server.
 [Link] can collect form data.
 [Link] can add, delete, modify data in your database.
13 Install [Link] on Windows
 [Link] development environment can be setup in Windows, Mac, Linux
and Solaris.
 Visit [Link] official web site [Link] It will automatically detect
OS and display download link as per your Operating System.
 Download [Link] installer for windows.
14 Install [Link] on Windows

Click the button


15 Install [Link] on Windows

Download msi file


16 Install [Link] on Windows
 After you download the MSI, double-click on it to start the installation as shown
below.

 Click Next to read and accept the License Agreement and then click Install. It
will install [Link] quickly on your computer. Finally, click finish to complete the
installation.
17 Verify Installation
 Once you install [Link] on your computer, you can verify it by opening the
command prompt and typing node -v.
 If [Link] is installed successfully then it will display the version of the
[Link] installed on your machine, as shown below
18 [Link] Console/REPL
 [Link] comes with virtual environment called REPL (aka Node shell). REPL
stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple
[Link]/JavaScript code.
 To launch the REPL (Node shell), open command prompt (in Windows) or
terminal (in Mac or UNIX/Linux) and type node as shown below. It will
change the prompt to > in Windows and MAC.
19 [Link] Console/REPL
 . You can also define variables and perform some operation on them

 If you need to write multi line JavaScript expression or function then just
press Enter whenever you want to write something in the next line as a
continuation of your code.
20 [Link] Console/REPL
 You can execute an external JavaScript file by executing the node
fileName command.
 [Link] contains the following statement
 [Link]("Welcome to Node JS beginners");
21 [Link] basics
 [Link] supports JavaScript. So, JavaScript syntax on [Link] is similar to
the browser's JavaScript syntax.
 JavaScript in [Link] supports loose typing like the browser's JavaScript.
Use var keyword to declare a variable of any type.
 Object literal syntax is same as browser's JavaScript.
 var obj = { authorName: 'Ryan Dahl', language: '[Link]' }
 A function can have attributes and properties also. It can be treated like a
class in JavaScript.
 function Display(x) { [Link](x); } Display(100);
 [Link] includes an additional data type called Buffer (not available in
browser's JavaScript). Buffer is mainly used to store binary data, while
reading from a file or receiving packets over the network.
22 [Link] basics
 Each [Link] script runs in a process. It includes process object to get all
the information about the current process of [Link] application.
 The following example shows how to get process information in REPL
using process object.
23 [Link] Module
 Module in [Link] is a simple or complex functionality
organized in single or multiple JavaScript files which can
be reused throughout the [Link] application.
 [Link] includes three types of modules:
Core Modules
Local Modules
Third Party Modules
24 Core Modules
 Built-in modules of node. js that are part of nodejs and come with the Node. js
installation process are known as core modules.
 However, you need to import the core module first in order to use it in your
application.
 To load/include this module in our program, we use the require function.
Core Module Description
http http module includes classes, methods and events to create
[Link] http server.
url url module includes methods for URL resolution and parsing.
querystring querystring module includes methods to deal with query string.
path path module includes methods to deal with file paths.
fs fs module includes classes, methods, and events to work with file
I/O.
util util module includes utility functions useful for programmers.
25 Loading core modules
 In order to use [Link] core or NPM modules, you first need to import it
using require() function as shown below.
 var module = require('module_name');
 As per above syntax, specify the module name in the require() function. The
require() function will return an object, function, property or any other
JavaScript type, depending on what the specified module returns.
 var http = require('http');
 var server = [Link](function(req, res)
 { //write code here });
 [Link](5000);
26 [Link] Local Module
 We can define modules locally as Local Module. It consists different
functions declared inside a JavaScript object and we reuse them
according to the requirement.
 We can also package it and distribute it using NPM.
 Local module must be written in a separate JavaScript file. In the separate
file, we can declare a JavaScript object with different properties and
methods.
27 Local Module example
const welcome = {
sayHello : function() {
[Link]("Hello Welcome to everyone");
},
currTime : new Date().toLocaleDateString(),
companyName : "Vellore Institute of Technology"
}
[Link] = welcome

Save the file as [Link]

var local = require("./[Link]");


[Link]();
[Link]([Link]);
[Link]([Link]);

Save the file as [Link]


28 Export Module in [Link]
 Node JS has provided almost all required modules (We can check this updates on its
official website: [Link] It is also known as Node JS Module
Repository).
 But in some real time applications, we may have some application functionality,
which is used many places in that application but not available at Node JS Module
Repository.
 In this scenario, to get Reusability benefit, we need to create our own new Node JS
module.
 Just creating new Module is not enough to use it in other modules of the system. We
need to export this module so that other modules will reuse it
29 Export Module in [Link] - example
var PI = 3.1416
[Link] = PI;

function add(a,b){ return a + b; }


function sub(a,b){ return a - b; }
[Link] = add
[Link] = sub

[Link] =
{ var PI = 3.1416;
function add(a,b){ return a + b; }
function sub(a,b){ return a - b; }
function mul(a,b){ return a * b; }
function div(a,b){ return a / b; } }
30 [Link] first example
 [Link] console based example
 [Link]("Happy to learn [Link]");

 [Link] web-based Example


 A [Link] web application contains the following three parts:
 Import required modules: The "require" directive is used to load a [Link]
module.
 Create server: You have to establish a server which will listen to client's request
similar to Apache HTTP Server.
 Read request and return response: Server created in the second step will read
HTTP request made by client which can be a browser or console and return the
response.
31 [Link] web-based Example
 Import required module:
 The first step is to use require directive to load http module and store
returned HTTP instance into http variable
 var http = require("http");
 Create server: In the second step, you have to use created http instance
and call [Link]() method to create server instance and then
bind it at port 8080 using listen method associated with server instance.
 Pass it a function with request and response parameters and write the
sample implementation to return ―Happy to learn [Link]".
 [Link](function (request, response) {
 [Link](200, {'Content-Type': 'text/plain'});
 [Link](‘Happy to learn node js\n');
 }).listen(8080);
32 [Link] web-based Example
33 Export module demo
 [Link] = function () {
return Date();
};
 Save the above file as [Link]
var http = require('http');
var dt = require('./dateandtime');
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]("The date and time are currently: " + [Link]());
[Link]();
}).listen(8080);
Save this file as [Link]
34 Export module demo output
35 [Link] url module
 The URL module splits up a web address into readable parts.
 var url = require('url');
 Parse an address with the [Link]() method, and it will return a URL object
with each part of the address as properties:
36 [Link] url demo
var url = require('url');
var adr = '[Link]
var q = [Link](adr, true);

[Link]([Link]); //returns 'localhost:8080'


[Link]([Link]); //returns '/[Link]'
[Link]([Link]); //returns '?year=2017&month=february'

var qdata = [Link]; //returns an object: { year: 2017, month: 'february' }


[Link]([Link]); //returns 'february'
37 [Link] file system module
 [Link] includes fs module to access physical file system. The fs module is
responsible for all the asynchronous or synchronous file I/O operations.
 To include the File System module, use the require() method:
 var fs = require('fs');
 Common use for the File System module:
Read files
Create files
Update files
Delete files
Rename files
38 readFile method
 The [Link]() method is used to read files on your system.
 <html>
<body>
<h1>How to use fs module in Node JS</h1>
<p>use require method</p>
</body>
</html>
 Save this file as [Link]
 var http = require('http');
var fs = require('fs');
[Link](function (req, res) {
[Link](‘[Link]', function(err, data) {
[Link](200, {'Content-Type': 'text/html'});
[Link](data);
return [Link]();
});
}).listen(8080);
39 writeFile method
var fs = require('fs');
[Link]('[Link]', 'File manipulation is very simple in node js', function
(err) {
if (err) throw err;
[Link]('[Link] is created successfully');
});
40 writeFile method (Running web server)
var http = require('http');
var fs = require('fs');
data = "Many of the website creation used by node js";
[Link](function (req, res)
{ [Link]('[Link]', data,function(err, fdata)
{ [Link](200, {'Content-Type': 'text/plain'});
[Link]("File is created successfully");
return [Link](); }); }).listen(8080);
41 appendFile method
var fs = require('fs');
[Link]('[Link]', 'Read, write and append file operation', function
(err) {
if (err) throw err;
[Link]('New line of content stored in [Link]');
});
42 appendFile method (Web Server)
var http = require('http');
var fs = require('fs');
data = "[Link] processes user requests differently when compared to a
traditional web server model";
[Link](function (req, res)
{ [Link]('[Link]', data,function(err, fdata)
{ [Link](200, {'Content-Type': 'text/plain'});
[Link]("New content is added to the file.");
return [Link](); }); }).listen(8080);
43 Delete and rename a file
 To delete a file with the File System module, use the [Link]() method.
 The [Link]() method deletes the specified file.
var fs = require('fs');
//Delete the file [Link]:
[Link]('[Link]', function (err) {
if (err) throw err;
[Link]('File deleted!');
});
 To rename a file with the File System module, use the [Link]() method.
 The [Link]() method renames the specified file:
var fs = require('fs');
[Link]('[Link]', '[Link]', function (err) {
if (err) throw err;
[Link]('File Renamed!');
});
44 Callback
 A callback is a function called when the task finishes, and a callback
function allows other code to run in the meantime.
 Using the Callback concept, Node. js can process many requests without
waiting for any function to return the result, making Node. js highly scalable.

var fs=require("fs");
var data=[Link]('[Link]');
[Link]([Link]());
[Link]("Task is completed");

var fs=require("fs");
[Link]('[Link]', function(err,data) {
if (err) return [Link](err);
[Link]([Link]());
});
[Link]("Task is completed");
45 Event loop
 In [Link], the Call Stack is a fundamental mechanism provided by the V8
JavaScript engine that manages the execution of your program's functions.
 It operates on a Last-In, First-Out (LIFO) principle, meaning the last function
added to the stack is the first one to be removed.
 Tracking Function Execution
 Maintaining Execution Order
 Function Completion and Removal
 Synchronous Execution
 Global Context:
 The entire script you are running is initially considered a "global function"
and is pushed onto the Call Stack when your program starts.
46 Event driven application
 An event-driven application in [Link] program flow is determined
by the occurrence of events.
 This architecture allows [Link] to handle asynchronous operations
efficiently and build scalable, real-time applications.
 Core Concepts:
 Events: These are signals that indicate a particular action or state
change within the application or from external sources.
 Examples include user actions (like a button click),
 system events (like a file being read), or
 messages from other services.
47 Event driven application
 Event Emitters:
 [Link] provides the EventEmitter class (part of the events module)
which objects can inherit from. These objects can "emit" named
events, triggering any registered listeners.
 Event Listeners (or Callbacks):
 These are functions that "listen" for specific events. When an event is
emitted, the corresponding listener function is executed.
 Event Loop:
 This is the central mechanism in [Link] that continuously monitors
for events and executes their respective callback functions.
 It's a single-threaded process that manages the execution of
asynchronous operations without blocking the main thread.
48 Event driven application
 When an event occurs (e.g., a network request
completes, a file is read), it is placed in a queue.
 The Event Loop picks up events from this queue and
dispatches them to their registered listeners.
 The listener functions are executed, performing the
necessary actions in response to the event.
 Because [Link] uses a non-blocking I/O model, the
Event Loop can continue processing other events while
waiting for long-running operations (like I/O) to
complete, making the application highly responsive and
efficient.
49 Event loop- Call Stack
 The Event Loop has one simple job — to monitor the Call Stack and the
Callback Queue.
 If the Call Stack is empty, the Event Loop will take the first event from the
queue and will push it to the Call Stack, which effectively runs it.
 In an event driven application, there is generally a main loop that listens for
events and then triggers a callback function when one of those events is
detected.
50 Event handler in Node js
 In [Link], event handlers are defined using the built-in events module and
its EventEmitter class.
 This allows for an event-driven architecture where you can create, emit,
and listen for custom events.
 To define an event handler in [Link]:
1. import the events module.
 const EventEmitter = require('events');
2. Create an instance of EventEmitter.
 const myEmitter = new EventEmitter();
3. Define the event handler function: This is the function that will be executed
when the event is triggered.
51 Event handler in Node js
const myEventHandler = function (data) {
[Link]('An event occurred with data:', data);
};

You can also define it as an arrow function:

const myEventHandler = (data) => {


[Link]('An event occurred with data:', data);
};

4. Register the event handler with an event: Use the on() method to associate
the handler with a specific event name.

[Link]('myCustomEvent', myEventHandler);
52 Event handler in Node js
If you want the handler to be called only once, use once() instead of on():
[Link]('myCustomEvent', myEventHandler);

5. Emit the event: Use the emit() method to trigger the event. You can also pass
arguments to the event handler.

[Link]('myCustomEvent', 'some important data');


53 Example1 for Event handling in [Link]
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
const welcomeHandler = function (username) {
[Link](`Welcome, ${username}!`); };
// Register the event handler for the 'userJoined' event
[Link]('userJoined', welcomeHandler);
// Emit the 'userJoined' event
[Link]('userJoined', 'Alice'); // Output: Welcome, Alice!
[Link]('userJoined', 'Bob'); // Output: Welcome, Bob!
54 Example2 for Event handling in [Link]
const EventEmitter = require('events');
// Create a new instance of EventEmitter
const myEmitter = new EventEmitter();
// Define a listener function
const myListener = function(message) {
[Link](`Received message: ${message}`);
};
// Register the listener for the 'greet' event
[Link]('greet', myListener);
// Emit the 'greet' event
[Link]('greet', 'Hello from the Event Emitter!');
55 Example2 for Event handling in [Link]
// You can also add multiple listeners to the same event
[Link]('greet', () => {
[Link]('Another greeting!');});
// Emit the 'greet' event again to trigger both listeners
[Link]('greet', 'Second greeting!');
// Remove a specific listener
[Link]('greet', myListener);
// Emit the 'greet' event again; only the second listener will be called
[Link]('greet', 'Third greeting!');
// Register a listener that only fires once
[Link]('onceEvent', () => {
[Link]('This event will only fire once.');});
// Emit the 'onceEvent'
[Link]('onceEvent'); // Output: This event will only fire once.
[Link]('onceEvent'); // No output, as the listener was removed after the first emit
56 Event handler in Node js
 The EventEmitter class is imported from the built-in events module.
 An instance of EventEmitter is created as myEmitter.
 A function myListener is defined to serve as an event handler.
 The [Link]() method registers myListener to be executed whenever
the 'greet' event is emitted.
 The [Link]() method triggers the 'greet' event,
causing myListener to be invoked with the provided message.
 Multiple listeners can be registered for the same event, and emit() will call
all of them.
 The [Link]() method is used to remove a specific listener from an
event.
 The [Link]() method registers a listener that will be called only
once and then automatically removed.
57 Example3 for Event handling in [Link]
const EventEmitter = require('events');
// Create a new instance of EventEmitter
const myEmitter = new EventEmitter();
// Register an event listener for the 'greet' event
[Link]('greet', (name) => {
[Link](`Hello, ${name}!`);
});
// Register another event listener for the 'farewell' event
[Link]('farewell', () => {
[Link]('Goodbye!');
});
58 Example3 for Event handling in [Link]
// Emit the 'greet' event with an argument
[Link]('greet', 'Alice');
// Emit the 'farewell' event
[Link]('farewell');
// Register a listener that will only be called once
[Link]('firstTime', () => {
[Link]('This message will only appear once.');
});
// Emit the 'firstTime' event multiple times
[Link]('firstTime');
[Link]('firstTime'); // This emit will not trigger the listener again
59 Removing event listener
 In [Link], specifically when working with EventEmitter instances,
you can remove event listeners using the removeListener() or
 removeAllListeners() methods.
60 Example 1 for remove listener method
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
function myListener() {
[Link]('Event fired!');}
// Add the listener
[Link]('myEvent', myListener);
// Emit the event (will trigger myListener)
[Link]('myEvent');
// Remove the listener
[Link]('myEvent', myListener);
// Emit the event again (will not trigger myListener)
[Link]('myEvent');
61 Example 2 for remove listener method
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
function listener1() { [Link]('Listener 1'); }
function listener2() { [Link]('Listener 2'); }
[Link]('data', listener1);
[Link]('data', listener2);
[Link]('data'); // Both listeners will fire
[Link]('data'); // Removes all listeners for 'data' event
[Link]('data'); // No listeners will fire
62 [Link] Event emitter demo 3
const EventEmitter = require('events');
var eventEmitter = new EventEmitter();
var g1= (msg) => {
[Link]("How to use eventemitter object: " + msg);
};
var g2 = (msg) => {
[Link]("how to register the event: " + msg);
};
[Link]('myEvent', g1);
[Link]('myEvent', g1);
[Link]('myEvent', g2);
[Link]('myEvent', "Event occurred");
[Link]("Removing listener g1");
[Link]('myEvent', g1);
[Link]('myEvent', "Event occurred");
[Link]("Removing all the listeners to myevent");
[Link]('myEvent');
[Link]('myEvent', "Event occurred");
63 Event handling exercises
1. Create and Emit a Simple Event:
a. Create an instance of EventEmitter.
b. Register a listener for a custom event, e.g., ‘greetings', that logs a message
to the console.
c. Emit the 'greetings' event.
2. Modify the previous exercise to pass a name argument when emitting the
'greetings' event. Update the listener to receive and display the name.
3. Register two different listeners for the same event, e.g., 'dataReceived'.
Remove one of the listeners using [Link](). Emit the event
and observe which listener is still active.
4. Create an EventEmitter to simulate a data [Link] a 'data' event at
regular intervals (e.g., using setInterval) with simulated data. Register a listener
to process the received data.
64 NPM - Node Package Manager
 Node Package Manager (NPM) is a command line tool that installs,
updates or uninstalls [Link] packages in your application
 NPM is included with [Link] installation
 NPM performs the operation in two modes: global and local. In the global
mode, NPM performs operations which affect all the [Link] applications
on the computer whereas in the local mode, NPM performs operations for
the particular local directory which affects an application in that directory
only.
 Use the following command to install any third party module in your local
[Link] project folder.
 npm install <module name>
65 NPM - Node Package Manager
 npm install express
 All the modules installed using NPM are installed
under node_modules folder. The above command will create ExpressJS
folder under node_modules folder in the root folder of your project and
install [Link] there.
 Use --save at the end of the install command to add dependency entry into
[Link] of your application.
 npm install express –-save
 Install Package Globally
 npm install -g express
 Update Package
 npm update <module name> npm update express
66 NPM - Node Package Manager
 Uninstall Packages
 npm uninstall <package name>
 npm uninstall express
 npm –ls
 npm search express
67 Express framework
 [Link] is a web application framework for [Link]. It provides various
features that make web application development fast and easy which
otherwise takes more time using only [Link].
 [Link] is based on the [Link] middleware module
called connect which in turn uses http module. So, any middleware which is
based on connect will also work with [Link].
68 Features of express framework
 Makes [Link] web application development fast and easy.
 Easy to configure and customize.
 Allows you to define routes of your application based on HTTP methods and
URLs.
 Includes various middleware modules which you can use to perform
additional tasks on request and response.
 Easy to integrate with different template engines like Jade, Vash, EJS etc.
 Allows you to define an error handling middleware.
 Easy to serve static files and resources of your application.
 Allows you to create REST API server.
 Easy to connect with databases such as MongoDB, Redis, MyS
69 Installing express
 npm install express --save
 body-parser: This is a [Link] middleware for handling JSON, Raw, Text and
URL encoded form data.
 cookie-parser: It is used to parse Cookie header and populate [Link]
with an object keyed by the cookie names.
 multer: This is a [Link] middleware for handling multipart/form-data.
 npm install body-parser --save
 npm install cookie-parser --save
 npm install multer --save
70 [Link] App Example
 simple Express app example which starts a server and listen on a local port.
It only responds to homepage
var express = require('express');
var app = express();
[Link]('/', function (req, res) {
[Link]('<html><body><h1>Hello World</h1></body></html>');
});
var server = [Link](5000, function () {
[Link]('Node server is running..');
});
71 [Link] App Example
 Requiring Express: const express = require('express'); imports the
Express library.
 Creating an Express application instance: const app = express();
creates the main application object.
 Defining routes: [Link]('/', ...) defines how the server responds to
GET requests to specific URLs.
 Starting the server: [Link](port, ...) makes the application listen
for incoming requests on a specified port.
72 [Link] Request Object
 [Link] Request and Response objects are the parameters of the
callback function which is used in Express applications.
 The [Link] request object represents the HTTP request and has properties
for the request query string, parameters, body, HTTP headers, and so on.

[Link]('/', function (req, res) {


// --
})
73 [Link] request object properties
Properties Description

[Link] This is used to hold a reference to the instance of the express application that is
using the middleware.

[Link] It contains key-value pairs of data submitted in the request body. By default, it is
undefined, and is populated when you use body-parsing middleware such as
body-parser.

[Link] When we use cookie-parser middleware, this property is an object that contains
cookies sent by the request.

[Link] An object containing properties mapped to the named route ?parameters?. For
example, if you have the route /user/:name, then the "name" property is available
as [Link]. This object defaults to {}

[Link] An object containing a property for each query string parameter in the route.

[Link] The currently-matched route, a string.

[Link] When using cookie-parser middleware, this property contains signed cookies
sent by the request, unsigned and ready for use.
74 Example for [Link]
const express = require('express');
const app = express();
const PORT = 3000;
// Set an application-level variable
[Link]('appName', 'Rama');
[Link]('/', (req, res) => {
// Access the application name using [Link]()
const appName = [Link]('appName');
[Link](`Welcome to ${appName}!`);
});
[Link](PORT, () => {
[Link](`Server listening on PORT ${PORT}`);
});
75 Example for [Link]
const express = require('express');
const app = express();
// Route with a route parameter ':name'
[Link]('/users/:name', (req, res) => {
const userName = [Link]; // userName will be the value from the
URL path
[Link](`Hello, ${userName}!`);
});
[Link](3000, () => {
[Link]('Server listening on port 3000');
});
76 Example for [Link]
In [Link], [Link] is an object that contains the query string parameters from
the URL. These parameters are typically used for filtering, sorting, or providing
optional data to a route.

const express = require('express');


const app = express();
const PORT = 3000;
// Define a route that uses query parameters
[Link]('/search', (req, res) => {
// Access query parameters using [Link]
const searchTerm = [Link].q; // e.g., 'javascript'
const pageNumber = [Link]; // e.g., '2'
const category = [Link]; // e.g., 'programming'
// You can perform actions based on these parameters
if (searchTerm) {
[Link](`Searching for: ${searchTerm}`);
}
77 Example for [Link]
if (pageNumber) {
[Link](`Requested page: ${pageNumber}`);
}
if (category) {
[Link](`Filtering by category: ${category}`);
}
// Send a response back to the client
[Link](`Search results for "${searchTerm}" on page ${pageNumber} in
category "${category}"`);
});
// Start the server
[Link](PORT, () => {
[Link](`Server is running on [Link]
});
78 [Link] request methods
 [Link] (types)
 This method is used to check whether the specified content types are
acceptable, based on the request's Accept HTTP header field.
[Link]('html');
//=>?html?
[Link]('text/html');
// => ?text/html?
 [Link](field)
 This method returns the specified HTTP request header field.
[Link]('Content-Type');
// => "text/plain"
[Link]('content-type');
// => "text/plain"
79 [Link] request methods
 [Link](type)
 This method returns true if the incoming request's "Content-Type" HTTP
header field matches the MIME type specified by the type parameter
[Link]('html');
[Link]('text/html');
[Link]('text/*');
// => true
 [Link](name [, defaultValue])
 This method is used to fetch the value of param name when present.
// ?name=sasha
[Link]('name')
80 [Link] Response Object
 The Response object (res) specifies the HTTP response which is sent by an
Express app when it gets an HTTP request.
 It sends response back to the client browser.
 It facilitates you to put new cookies value and that will write to the client
browser (under cross domain rule).
 Response properties
Properties Description

[Link] It holds a reference to the instance of the express application that


is using the middleware.
[Link] It is a Boolean property that indicates if the app sent HTTP
ent headers for the response.
[Link] It specifies an object that contains response local variables
scoped to the request
81 [Link] response object method
 Response Attachment method
[Link]('path/to/js_pic.png');
 Response Cookie method [Link](name, value [, options])
[Link]('name', 'Aryan', { domain: '.[Link]', path: '/admin', secure:
true });
[Link]('Section', { Names: [Aryan,Sushil,Priyanka] });
[Link]('Cart', { items: [1,2,3] }, { maxAge: 900000 });
 Response ClearCookie method [Link](name [, options])
[Link]('name', 'Aryan', { path: '/admin' });
 Response End method [Link]([data] [, encoding])
 Response Get method [Link](field) [Link]('Content-Type');
 Response JSON method:
[Link]([body]) [Link]({ name: 'ajeet' })
 Response Send method rre res

 .....some html

 ');
82 [Link] response object method
[Link]({ some: 'json' });
[Link]('
.....some html
');
 Response Set method [Link](field [, value]) [Link]('Content-
Type', 'text/plain');
 Response Type method
[Link]('.html'); // => 'text/html'
[Link]('html'); // => 'text/html'
[Link]('json'); // => 'application/json'
[Link]('application/json'); // => 'application/json'
[Link]('png'); // => image/png:
 Response sendFile method [Link](fileName, options, function (err) {
 // ...
 });
83 Middleware function
 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.
 If the current middleware function does not end the request-response
cycle, it must call next() to pass control to the next middleware function
84 Middleware function call
85 [Link] GET Request
 GET and POST both are two common HTTP requests used for building
REST API's.
 GET requests are used to send only limited amount of data because
data is sent into header while POST requests are used to send large
amount of data because data is sent in the body.
86 Form get method demo
<html>
<body>
<form action="[Link] method="GET">
First Name: <input type="text" name="first_name"/> <br/>
Last Name: <input type="text" name="last_name"/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Save it as [Link]
87 Form get method processing – [Link]
var express = require('express');
var app=express();
[Link]('/formex1', function (req, res) {
[Link]('<h1>Username: ' + [Link]['first_name']+'</h1><h1>Lastname:
'+[Link]['last_name']+'</h1>');
})
var server = [Link](8000, function () {
var host = [Link]().address
var port = [Link]().port
[Link]("Example app listening at [Link] host, port)
})
88 Form get method – example 2
<!DOCTYPE html>
<html>
<body>
<form action="[Link]
<table>
<tr><td>Enter First Name:</td><td><input type="text" name="firstname"/><td></tr>
<tr><td>Enter Last Name:</td><td><input type="text" name="lastname"/><td></tr>
<tr><td>Enter Password:</td><td><input type="password" name="password"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"> Male
<input type="radio" name="sex" value="female">Female
</td></tr>
<tr><td>About You :</td><td>
<textarea rows="5" cols="40" name="aboutyou" placeholder="Write about yourself">
</textarea>
</td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>
</body>
</html>
89 Form get method processing – [Link]
var express = require('express');
var app=express();
[Link]('/formex2', function (req, res) {
[Link]('<p>Firstname: ' + [Link]['firstname']+'</p> <p>Lastname:
'+[Link]['lastname']+'</p><p>Password: '+[Link]['password']+'</p>
<p>AboutYou: '+[Link]['aboutyou']+'</p>');
})
var server = [Link](8000, function () {
var host = [Link]().address
var port = [Link]().port
[Link]("Example app listening at [Link] host, port)
})

You might also like