CHAPTER
FOUR [Link]
1 / 41
Table of Contents
1. [Link] Introduction....................................3 Inception of NodeJS for
1. How does a website work?......................4 non-blocking/asynchronous architecture.......13
2. What is a webpage?.................................4 11. What problem was [Link] created to solve?
3. What is the purpose of a webpage?.........5 ............................................................................ 13
Webpage vs a web application vs desktop 12. what is Nodejs now?.....................................14
application:.......................................................5 2. Main technology/component involve in Nodejs
The Browser/Web Browser:.................................6 ............................................................................ 14
4. What is a browser?..................................6 1. V8 JavaScript Engine............................15
5. Why do we need a browser?.............................7 2. Event Loop............................................16
6. Why do the texts in a webpage need to be 3. libuv.......................................................16
tagged with HTML?.............................................7 4. Thread Pool...........................................17
7. How does the browser render JS files?.............8 5. Callbacks and Promises.........................17
Static webpages Vs Dynamic webpages.....9 6. Event Queue..........................................18
8. How does a dynamic website display different 7. C++ Bindings........................................18
content?...............................................................10 8. Node Modules.......................................19
Requesting and receiving data from a 9. CommonJS Vs ES6...............................19
remote computer........................................10 10. CommonJS (CJS)................................20
9. How modern web servers handle concurrent Exporting in CommonJS......................21
requests?.............................................................10 Types of Node modules.................................26
Threading..............................................11 1. Default/Core/Built-in Modules.............27
10. How thread blocking works?........................11 2. User-Defined Modules..........................29
Pros of synchronous architecture.........12 3. Third-Party Modules.............................30
Cons of Synchronous Architecture.......12 How it Works........................................30
Popular Examples..........................................30
2 / 41
Creating a Server in [Link]..........................34 Handling Requests.........................................39
1. Using http Module (Built-in/Core Key Aspects of a Request..........................39
Module).....................................................34 1. Middleware (The Foundation)..........40
1.1. How it Work?.................................35 2. Authentication (Who are you?) ....40
2. Using Express Module (Third-Party)....36 3. Authorization (What can you do?). . .41
2.1. How it Works?...............................37
1. [Link] Introduction
Before we discuss directly to [Link] it is better to define the following terminology and questions
related to website, web application and servers.
1. How does a website work?
2. What is a webpage?
3. What is the purpose of a webpage?
4. What is a browser?
5. Why do we need a browser?
6. Why do the texts in a webpage need to be tagged with HTML?
3 / 41
7. How does the browser render JS files?
8. How does a dynamic website display different content?
9. How modern web servers handle concurrent requests?
10. How thread blocking works?
11. What problem was [Link] created to solve?
12. what is Nodejs now?
1. How does a website work?
2. What is a webpage?
A web page/webpage is a text document that is properly tagged with HTML and is viewed in
a browser.
4 / 41
3. What is the purpose of a webpage?
The main purpose of a webpage is to display a text document in a well-organized and visually
meaningful way to the user in a browser.
Webpage vs a web application vs desktop application:
A web page
is a simple text document properly tagged with HTML.
A web application/app:
is an interactive computer software that needs an internet connection or some sort of network to
function properly.
A web app uses data saved in remote computers (server) and will be using a browser to perform its
function.
Example: Facebook, Gmail
5 / 41
A desktop application/app:
is a software that runs locally on your computer, meaning you need to install it on need to install
it on the hard drive.
Unlike web apps, desktop apps are not accessible anywhere from a web browser.
Example: Adobe Photoshop
The Browser/Web Browser:
4. What is a browser?
It is a software that loads documents from a remote server and displays them to users that are
available on the internet (world wide web).
As a webpage is simply a text document, we would need help to create some useful visual
representation of the text.
A software that helps us create a useful visual representation of a text document is called a
Browser. This means a web page without the help of a Browser is as helpless as a text
document. Note: The browser is a software made of many software/programs that control
various aspects of the browser.
6 / 41
5. Why do we need a browser?
The main role of a web browser is to create a visual representation of text documents based on
the HTML tags used in the text document.
Browser rendering: This is a process by which the browser takes your hypertext markup
language document or HTML document, converts the document to human readable format, and
displays it on the browser.
In short, browser rendering is a process by which the browser creates a visual representation of
the HTML text document so that the users can view it on a browser screen.
6. Why do the texts in a webpage need to be tagged with
HTML?
For a text to be viewed in a web browser, it must be tagged with HTML tags.
When an HTML file is saved locally, all the browser needs is a way to locate the file containing
the HTML.
7 / 41
The way we achieve this is by giving a URL (Uniform Resource Locator) on the browser’s
address bar. Since we are trying to locate the file from a local computer, this URL is just the
path to the HTML file. The path is structured by the Operating System on the computer.
Example: [Link]
7. How does the browser render JS files?
We know that the browser has built-in HTML and CSS interpreters to understand and render
HTML and CSS files as soon as it finds the “.html” or “.css” file extensions.
If the required file is a JavaScript file, it means the browser needs help understanding the code
in the JavaScript file. We have said that the browser is made of different software.
For the browser to understand JS files and render them, it will use one of its software called
the browser engine.
The job of any browser’s engine is to take the JavaScript code downloaded from a remote or
local computer and interpret and compile it into something the browser can understand.
8 / 41
Static webpages Vs Dynamic webpages
Static webpages:
The word static refers to something that is fixed, that doesn’t move or change in any way. A
static page is an HTML text document with the content already written on it. A static website
contains simple HTML pages and supporting files (e.g., Cascading Style Sheets (CSS),
JavaScript (JS)) hosted on a web server. When the web server receives a user request for a
webpage, it sends the HTML page directly to the requesting browser. Note: Static pages require
manual updating of the HTML document before their contents change.
Dynamic webpages:
A dynamic webpage is a page that displays different content each time it is viewed by a user’s
input, the time of day, language, location, etc. The content of a dynamic page is not yet fully
written and tagged as HTML. Rather, it is generated when the browser requests the document.
9 / 41
8. How does a dynamic website display different content?
The HTML of dynamic pages changes due to a server-side script/logic we write to instruct the
remote server to execute before it sends the content to the user’s browser.
Requesting and receiving data from a remote computer
When a static web page is saved on another computer (called a remote server), your browser has
to ask that computer for the file. This is called making a request.
The server then sends the file back, and your browser displays the web page on your screen.
No matter where the file is on your computer (local) or a different one somewhere else (remote)
you must give the browser the correct web address (URL) so it knows exactly where to look.
9. How modern web servers handle concurrent requests?
Different web servers tried different methods to solve this problem of handling concurrent
requests. Most implemented the concept of threading.
Note: Threading is possible only if the programming language supports threading in the first place.
10 / 41
Threading
It is a way for a program/app to split itself into two or more simultaneously running tasks.
Technically speaking, threads are the virtual code/application that divide the physical core of a
CPU into virtual multiple cores.
Thread blocking/synchronous architecture:
Synchronous architecture uses thread blocking, meaning a single thread is allocated to handle
one request while other tasks remain idle until the first thread completes the task. This means
that when a request arrives from the browser, that request is received by the web server and is
allocated to a thread to handle that request. Most of the time, requests involve getting data from
the database, which involves querying the database and getting the data. In such cases, other
tasks must wait until a thread gets the data from the database.
10. How thread blocking works?
11 / 41
When a thread enters a section of code or method that can only be executed by one thread at a
time, that thread locks the section of code. That means other threads must wait until the first
thread leaves that section of code. When a thread has the code locked, it's called a blocking
thread because it is blocking other threads from executing the code.
Pros of synchronous architecture
In Synchronous Architecture, the thread that sends the query sits and waits until it gets the data
back from the database. This means that it cannot accept another request and is blocked from
other requests. This has its advantages as you don't have to worry about any other thing in the
meantime. In addition, writing synchronous programs is objectively easier than writing
asynchronous programs.
Cons of Synchronous Architecture
One of the disadvantages of this architecture is SPEED.
If there are many concurrent requests, it causes a delay.
12 / 41
A good analogy for this would be if a waiter refuses to bring out any of the dishes you ordered
until each dish was fully prepared.
To avoid the delay, we need to add more hardware to handle the requests.
Which makes it an expensive approach.
Adding additional resources could have been avoided if we could have a way to avoid the time
the CPU sits idle waiting for the response.
Inception of NodeJS for non-blocking/asynchronous architecture
11. What problem was [Link] created to solve?
[Link] was created to improve the speed of serving pages when there are a lot of concurrent
requests by designing a non-blocking or asynchronous Architecture.
Asynchronous programming relies on a non-blocking input operation that is not executed
in a hierarchical or sequential order.
This means that asynchronous operations can run multiple tasks concurrently on a single thread.
13 / 41
This simply means you can serve another client while the previous request is being handled.
12. what is Nodejs now?
[Link] is an open-source, cross-platform runtime environment that allows developers to run
JavaScript code outside a web browser, typically on the server side.
• It is built on Google’s V8 JavaScript engine and provides non-blocking, event driven
architecture, enabling it to handle many connections efficiently with a single main
thread.
For example, [Link] can handle multiple client requests in a web server without waiting for
one to finish before starting the next.
2. Main technology/component involve in Nodejs
14 / 41
1. V8 JavaScript Engine
The V8 engine is developed by Google and written in C++. It’s responsible for executing
JavaScript code by compiling it directly into machine code, making it fast and efficient. In
[Link], V8 allows JavaScript to run on the server instead of the browser.
Example: figure in the left side is the use of V8 to run JavaScript without browser (may be
server) and the second image is V8 run the same code on browser. So Nodejs use this chrome
engine to run js without browser.
15 / 41
2. Event Loop
The event loop is the core mechanism that enables [Link] to perform non-blocking I/O
operations on a single thread.
It continuously checks for tasks, executes them, and waits for events to complete. Rather than
waiting for slow tasks (like file or network operations), it continues running other code and
handles results later.
Example: If you call [Link]() to read a file, Node continues executing other code while
waiting for the file to load.
3. libuv
libuv is a C library that provides asynchronous I/O and implements the event loop internally. It
handles operations like file system access, networking, DNS, and timers in a platform-
independent way. It uses a thread pool and interacts with the operating system kernel for event
notifications. after the events handled the libun signal the event loop for next operation.
Example: When you make an HTTP request in [Link], libuv manages the socket connections
and notifies Node when the response arrives.
16 / 41
4. Thread Pool
The thread pool is part of libuv and contains a small number of background threads (default: 4).
It runs tasks that cannot be performed asynchronously by the operating system, such as file I/O,
encryption, and compression. This prevents blocking the main thread. Example: When you use
[Link]() to save a file, that operation runs in the thread pool so your main JavaScript code
can keep executing.
5. Callbacks and Promises
[Link] uses callbacks and promises to handle asynchronous results once operations complete.
A callback is a function executed after a task finishes, while promises (and async/await) provide
a more readable way to manage async code.
Example: The [Link] runs only after the file is read.
17 / 41
6. Event Queue
The Event Queue (also called the Callback Queue) is a data structure inside [Link] that
temporarily stores the callbacks of completed asynchronous operations (like file reads, timers,
or network requests) until the event loop is ready to execute them. It works hand-in-hand with
libuv (which adds completed events to the queue) and the event loop (which removes and
executes them in order). It operates in FIFO (First in, First Out) order the first callback that
enters the queue is the first to be executed.
7. C++ Bindings
18 / 41
[Link] itself is partly written in C++, which connects (or “binds”) JavaScript running on the
V8 engine with system-level features through bindings. This allows [Link] to access low-level
resources efficiently.
Example: When you call [Link](), the JS code internally connects to C++ functions that
actually interact with the operating system.
8. Node Modules
Modules are the fundamental building blocks of the code structure. The module system allows
you to organize your code, hide information, and only expose the public aspect of a module by
exporting. Node module is a single or multiple JavaScript files with specific functionality
organized in a way that can be reused throughout the [Link] application.
9. CommonJS Vs ES6
In [Link], modules allow developers to organize code into reusable blocks. Modules help
improve code maintainability, readability, and reusability. JavaScript two main standards for
writing modules. The first is CommonJS which is original [Link] module system. The second
19 / 41
one is ES6 Modules the modern official JavaScript module standard introduced in ES6 (2015).
These standards define how modules export their content and how other modules import it.
CommonJS is synchronous and Node-specific. ES6 Modules are asynchronous and browser-
compatible, becoming the modern standard.
10. CommonJS (CJS)
CommonJS is a module standard for [Link] created in 2009. It allows splitting code into
separate files and sharing functions, objects, or variables between them.
Keywords in CommonJS Modules
Keyword Definition Example
require() Built-in function used to import a module into the const getCS = require('./ipstu);
current file.
[Link] Defines what a module exports to make it [Link] = { getCS };
available to other files.
20 / 41
exports Shortcut to [Link] to export multiple [Link] = getCS;
members.
__filename Returns the full path of the current module file. [Link](__filename);
__dirname Returns the directory path of the current module [Link](__dirname);
file.
Exporting in CommonJS
1. Exporting a Single Value (Function, Object, or Variable)
• Use [Link] to export one thing.
When you assign directly to [Link], only that single value is exported.
Example: we have two js file with the name of [Link] that has different module and [Link] the file that
imports module from [Link]
21 / 41
And the [Link] is
2. Exporting a multiple Value (Function, Object, or Variable)
22 / 41
And the module that import this is below.
We must use the same name for this case when destruction the exported data.
Using exports
We import this like
And the output is like ES6 Modules (ESM) ES6 Modules are the official JavaScript module system
introduced in 2015 (ES6).
23 / 41
They provide a standard way to export and import modules in JavaScript, usable in both [Link] and
browsers.
Keywords in ES6 Modules
Keyword Definition Example
import Used to import functions, import { getCS } from './
objects, or default exports from [Link]';
another module.
export Used to export functions, export function getCS()
objects, or variables from a { [Link]("hello computer
module so other modules can use Science student"); }
them.
export default Defines a single default export export default function getCS()
per module. Can be imported { [Link]("hello computer
24 / 41
with any name. Science student"); }
Example: we have two js file with the name of [Link] that has different module and [Link] the file that
imports module from [Link]
The next thing is import to use the above module
The default export imported by its name or other name but the other must be specifying the name of
function or variables. In one file only one default export
The following is how to import the default export
25 / 41
The following is how to import modules by specifying the target function that we went to use
We can import both default and other export together as follow
Types of Node modules
26 / 41
[Link] uses a modular system (primarily CommonJS with require() and [Link], or modern ES
modules with import/export) to organize and reuse code. There are three main types of modules:
1. Default/Core/Built-in Modules
These are pre-installed with [Link] itself. No need to install anything, they come compiled into the
[Link] binary. They provide essential low level functionalities like file handling, networking, etc.
Common Examples:
• fs (File System) → Read/write files
• http / https → Create servers or make requests
• path → Handle file paths
• os → Operating system info
• url → Parse URLs
• events → Event emitters
1. fs (File System) Used for reading, writing, and managing files on the disk.
Import const fs = require('fs');
Examples:
27 / 41
Write file:
[Link]('[Link]'Hello content', (err) => { if(err) throw err; [Link]('Saved'); });
Read file: [Link]('[Link]', 'utf8', (err, data) => { if(err) throw err; [Link](data); });
2. http / https Used to create web servers or make HTTP/HTTPS requests.
Import:
const http = require('http'); or const https = require('https');
Examples:
Create server:
const server = [Link]((req, res) => { [Link]('Hello World'); }); [Link](3000);
3. path Helps work with file and directory paths in a safe, cross-platform way.
Import:
const path = require('path');
Examples:
Join paths: [Link](__dirname, 'folder', '[Link]');
28 / 41
4. os Provides information about the operating system.
Import:
const os = require('os');
Examples:
Platform: [Link](); → 'win32' or 'linux' or 'darwin'
CPU cores: [Link]().length;
Total memory (GB): [Link]() / 1024 / 1024 / 1024;
Home directory: [Link]();
2. User-Defined Modules
A user-defined module is a custom JavaScript file you create to organize and reuse your own code.
You export functions or values from it, then import and use them in other files. The examples are the
same to example we discussed in above commonJS and ES6 examples.
29 / 41
3. Third-Party Modules
Third-party modules are external packages created by the community (not built into [Link]).
They add extra features like web frameworks, database tools, utilities, etc.
You install them using npm (Node Package Manager).
How it Works
Install with: npm install package-name
Import with: const name = require('package-name');
Than we can use in our code just like built-in or user-defined modules.
Popular Examples
1. Express
Most popular and minimal web framework for [Link]. Makes it easy to build web servers,
REST APIs, and full backend applications.
Install: npm install express
30 / 41
Common use: Create routes, handle HTTP requests/responses, build APIs and servers.
2. Axios
Easy and popular HTTP client for making API requests (GET, POST, etc.). Supports promises
and interceptors. Install: npm install axios
Common use: Fetch data from external APIs.
3. Bcrypt
Library for hashing passwords securely. Protects user passwords in databases.
Install: npm install bcrypt
Common use: User registration/login authentication.
4. Body-parser
Middleware to parse incoming request bodies (JSON, URL-encoded, etc.) in Express apps.
(Built into Express from v4.16+).
Install: npm install body-parser
31 / 41
Common use: Handle form data or JSON payloads.
5. Cors
Enables Cross-Origin Resource Sharing. Allows your API to be accessed from different
domains.
Install: npm install cors
Common use: Fix CORS errors in Express servers.
6. Dotenv
Loads environment variables from a .env file into [Link]. Keeps secrets safe.
Install: npm install dotenv
Common use: Configure database connections or API keys securely.
7. Firebase-admin
Official Firebase Admin SDK. Manage Firebase services from the server.
Install: npm install firebase-admin
Common use: Server-side operations (verify tokens, manage users).
32 / 41
8. Jsonwebtoken
Creates and verifies JSON Web Tokens (JWT) for authentication.
Install: npm install jsonwebtoken
Common use: Stateless login sessions (token-based auth).
9. Multer
Middleware for handling file uploads in Express.
Install: npm install multer
Common use: Upload images, documents, or files.
10. Mysql2
MySQL database driver with promise support and modern features.
Install: npm install mysql2
Common use: Connect and query MySQL databases.
11. Nodemailer
33 / 41
Send emails easily (SMTP, Gmail, etc.).
Install: npm install nodemailer
Common use: Send verification emails, password resets, notifications.
12. Pdfkit
Generate PDF documents programmatically (text, images, tables).
Install: npm install pdfkit
Common use: Create invoices, reports, certificates.
These packages are widely used in real-world [Link] backend projects. Install with npm install
and require them to start using.
Creating a Server in [Link]
1. Using http Module (Built-in/Core Module)
The http module is part of [Link] core.
34 / 41
No installation required. It gives full low-level control over the server.
Import: const http = require('http');
1.1. How it Work?
Create server with [Link](callback)
Callback receives req (request) and res (response) objects
Use [Link]() to send response
Call [Link](port) to start
Example
35 / 41
2. Using Express Module (Third-Party)
Express is the most popular framework.
36 / 41
Makes server creation and routing much simpler and cleaner.
Install: npm install express
Import: const express = require('express');
2.1. How it Works?
Create app with express()
Define routes using [Link](), [Link](), etc.
Start server with [Link](port)
Example
37 / 41
NB: please Refer the lab manual
38 / 41
Handling Requests
Request handling involves receiving data from the client, processing it, and sending back a response.
Key Aspects of a Request
➢ Request URL ([Link]): The path requested by the client.
➢ Request Method ([Link]): The HTTP verb (GET, POST, PUT, DELETE).
➢ Request Headers ([Link]): Metadata about the request (e.g., Content-Type,
Authorization). Request Body: Data sent with POST/PUT requests (e.g., form data, JSON
payload).
➢ Query Parameters ([Link]): Data appended to the URL after a ? (e.g., /users?limit=10).
➢ Route Parameters ([Link]): Variables defined in the route path (e.g., /users/:id).
Example
39 / 41
Authentication, Authorization, middleware
1. Middleware (The Foundation)
Definition: A function that runs before or after a route handler executes.
It has access to the request (req), response (res), and the ability to pass control (next()).
Role: Acts as the processing stage for every incoming request.
Common Uses: Parsing the request body ([Link]()), logging, and most importantly,
security checks.
Key Action: Must call next() to let the request continue to the next step, or send a response
([Link]()) to terminate it.
2. Authentication (Who are you?)
Goal: To verify a user's identity. Proving who you are.
Process: User provides credentials (username/password) $\rightarrow$ Server checks them
against the database.
[Link] Tools: Packages like [Link] or using JWTs (JSON Web Tokens).
40 / 41
Implementation Note: Usually implemented via a specific middleware that checks for a valid
token or session ID in the request header.
If the token is bad, the middleware terminates the request with a 401 Unauthorized status.
3. Authorization (What can you do?)
Goal: To verify a user's permissions once their identity is confirmed. What are you allowed to
do? Prerequisite: Must always run AFTER Authentication.
Process: The server checks the authenticated user's role (e.g., 'admin', 'guest') against the
required permission for the specific action (e.g., deleting a file).
Implementation Note: Implemented via a second, dedicated middleware.
This middleware checks the user's role (usually attached to [Link] by the authentication
middleware).
If permissions are insufficient, it terminates the request with a 403 Forbidden status.
41 / 41