Node.js Basics and Application Development
Node.js Basics and Application Development
[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 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
[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]");
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);
};
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] 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] 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.
.....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)
})