Module 6 - Node JS - Up To Form Get Method
Module 6 - Node JS - Up To Form Get Method
Dr.Brindha.K 9/16/2025
2 MODULE 6 : NodeJS
Getting Started with Node.js
Using Events
Listeners
Timers and Callbacks in Node.Js
Handling data I/O in Node.js
Accessing the File System from Node.js
Implementing HTTP Services in Node.js
Dr.Brindha.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 Node.js Process model
Node.js processes user requests differently when compared to a traditional
web server model.
Node.js 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 Node.js Process model
Node.js 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 Node.js 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.
Node.js 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.
Node.js eliminates the waiting and simply continues with the next request.
Node.js runs single threaded, non blocking, asynchronously programming which is very memory
efficient.
8 Node JS - Introduction
Basically, Node.js is a run-time environment based on
JavaScript, that can be used as frontend and backend.
Node.js platform, then it was created by the developer
Ryan Dahl in the year 2009.
Considering the popularity of the Node.js development
on SimilarTech website, around 175k websites are
developed using the node.js.
The highest number of Node.js 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.
Node.js 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.
Node.js 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
Node.js
12 Important features of Node.js
Node.js can generate dynamic page content.
Node.js can create, open , read, write, delete and close
files on the server.
Node.js can collect form data.
Node.js can add, delete, modify data in your database.
13 Install Node.js on Windows
Node.js development environment can be setup in Windows, Mac, Linux
and Solaris.
Visit Node.js official web site https://nodejs.org. It will automatically detect
OS and display download link as per your Operating System.
Download Node.js installer for windows.
14 Install Node.js on Windows
Click Next to read and accept the License Agreement and then click Install. It
will install Node.js quickly on your computer. Finally, click finish to complete the
installation.
17 Verify Installation
Once you install Node.js on your computer, you can verify it by opening the
command prompt and typing node -v.
If Node.js is installed successfully then it will display the version of the
Node.js installed on your machine, as shown below
18 Node.js Console/REPL
Node.js 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
Node.js/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 Node.js 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 Node.js Console/REPL
You can execute an external JavaScript file by executing the node
fileName command.
Example.js contains the following statement
console.log("Welcome to Node JS beginners");
21 Node.js basics
Node.js supports JavaScript. So, JavaScript syntax on Node.js is similar to
the browser's JavaScript syntax.
JavaScript in Node.js 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: 'Node.js' }
A function can have attributes and properties also. It can be treated like a
class in JavaScript.
function Display(x) { console.log(x); } Display(100);
Node.js 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 Node.js basics
Each Node.js script runs in a process. It includes process object to get all
the information about the current process of Node.js application.
The following example shows how to get process information in REPL
using process object.
23 Node.js Module
Module in Node.js is a simple or complex functionality
organized in single or multiple JavaScript files which can
be reused throughout the Node.js application.
Node.js 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
Node.js 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 Node.js 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 = http.createServer(function(req, res)
{ //write code here });
server.listen(5000);
26 Node.js 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() {
console.log("Hello Welcome to everyone");
},
currTime : new Date().toLocaleDateString(),
companyName : "Vellore Institute of Technology"
}
module.exports = welcome
exports.arthmetic =
{ 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 Node.js first example
Node.js console based example
console.log("Happy to learn node.js");
var fs=require("fs");
var data=fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Task is completed");
var fs=require("fs");
fs.readFile('input.txt', function(err,data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Task is completed");
45 Event loop
In Node.js, 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 Node.js program flow is determined
by the occurrence of events.
This architecture allows Node.js 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:
Node.js 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 Node.js 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 Node.js 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 Node.js, 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 Node.js:
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) {
console.log('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.
myEmitter.on('myCustomEvent', myEventHandler);
52 Event handler in Node js
If you want the handler to be called only once, use once() instead of on():
myEmitter.once('myCustomEvent', myEventHandler);
5. Emit the event: Use the emit() method to trigger the event. You can also pass
arguments to the event handler.
req.app This is used to hold a reference to the instance of the express application that is
using the middleware.
req.body 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.
req.cookies When we use cookie-parser middleware, this property is an object that contains
cookies sent by the request.
req.params 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 req.params.name. This object defaults to {}
req.query An object containing a property for each query string parameter in the route.
req.signedcookies When using cookie-parser middleware, this property contains signed cookies
sent by the request, unsigned and ready for use.
74 Example for req.app
const express = require('express');
const app = express();
const PORT = 3000;
// Set an application-level variable
app.set('appName', 'Rama');
app.get('/', (req, res) => {
// Access the application name using req.app.get()
const appName = req.app.get('appName');
res.send(`Welcome to ${appName}!`);
});
app.listen(PORT, () => {
console.log(`Server listening on PORT ${PORT}`);
});
75 Example for req.params
const express = require('express');
const app = express();
// Route with a route parameter ':name'
app.get('/users/:name', (req, res) => {
const userName = req.params.name; // userName will be the value from the
URL path
res.send(`Hello, ${userName}!`);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
76 Example for req.query
In Express.js, req.query 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.
.....some html
');
82 Express.js response object method
res.send({ some: 'json' });
res.send('
.....some html
');
Response Set method res.set(field [, value]) res.set('Content-
Type', 'text/plain');
Response Type method
res.type('.html'); // => 'text/html'
res.type('html'); // => 'text/html'
res.type('json'); // => 'application/json'
res.type('application/json'); // => 'application/json'
res.type('png'); // => image/png:
Response sendFile method res.sendFile(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 Express.js 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="http://localhost:8000/formex1" 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 form1.html
87 Form get method processing – formex1.js
var express = require('express');
var app=express();
app.get('/formex1', function (req, res) {
res.send('<h1>Username: ' + req.query['first_name']+'</h1><h1>Lastname:
'+req.query['last_name']+'</h1>');
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
88 Form get method – example 2
<!DOCTYPE html>
<html>
<body>
<form action="http://localhost:8000/formex2">
<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 – formex2.js
var express = require('express');
var app=express();
app.get('/formex2', function (req, res) {
res.send('<p>Firstname: ' + req.query['firstname']+'</p> <p>Lastname:
'+req.query['lastname']+'</p><p>Password: '+req.query['password']+'</p>
<p>AboutYou: '+req.query['aboutyou']+'</p>');
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})