Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
29 views111 pages

Fullstack Notes With Programs

JavaScript is a high-level programming language used for web development, enabling interactivity and dynamic content. It has applications in various fields such as web and mobile app development, game development, and server-side programming, utilizing frameworks like React.js and Node.js. The document also covers regular expressions, email validation, simple calculator implementation, and introduces React.js, AngularJS, Express.js, and MongoDB basics.
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)
29 views111 pages

Fullstack Notes With Programs

JavaScript is a high-level programming language used for web development, enabling interactivity and dynamic content. It has applications in various fields such as web and mobile app development, game development, and server-side programming, utilizing frameworks like React.js and Node.js. The document also covers regular expressions, email validation, simple calculator implementation, and introduces React.js, AngularJS, Express.js, and MongoDB basics.
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
You are on page 1/ 111

UNIT-1

What is JavaScript?

JavaScript (JS) is a high-level, dynamic programming language primarily used for web
development. It enables interactivity on websites, such as animations, form validations, dynamic
content updates, and more.
Key Features:
 Client-Side Execution: Runs in web browsers without requiring additional software.
 Event-Driven: Reacts to user interactions (clicks, scrolls, etc.).
 Asynchronous Processing: Uses callbacks, promises, and async/await for non-blocking
execution.
 Object-Oriented & Functional: Supports multiple programming paradigms.

Real-Time Applications of JavaScript


JavaScript is used in a wide range of real-world applications, including:
1. Web Development (Front-end & Back-end)
 Frameworks like React.js, Angular, and Vue.js power modern, interactive web
applications.
 Node.js allows JavaScript to run on servers.
 Example: Google, Facebook, Twitter (dynamic content updates).
2. Mobile App Development
 Frameworks like React Native and Ionic allow building cross-platform mobile apps.
 Example: Instagram, Airbnb (React Native-based apps).
3. Game Development
 Three.js for 3D games.
 Phaser.js for 2D games.
 Example: Browser-based games like 2048, Slither.io.
4. Server-Side Development
 Node.js enables JavaScript on the backend, replacing traditional server-side languages like
PHP.
 Example: Netflix, PayPal use Node.js for scalable backends.
5. Web APIs & Real-Time Applications
 WebSockets for live chat applications.
 AJAX & Fetch API for seamless web data fetching.
 Example: WhatsApp Web, Slack, Google Docs (real-time collaboration).
6. AI & Machine Learning
 Libraries like TensorFlow.js allow ML models to run in browsers.
 Example: AI-powered chatbots & recommendation engines.
7. Internet of Things (IoT)
 Node.js can control IoT devices.
 Example: Smart home automation systems, IoT dashboards.
8. Cybersecurity & Ethical Hacking
 JavaScript is used for penetration testing and detecting security vulnerabilities.
 Example: Browser security testing tools.
9. Automation & Scripting
 Puppeteer & Selenium automate web tasks (like web scraping).
 Example: Web crawling, automated testing.
10. Desktop Applications
 Electron.js allows building cross-platform desktop apps.
 Example: VS Code, Slack, Discord (Electron-based apps).
Here are some important topics and programs on Java Scripts. ( All of them may or may not
be important for exams but they are important to gain knowledge )

Regular expressions Basics :

^ - beginning symbol
$ - ending symbol
/ ………. / eg :- /^gmail$/
[a-z] [A-Z] [0-9]

n+ Matches any string that contains at least one n


n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n Matches any string that is not followed by a specific string n

/yahoo/ means any number of characters followed by yahoo followed by any number of characters
/^yahoo$/ means exactly yahoo [ ^ means beginning , $ means at the ending ]

/^[a-z]*$/ means any number of small characters -- * means 0 or more


/^[a-z]{3}/ means any exactly 3 small characters followed by any characters
/^[a-z]{3}$/ means exactly any 3 small characters
/^[a-z]{3,5}$/ means any 3 to 5 small characters
/^[a-z]{3}\.$/ means exactly any 3 small characters followed by.
/^[a-z]{3}\.[a-z]$/ means exactly 3 small characters followed by. Followed by one single character
/^[^0-9]/ -- Means string should not begin with 0-9

Program to validate email

Conditions for valid email


1.Could be in caps or small
2.Should start with only characters [a|A]
3.May include numbers in email id after few characters
4.Valid domain names for email servers =.in, .uk, us, com, .co.in
i.e ending domain name should have either [2-5] characters

program

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
var y=/^([a-z]|[A-Z]){1,25}[0-9]*\@([a-z]|[A-Z]){2,10}\.([a-z]|[A-Z]|.){3,5}$/;
if(x.match(y))
alert(" Valid email ");
else
alert("In valid email ");
}
</script>
</head>
<body>
<h3>EMAIL VALIDATION </h3>
ENTER EMAIL :
<input type="text" id="myText">
<button onClick="myFunction()">Try it</button>
<p id="demo"> </p>
</body>
</html>

********************************************************************************
*****

SIMPLE CALCULATOR

<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>

</head>
<body>
<div class="calculator">
<h2>Simple Calculator</h2>
<input type="text" id="display" disabled>
<br>
<div class="buttons">
<button onclick="appendNumber(1)">1</button>
<button onclick="appendNumber(2)">2</button>
<button onclick="appendNumber(3)">3</button>
<button onclick="appendNumber(4)">4</button>
<button onclick="appendNumber(5)">5</button>
<button onclick="appendNumber(6)">6</button>
<button onclick="appendNumber(7)">7</button>
<button onclick="appendNumber(8)">8</button>
<button onclick="appendNumber(9)">9</button>
<button onclick="appendNumber(0)">0</button>
<button onclick="clearDisplay()">C</button>
</div>
<br>
<button onclick="setOperator('+')">+</button>
<button onclick="setOperator('-')">-</button>
<button onclick="setOperator('*')">*</button>
<button onclick="setOperator('/')">/</button>
<br>
<button onclick="calculate()">=</button>
<h3>Result: <span id="result">0</span></h3>
</div>

<script>
let currentInput = "";
let operator = "";
let firstNumber = "";

function appendNumber(num) {
currentInput += num;
document.getElementById("display").value = currentInput;
}

function setOperator(op) {
if (currentInput === "") return;
firstNumber = currentInput;
operator = op;
currentInput = "";
document.getElementById("display").value = "";
}
function calculate() {
if (firstNumber === "" || currentInput === "") return;
let num1 = parseFloat(firstNumber);
let num2 = parseFloat(currentInput);
let result = 0;

switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num2 !== 0 ? num1 / num2 : 'Cannot divide by zero'; break;
default: result = 'Error';
}

document.getElementById("result").innerText = result;
document.getElementById("display").value = result;
currentInput = "";
firstNumber = "";
operator = "";
}

function clearDisplay() {
currentInput = "";
firstNumber = "";
operator = "";
document.getElementById("display").value = "";
document.getElementById("result").innerText = "0";
}
</script>
</body>
</html>

********************************************************************************
******
PROGRAMS ON CREATING DYNAMIC HTML

1. Chaning colors ( bg and foreground)

<html>
<head>
<title> Dynamic Colors
</title>
<script>
function setColor(where, newColor) {
if (where == "background" )
document.body.style.backgroundColor = newColor;
else
document.body.style.color = newColor;
}
</script>
</head>

<body>
<p style = " font-family: Times; font-style: italics;
font-size: 24pt;">
Demonstration on dynamic settings of the
foreground and background colors.
</p>
<form>
<p>
Background color:
<input type= "text" name="background" size ="10"
onchange = "setColor('background', this.value)" />
<br />
Foreground color:
<input type= "text" name="foreground" size ="10"
onchange = "setColor('foreground', this.value)" />
<br />
</p>
</form>
</body>
</html>

2. Fonts and color of fonts changing upon moving cursor

<html>
<head>
<title>
Dynamic fonts for links
</title>
<style type ="text/css">
.regText { font: Times; font-size:16pt;}
</style>

</head>

<body>
<p class ="regText">
Mouseover on below paragraph
<p style = "color: blue;"
onmouseover = "this.style.color = 'red';
this.style.font = 'italic 16pt Times';"
onmouseout = "this.style.color = 'blue';
this.style.font = 'normal 16pt Times';" >
This is working great ! </p>
Simple demonstration on font change.
</p>

</body>
</html>
3. Moving image based on x and y given coordinates

<html>
<head>
<title>
Moving elements
</title>
<script type = "text/javascript">
<!--
// The event handler function to move and element

function moveIt(movee, newTop, newLeft) {


dom = document.getElementById(movee).style;
dom.top = newTop + "px";
dom.left = newLeft + "px";
}
//-->
</script>
</head>

<body>
<form action ="">
<p>
x coordinate:<input type= "text" id ="leftCoord" size ="5" />
<br />
y coordinate: <input type= "text" id ="topCoord" size ="5" />
<br />
<input type= "button" value = "Move it" onclick =
"moveIt('div1',document.getElementById('topCoord').value,
document.getElementById('leftCoord').value)" />
</P>
</form>

<div id ="div1" style = "position: absolute; top: 115 px; left: 0;">
<img src= "computer.jpg" />
</div>
</body>
</html>

4. deleting elements upon clicking

<!DOCTYPE html>
<html>
<head>
<script>
function demo(x)
{
x.remove();
}
</script>
<style>
.myDiv1 {
border: 10px outset black;
background-color: grey;
text-align: center;
}
.myDiv2 {
border: 10px outset green;
background-color: lightgreen;
text-align: center;
}
.myDiv3 {
border: 10px outset red;
background-color: lightpink;
text-align: center;
}
</style>
</head>
<body>
<h1>Div element - Click on boxes to vanish - Using java script</h1>
<p id="p1"></p>
<div id="div1" class="myDiv1" onclick="demo(this)">
<h2>This is h2 element </h2>
<p>This is paragraph </p>
</div>

<br>
<div id="div2" class="myDiv2" onclick="demo(this)">
<h2>This is h2 element </h2>
<p>This is paragraph </p>
</div>
<br>
<div id="div3" class="myDiv3" onclick="demo(this)">
<h2>This is h2 element </h2>
<p>This is paragraph </p>
</div>
</body>
</html>

End of java script programs

********************************************************************************
**********************

Reactjs :

React.js is a JavaScript library developed by Meta (Facebook) for building user interfaces
(UIs), especially for single-page applications (SPAs). It allows developers to create reusable UI
components and manage application states efficiently.

Why Use React.js?


1. Component-Based Architecture – Code is divided into reusable components, making
development structured.
2. Virtual DOM – React updates only changed parts of the UI instead of reloading the whole
page, improving performance.
3. Fast Rendering – Uses a "diffing" algorithm to update only necessary UI parts.
4. State Management – React’s state system makes UI updates dynamic and efficient.
5. One-Way Data Binding – Enhances control and debugging by ensuring data flows in one
direction.
6. Strong Community Support – Huge ecosystem, libraries, and tools available.
Create a React App Using Vite

Instead of create-react-app, we use Vite for better performance.


What is Vite?
Simple JavaScript can run directly in a browser without needing a server. However, React.js
requires a development server because of the way it processes and renders code.
Vite (pronounced "veet") is a modern frontend build tool and development server created by
Evan You (the creator of Vue.js). It is designed to be faster and more efficient than traditional
bundlers like Webpack.
npm create vite@latest my-react-app --template react

Navigate to Project and Install Dependencies


cd my-react-app
npm install

Start the Development Server


npm run dev

The app runs locally, usually at http://localhost:5173/.

Understanding the React.js Project Structure


Writing first reactjs program

Modify App.jsx (Main React Component)


Open src/App.jsx and replace its content with the following simple program:

function App() {
return (
<div>
<h1>Hello, React!</h1>
<p>Welcome to my first React.js app.</p>
</div>
);
}

export default App;

How It Works
 The App function is a React component that returns JSX (HTML-like syntax in
JavaScript).
 <h1> and <p> are displayed in the browser.
 export default App; allows this component to be used in main.jsx.
Open http://localhost:5173/ in your browser, and you will see:
Hello, React!
Welcome to my first React.js app.

********************************************************************************
***************
Angularjs :
What is AngularJS?
AngularJS is a JavaScript framework developed by Google in 2010 for building dynamic web
applications. It extends HTML with additional attributes (called directives) and follows the
Model-View-Controller (MVC) architecture.
📌 Important Note:
 AngularJS (1.x) is the old version, which is now obsolete.
 Angular (2+) is the modern version (completely different from AngularJS).
 Most new projects use Angular (2+), not AngularJS.
Basics of AngularJS -- Key Features:
1. Two-Way Data Binding – Auto-updates UI when data changes.
2. Directives (ng-*) – Custom HTML attributes (ng-model, ng-repeat).
3. Dependency Injection (DI) – Manages dependencies automatically.
4. MVC Architecture – Divides code into Model, View, Controller.
5. Single Page Application (SPA) Support – Loads content dynamically.
Differences between React and Angular

********************************************************************************
**************

Express framework:
Express.js is a fast, minimal, and flexible web framework for Node.js that simplifies building
web applications and APIs.
It provides:
✅ Routing – Handles different URLs (/home, /about).
✅ Middleware – Processes requests before sending responses.
✅ Request & Response Handling – Easily handle GET, POST, PUT, DELETE requests.
✅ Template Engines – Supports rendering HTML dynamically (EJS, Pug, Handlebars).
✅ REST API Support – Ideal for creating APIs.

Why Use Express.js?


1. Easier than raw Node.js – No need to manually create an HTTP server.
2. Faster Development – Simple syntax for handling requests.
3. Supports Middleware – Helps with logging, authentication, and validation.
4. Scalable – Used for small apps to large enterprise systems.
5. Compatible with Databases – Works with MongoDB, MySQL, PostgreSQL, etc.

********************************************************************************
******************
MongoDB basics

As part of unit-1 , you will study introduction and only basic commands

MongoDB Overview
MongoDB is a NoSQL database that stores data in a document-oriented format using BSON
(Binary JSON). Unlike relational databases, which store data in tables with fixed schemas,
MongoDB uses flexible, schema-less collections.
Key Features
 Document-Oriented: Stores data as JSON-like documents.
 Schema Flexibility: No fixed schema; each document can have different fields.
 Scalability: Supports horizontal scaling through sharding.
 Indexing: Supports various types of indexes for efficient querying.
 Aggregation Framework: Performs complex data manipulations.
What is a Collection in MongoDB?
A collection in MongoDB is equivalent to a table in a relational database. It is a group of
documents (records) that share a common purpose but do not necessarily have a fixed schema.
Key Features of a Collection:
1. Schema-less: Documents within a collection can have different fields and structures.
2. Stores Documents: Each document is stored in BSON (Binary JSON) format.
3. Dynamic Growth: Collections are automatically created when you insert a document.
4. Indexing Support: You can create indexes to speed up queries.
Basic commands :

1. Connect to database
mongod

2. Listing out database


show dbs

3. Create or Switch Database


use databasename

4. list out Collections (Tables)


show collections

5. creating collections
db.createCollection("students")

6. Insert a document
db.students.insertOne({name: "Alice", age: 22, course: "CS"})

7. insert multiple documents


db.students.insertMany([
{name: "Bob", age: 23, course: "IT"},
{name: "Charlie", age: 24, course: "CS"}
])

8. uploading external collection i.e json file


mongoimport --db myDatabase --collection students --file students.json --jsonArray
********************************************************************************
*******

Full stack components

A Full-Stack application consists of three main layers:


1. Frontend (Client-Side)
2. Backend (Server-Side)
3. Database (Storage)
Here’s a breakdown of common components in each layer:

1️⃣ Frontend (Client-Side)


The frontend is what users interact with in a web application. It includes:
✅ Languages & Markup
 HTML (Structure)
 CSS (Styling)
 JavaScript (Functionality)
✅ Frontend Frameworks/Libraries
 React.js (Popular UI library)
 Angular (Google’s framework)
 Vue.js (Lightweight alternative)
 Svelte (Compiler-based UI framework)
✅ CSS Frameworks & Preprocessors
 Bootstrap (Popular CSS framework)
 Tailwind CSS (Utility-first CSS)
 Sass / LESS (CSS preprocessors)
✅ State Management
 Redux (For React-based apps)
 Context API (React built-in state management)
 Vuex / Pinia (Vue.js state management)
✅ Frontend Build Tools
 Webpack (Bundler)
 Vite (Faster alternative to Webpack)
 Parcel (Zero-config bundler)
✅ Package Managers
 npm (Node Package Manager)
 Yarn (Alternative to npm)
✅ APIs for Communication
 REST APIs (Traditional approach)
 GraphQL (More flexible querying)
 WebSockets (For real-time communication)

2️⃣ Backend (Server-Side)


The backend handles business logic, database interactions, and API requests.
✅ Programming Languages
 JavaScript (Node.js)
 Python (Django, Flask, FastAPI)
 Java (Spring Boot)
 C# (ASP.NET)
 Ruby (Ruby on Rails)
 PHP (Laravel)
✅ Backend Frameworks
 Node.js (JavaScript runtime)
 Express.js (Lightweight Node.js framework)
 NestJS (TypeScript-based framework)
 Django (Python-based full-featured framework)
 Flask (Lightweight Python framework)
 Spring Boot (Java-based backend framework)
✅ Authentication & Authorization
 JWT (JSON Web Tokens)
 OAuth (Google, Facebook, GitHub login)
 Firebase Authentication
 Auth0
✅ Caching
 Redis (In-memory data store)
 Memcached (Another caching solution)
✅ Real-time Communication
 WebSockets (Bidirectional communication)
 Socket.io (Real-time communication library)
 Firebase Realtime Database
✅ Backend APIs
 RESTful APIs (Most common)
 GraphQL APIs (For flexible querying)
 gRPC (For high-performance communication)
✅ Background Jobs & Task Queues
 Celery (Python)
 BullMQ (Node.js)
 Sidekiq (Ruby)

3️⃣ Database (Storage)


Databases store and retrieve application data.
✅ Relational Databases (SQL-based)
 MySQL (Popular open-source SQL database)
 PostgreSQL (Advanced relational database)
 MariaDB (MySQL alternative)
 Microsoft SQL Server (Enterprise-level SQL database)
✅ NoSQL Databases (Schema-less, Scalable)
 MongoDB (Document-oriented database)
 Firebase Firestore (Cloud NoSQL database)
 Cassandra (Highly scalable NoSQL database)
 CouchDB (JSON document database)
✅ Graph Databases
 Neo4j (Graph-based database)
✅ ORMs (Object-Relational Mappers)
 Sequelize (Node.js for SQL databases)
 TypeORM (TypeScript ORM for SQL)
 Prisma (Modern ORM for Node.js)
 SQLAlchemy (Python ORM)

4️⃣ DevOps & Deployment


To deploy and manage full-stack applications, these tools are used:
✅ Version Control
 Git
 GitHub / GitLab / Bitbucket
✅ CI/CD Pipelines
 GitHub Actions
 Jenkins
 GitLab CI/CD
 CircleCI
✅ Containerization & Orchestration
 Docker (Containerization)
 Kubernetes (Container Orchestration)
✅ Cloud Providers
 AWS (Amazon Web Services)
 Google Cloud Platform (GCP)
 Microsoft Azure
 DigitalOcean
✅ Serverless Platforms
 AWS Lambda
 Firebase Functions
 Vercel / Netlify (For frontend & backend hosting)
✅ Web Servers & Reverse Proxies
 Nginx (Web server, reverse proxy)
 Apache (Traditional web server)
✅ Monitoring & Logging
 Prometheus (Monitoring)
 Grafana (Visualization)
 ELK Stack (Elasticsearch, Logstash, Kibana)

********************************************************************************
*****************

Introduction to Nodejs

Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to


run JavaScript code outside a web browser. It is built on Google Chrome's V8 JavaScript engine
and is primarily used for building scalable network applications, such as web servers, APIs, and
real-time applications.
Key Features of Node.js
1. Asynchronous & Non-Blocking I/O
 Asynchronous: Node.js operates on an event-driven architecture, meaning it does not wait
for a function to complete before moving to the next task.
 Non-blocking I/O: Traditional web servers follow a blocking I/O model (one request at a
time), but Node.js can handle multiple requests concurrently without blocking the execution thread.
2. Single-Threaded with Event Loop
 Unlike traditional multi-threaded servers, Node.js operates on a single-threaded event loop,
which makes it lightweight and efficient.
 The event loop continuously listens for incoming requests and delegates tasks to the system
kernel whenever possible.
3. Built on V8 Engine
 Node.js uses Google’s V8 engine, which compiles JavaScript to machine code, making
execution fast and efficient.
4. Cross-Platform
 Node.js can run on Windows, macOS, and Linux.
 It allows developers to write platform-independent applications.
5. Package Management with npm
 npm (Node Package Manager) is the default package manager for Node.js, providing
access to thousands of libraries and modules.
6. Microservices & API Development
 Node.js is widely used for REST APIs and GraphQL APIs due to its lightweight nature
and ability to handle multiple requests efficiently.
How Node.js Works?
1. A request comes to the Node.js server.
2. Node.js checks if the request requires a database or file system operation.
 If not, it processes the request immediately.
 If yes, it sends the task to the event loop.
3. The event loop handles the request asynchronously.
4. Once the operation is completed, Node.js sends the response back to the client.
****************************************************************************
Installing Node.js on Linux and Windows
Node.js can be installed on both Linux and Windows in multiple ways.
Installing Node.js on Linux
There are multiple methods to install Node.js on Linux:
1️. Installing via Package Manager (Recommended)
Most Linux distributions provide Node.js in their official repositories.

For Ubuntu/Debian-based Systems


Update your package list
bash

sudo apt update


Install Node.js and npm
bash

sudo apt install nodejs npm -y


Verify installation
bash

node -v
npm -v

If installed correctly, this will display the versions of Node.js and npm.

2. Installing Node.js via NodeSource (Latest Version)

If you need the latest stable version of Node.js, use NodeSource:


Add the NodeSource repository (For Ubuntu/Debian)
bash
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
(Replace 20.x with the latest LTS version)

Install Node.js
bash
sudo apt install nodejs -y
Verify installation
bash
node -v
npm -v

3. Installing Node.js Using NVM for Windows


Just like Linux, you can use NVM for Windows to manage multiple Node.js versions.

Download NVM for Windows


Visit NVM for Windows
Download the latest .zip or .exe file.
Install NVM

Extract and run the installer.


Follow the installation steps.
Install Node.js Using NVM Open Command Prompt (cmd) and run:

powershell

nvm install 20
(Replace 20 with the required version)

Use a specific Node.js version

powershell

nvm use 20
Verify installation

powershell
node -v
npm -v

********************************************************************************
*******************
Creating Your First "Hello World" Application in Node.js

Step1:- create simple web server


Step2:- open browser and check the output

Creating a Simple http Web Server


Let the below file name is app.js

const http = require('http');

// Create a server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});

// Define a port
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});

open terminal and type node app.js ( where app.js is above file name)
when you run, web server will be running in port 3000
Type localhost:3000 in your browser then you can see the output as HelloWorld

Note that res is inbuilt response object. It is used to send response to the user. In the same way, we
do have req inbuilt request object. Ofcos, this object is not used in the above program. It is used to
take input from user.

********************************************************************************
*********************
Understanding Nodejs architecture, Event Modules and How to add work to event Queue

Consider the below architecture

 Users send requests (blocking or non-blocking) to the server for performing operations.
 The requests enter the Event Queue first at the server-side.
 The Event queue passes the requests sequentially to the event loop. The event loop checks
the nature of the request (blocking or non-blocking).
 Event Loop processes the non-blocking requests which do not require external resources and
returns the responses to the corresponding clients
 For blocking requests, a single thread is assigned to the process for completing the task by
using external resources.
 After the completion of the operation, the request is redirected to the Event Loop which
delivers the response back to the client.

Understanding the Nodejs Event Module


The Event Module in Node.js is a core feature that allows applications to be event-driven, meaning
they respond to events (such as user actions, system processes, or network requests). This makes
Node.js efficient and non-blocking.

1️. What is the Event Module?


 Node.js uses the Event-Driven Architecture, where code reacts to events instead of
following a strict sequence.
 The events module in Node.js provides a class called EventEmitter that allows us to create,
listen for, and trigger events.

2️. How Do Events Work?


Think of events like a real-world scenario:
1. You subscribe to an event (like setting an alarm).
2. The event occurs (the alarm rings).
3. A predefined action is executed (you wake up).
Similarly, in Node.js:
 We define an event.
 We listen for it.
 We trigger the event when needed.

3️. Key Concepts of Events in Node.js


🔹 EventEmitter (Event Manager)
 The EventEmitter class acts as a manager that keeps track of events and their listeners.
 It allows us to register and trigger events.
🔹 Registering an Event Listener
 When we "register" an event, we define what should happen when the event occurs.
 Example: Imagine an "order placed" event in an e-commerce system. When an order is
placed, the system listens for this event and responds by sending a confirmation email.
🔹 Emitting (Triggering) an Event
 "Emitting" means activating the event so that all registered listeners respond.
 Example: When a user logs in, an event can be emitted to record login details and notify
other parts of the system.

4️. Real-Life Examples of Events


1. Button Click on a Website
 A user clicks a button.
 The browser listens for the "click" event.
 A function executes, like submitting a form.
2. File Upload Progress
 A user uploads a file.
 The system tracks the upload progress.
 It emits progress updates until the upload is complete.
3. Chat Application
 A user sends a message.
 The event module detects the new message.
 It notifies the recipient in real-time.
4. Server Handling Requests
 A web server receives a request (like loading a webpage).
 It listens for the "request received" event.
 The server processes the request and sends a response.

5️. Special Events in Node.js


🔹 The error Event
 If an error occurs and there is no event listener for it, the program may crash.
 Handling errors through events ensures that the system can respond gracefully.
🔹 The once Event
 Some events should only happen once, like sending a welcome email when a user signs up.
🔹 Removing Event Listeners
 If an event is no longer needed, it can be removed to free up system resources.

6️. Why Use Events in Node.js?


Asynchronous Execution → Events allow non-blocking operations.
Scalability → Event-driven design helps handle thousands of requests efficiently.
Modularity → Different parts of an application can listen for and respond to events separately.
********************************************************************************
****************

1. What is the Event Queue?


The event queue in Node.js is a part of the event-driven, non-blocking architecture. It is where
asynchronous tasks wait to be executed once the main execution stack (synchronous code) is
cleared.
How It Works
1. When an asynchronous operation is initiated (e.g., reading a file, making a network request,
setting a timer), Node.js does not wait for it to complete.
2. Instead, the operation is delegated to background workers (e.g., the OS kernel, Node.js
internal threads).
3. Once the operation completes, its associated callback function is queued in the event
queue.
4. The event loop then picks up these tasks from the queue and executes them when the call
stack is empty.

2️. How to Add Work to the Event Queue?


In Node.js, there are different ways to add work (tasks) to the event queue, depending on when you
want them to execute. These include:
🔹 (1) Timers Queue (Using setTimeout)
 What it does? Schedules a task to run after a specified delay.
 How it works? The function is added to the event queue and will execute after the delay is
over.
Theory:
When you use setTimeout(), Node.js registers the function and schedules it in the timers queue.
Once the specified delay expires, the event loop picks it up and executes it after all synchronous
code has completed.

🔹 (2) Check Queue (Using setImmediate)


 What it does? Adds a task to the event queue that executes right after the I/O phase.
 How it works? The callback is scheduled to run immediately after the current phase of
the event loop is completed.
Theory:
setImmediate() adds the task to the check queue, which is processed before any scheduled timers
(setTimeout()). It ensures that the function executes as soon as possible after the current
operation completes.

🔹 (3) Next Tick Queue (Using process.nextTick)


 What it does? Queues a function to execute before the event loop proceeds to the next
phase.
 How it works? It ensures that a task runs immediately after the current execution stack is
cleared, even before I/O tasks or timers.
Theory:
Node.js treats process.nextTick() as a priority queue and executes these tasks before checking any
other event queue (timers, I/O, etc.). This makes it useful for high-priority tasks that need to be
executed as soon as possible.

🔹 (4) I/O Queue (Using Asynchronous File Reads, Network Requests, etc.)
 What it does? Adds I/O tasks (e.g., file system operations, database queries) to the event
queue.
 How it works? Once the I/O operation completes, the event loop picks up the corresponding
callback function and executes it.
Theory:
Asynchronous I/O operations in Node.js do not block the execution. Instead, they are handled by
background workers. Once an operation is finished, its callback is queued and executed when the
event loop reaches the I/O phase.

🔹 (5) Microtask Queue (Using Promises and then())


 What it does? Adds tasks to the microtask queue, which runs before any other queued
event.
 How it works? Any resolved promise’s .then() callback is processed immediately after
synchronous code and before timers or I/O tasks.
Theory:
Promises have higher priority than normal callbacks in the event queue. The microtask queue is
always executed before moving to the next phase of the event loop, ensuring that resolved
promises execute as soon as possible.

3️. Execution Order of the Event Queue


When multiple asynchronous tasks are queued, they execute in the following order:
1. Synchronous Code → Runs first in the call stack.
2. Microtask Queue (Promises, process.nextTick()) → Executes before anything else in the
event queue.
3. Timers Queue (setTimeout(), setInterval()) → Executes after the specified delay.
4. I/O Queue (File reads, network requests) → Executes after the current phase is completed.
5. Check Queue (setImmediate()) → Executes right after I/O operations.

4️. Why Does This Matter?


🔹 Performance Optimization → Understanding when a task executes helps improve application
efficiency.
🔹 Preventing Race Conditions → Ensuring that operations execute in the expected order avoids
unpredictable behavior.
🔹 Handling High-Priority Tasks → Using process.nextTick() or the microtask queue ensures
important operations run immediately.
********************************************************************************
********************

1. What is a Callback in Node.js?


A callback is a function that is passed as an argument to another function and is executed after
the completion of that function.
Since Node.js is asynchronous and non-blocking, callbacks are used extensively to handle tasks
such as:
 Reading files
 Making API requests
 Handling database queries
 Processing user input
Key Concept: Callbacks Enable Asynchronous Execution
Instead of waiting for a function to complete before moving forward, Node.js moves on to execute
other code and calls the callback function once the task is done.

2. How Callbacks Work in Node.js?


1. A function takes another function as a parameter.
2. Once the operation completes, it "calls back" the passed function with results or errors.
3. The callback function is executed after the main function finishes processing.
Example in Theory (Without Code)
 Suppose you request data from a database.
 Instead of waiting for the database to respond, Node.js continues executing other tasks.
 Once the database fetches the data, the callback function is triggered with the retrieved
information.
3️. Types of Callbacks in Node.js
🔹 1. Synchronous Callbacks (Blocking Callbacks)
 These callbacks execute immediately as part of the current function execution.
 Used mainly for small, immediate operations that don’t require waiting.
Example in Theory:
 A function performs a mathematical operation and calls another function to print the
result.
 The callback executes immediately, without waiting for any external operation.

🔹 2. Asynchronous Callbacks (Non-Blocking Callbacks)


 These callbacks execute later, once an asynchronous operation completes.
 Commonly used in I/O operations, network requests, or file handling.
Example in Theory:
 A function reads a file and passes the data to a callback function.
 Node.js does not wait for the file reading to finish and instead moves on.
 Once the file is read, the callback function executes with the retrieved content.

4️. Error-First Callbacks in Node.js


 Node.js follows the error-first callback convention.
 The first argument of a callback function is always an error object (if an error occurs).
 The second argument contains data or the result of the operation.
Example in Theory:
 A function fetches user details from a database.
 If an error occurs, the callback function receives the error and handles it.
 If the operation succeeds, the callback function processes the retrieved user data.
This ensures that errors are handled properly instead of causing unexpected failures.

5️. Why Are Callbacks Important in Node.js?


Efficient Execution – Prevents blocking of operations, making Node.js fast.
Handles Asynchronous Operations – Ensures non-blocking behavior for I/O tasks.
Error Handling – Uses error-first callbacks to manage failures gracefully.
********************************************************************************
*********************
UNIT-2

Working with JSON

What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging
data between a server and a client. It is easy to read, write, and parse, making it widely used in
web APIs, databases, and configurations.

1️. Key Features of JSON:


Lightweight – Uses minimal syntax for data representation.
Human-Readable – Easy to understand and edit.
Language-Independent – Supported in almost all programming languages.
Structured Data Format – Stores data in a key-value format, like objects in JavaScript.

2️. JSON Structure


JSON data is written as key-value pairs, where:
 Keys are strings enclosed in double quotes ("key")
 Values can be:
 Strings (e.g., "name": "Alice")
 Numbers (e.g., "age": 25)
 Booleans (true or false)
 Arrays (e.g., "hobbies": ["reading", "traveling"])
 Objects (nested JSON data)

3️. Example of JSON Data


{
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"isStudent": false,
"skills": ["JavaScript", "Node.js", "React"],
"address":
{
"street": "123 Main St",
"city": "New York",
"zipcode": "10001"
}
}

Note:- The file extension should be .json

Where is JSON Used?


APIs (Web Services) – Sending and receiving data between clients and servers.
Configuration Files – Storing settings in applications (config.json).
Databases (NoSQL) – MongoDB stores data in JSON format.
Data Storage – Exporting/importing structured data.
********************************************************************************
*****************
What is the Buffer Module in Node.js?
The Buffer module in Node.js is a built-in module that provides a way to handle binary data
directly in memory. It is useful when dealing with raw data such as files, network packets, or
streams.
By default, JavaScript does not handle binary data efficiently, but Buffers allow Node.js to work
with binary data easily.

How to Use Buffers in Node.js?


1. Creating a Buffer
You can create a buffer in multiple ways:
const buf = Buffer.alloc(10); // Creates a buffer of 10 bytes (filled with zeros)
console.log(buf);
output
<Buffer 00 00 00 00 00 00 00 00 00 00>
You can also initialize a buffer with specific data:
const buf = Buffer.from("Hello");
console.log(buf); // Prints: <Buffer 48 65 6c 6c 6f>
Buffer.from("Hello") → Converts the string "Hello" into a binary buffer.
 Stores raw binary data instead of a regular string.
 The resulting buf contains a sequence of bytes representing "Hello" in UTF-8 encoding.

Accessing Buffer Values


Since buf stores raw binary data, you can access individual bytes like an array:
const buf = Buffer.from("Hello");
console.log(buf[0]); // Output: 72 (ASCII code of 'H')
console.log(buf[1]); // Output: 101 (ASCII code of 'e')
console.log(buf.toString()); // Output: Hello

Buffer Concatenation
If you receive data in chunks, you can concatenate buffers:
const buf1 = Buffer.from("Hello ");
const buf2 = Buffer.from("World");
const combined = Buffer.concat([buf1, buf2]);

console.log(combined.toString()); // Output: Hello World

When to Use Buffers?


 Handling binary data (e.g., images, files, network packets).
 Reading or writing streams of data.
 Working with TCP or HTTP requests that come in chunks.
 Encoding/decoding data in different formats
How buffer is different from Array
********************************************************************************
***************

Understanding the Stream Module in Node.js

The Stream module in Node.js is a built-in module that allows handling data in chunks instead of
loading everything into memory at once. This is useful for working with large files, network
requests, and real-time data processing.
Types of Streams
Node.js provides four types of streams:

You will learn how streams are used in next section along with file modules.
********************************************************************************
*****************
Accessing files using file module in Nodejs :- open, read, write and close
In Node.js, you can interact with the file system using the built-in fs (File System) module. This
module allows you to perform operations such as reading, writing, opening, closing, and deleting
files.
Reading a File with Explicit Open and Close
Here, we manually open the file using fs.open(), read it using fs.read(), and then close it using
fs.close().
const fs = require('fs');
const filePath = 'example.txt';
// Open the file for reading
fs.open(filePath, 'r', (err, fd) => {
if (err) {
console.error('Error opening file:', err);
return;
}

// Get file stats to determine size


fs.fstat(fd, (err, stats) => {
if (err) {
console.error('Error getting file stats:', err);
fs.close(fd, () => {}); // Ensure file is closed in case of an error
return;
}

const buffer = Buffer.alloc(stats.size);

// Read the file


fs.read(fd, buffer, 0, stats.size, 0, (err, bytesRead, buffer) => {
if (err) {
console.error('Error reading file:', err);
} else {
console.log('File content:\n', buffer.toString());
}

// Close the file after reading


fs.close(fd, (err) => {
if (err) {
console.error('Error closing file:', err);
} else {
console.log('File closed successfully.');
}
});
});
});
});
Explanation:
1. fs.open(filePath, 'r', callback): Opens the file in read mode ('r').
2. fs.fstat(fd, callback): Retrieves the file size.
3. fs.read(fd, buffer, offset, length, position, callback): Reads the file into a buffer.
4. fs.close(fd, callback): Closes the file after reading.
2. Writing to a File with Explicit Open and Close
Here, we manually open the file using fs.open(), write to it using fs.write(), and close it using
fs.close().
const fs = require('fs');
const filePath = 'output.txt';
const fileContent = 'Hello, this is a sample text written explicitly using open and close functions.';

// Open the file for writing


fs.open(filePath, 'w', (err, fd) => {
if (err) {
console.error('Error opening file:', err);
return;
}

// Write to the file


fs.write(fd, fileContent, (err, written, string) => {
if (err) {
console.error('Error writing to file:', err);
} else {
console.log('File written successfully.');
}
// Close the file after writing
fs.close(fd, (err) => {
if (err) {
console.error('Error closing file:', err);
} else {
console.log('File closed successfully.');
}
});
});
});
Explanation:
1. fs.open(filePath, 'w', callback): Opens the file in write mode ('w').
2. fs.write(fd, fileContent, callback): Writes content to the file.
3. fs.close(fd, callback): Closes the file after writing.

Delete a File Asynchronously


You can delete a file in Node.js using the fs.unlink() method (asynchronous) or fs.unlinkSync()
method (synchronous).
const fs = require('fs');

const filePath = 'example.txt'; // File to be deleted

fs.unlink(filePath, (err) => {


if (err) {
console.error('Error deleting file:', err);
return;
}
console.log('File deleted successfully.');
});
Explanation:
 fs.unlink(filePath, callback): Deletes the file asynchronously.
 If an error occurs (e.g., file does not exist), it is handled inside the callback.
 On success, it logs a confirmation message.
Note :- Important -- The difference between synchronous and asynchronous is synchronous --
Blocks the execution until the operation is complete where as asynchronous -- Non-blocking,
continues executing other code. Sync is slower where as async is faster.
********************************************************************************
*******************
Processing urls, querystrings, form parameters, understanding request and response and
Implementing http client and server
When building web applications, you often need to handle URLs and extract information such as
paths, query parameters, and route variables. In Node.js, this is done using the built-in url and
querystring modules.
Understanding a URL Structure
A typical URL looks like this:
https://example.com/products?category=electronics&price=low
It consists of:
 Protocol: https://
 Host: example.com
 Path: /products
 Query String: ?category=electronics&price=low
Request and Response inbuilt objects in Nodejs
Request (req)
The request object (req) contains information about the HTTP request sent by the client (browser,
Postman, etc.). It includes:

Response object (res) :-


Response (res)
The response object (res) is used to send a response back to the client (browser).
Request-Response Flow in the Example
1. Client Request (index.html form submission)
 The user fills in Student ID and Student Name.
 Pressing "Submit" sends a POST request to /submit.
2. Server Handles the Request (server.js)
 The server listens for POST /submit.
 Reads incoming form data (req.on("data", callback)).
 Parses the data.
3. Server Sends a Response (res)
 Generates an HTML page displaying the submitted data.
 Sends the response to the client using res.writeHead() and res.end().
You will understand this best by writing a nodejs program which takes inputs like student id and
student name from index.html and process the inputs and prints them on web page upon pressing
the submit button. The same example can also be used to demonstrate streams and also for
implementing http client and server. We need to do all these things to print student details collected
on web page.
To do this program, we need to create two files
1. Index.html file which consists of two text fields
2. Server file – server.js – which takes input, process it and prints output on screen
INDEX.HTML file
<!DOCTYPE html>
<html>
<head>
<title>Student Form</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="/submit" method="POST">
<label for="studentId">Student ID:</label>
<input type="text" id="studentId" name="studentId" required>
<br><br>
<label for="studentName">Student Name:</label>
<input type="text" id="studentName" name="studentName" required>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

SERVER.JS file
const http = require("http");
const fs = require("fs");
const url = require("url");
const querystring = require("querystring");

const server = http.createServer((req, res) => {


if (req.method === "GET" && req.url === "/") {
// Serve the index.html file
fs.readFile("index.html", (err, data) => {
if (err) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal Server Error");
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
}
});
} else if (req.method === "POST" && req.url === "/submit") {
// Handle form submission
let body = "";
req.on("data", chunk => {
body += chunk.toString();
});
req.on("end", () => {
const formData = querystring.parse(body);
const responseHTML = `
<html>
<head><title>Student Details</title></head>
<body>
<h2>Submitted Data</h2>
<p><strong>Student ID:</strong> ${formData.studentId}</p>
<p><strong>Student Name:</strong> ${formData.studentName}</p>
<a href="/">Go Back</a>
</body>
</html>
`;
res.writeHead(200, { "Content-Type": "text/html" });
res.end(responseHTML);
});
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 Not Found");
}
});

server.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});

How to Run the Server


1. Save server.js and index.html in the same directory.
2. Open a terminal in that directory.
3. Run node server.js
4. Open browser and type localhost:3000
5. fill the form and submit to see the output

Nodejs Program to read form data from query string and generate response
Explanation about program
There are two files. One is form.html and other is server.js. First run the server file in node
environment. Open browser and type localhost:3000 then form.html will be loaded on webpage.
Provide input and press submit. You will see form data is accessed via query string and displayed on
the web page.
1. Form.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Form</title>
</head>
<body>
<h2>User Registration Form</h2>
<form action="/submit" method="GET">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>

<label>Skills:</label><br>
<input type="checkbox" name="skills" value="C"> C<br>
<input type="checkbox" name="skills" value="C++"> C++<br>
<input type="checkbox" name="skills" value="Java"> Java<br>
<input type="checkbox" name="skills" value="Python"> Python<br><br>

<label>Gender:</label><br>
<input type="radio" name="gender" value="Male"> Male<br>
<input type="radio" name="gender" value="Female"> Female<br><br>

<label for="location">Location:</label>
<select id="location" name="location">
<option value="Hyderabad">Hyderabad</option>
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
</select><br><br>

<input type="submit" value="Submit">


</form>
</body>
</html>

2. Server.js

const http = require('http');


const fs = require('fs');
const url = require('url');

const server = http.createServer((req, res) => {


if (req.url === '/') {
// Serve the HTML file
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error loading index.html');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else if (req.url.startsWith('/submit')) {
// Process form submission
const queryParams = url.parse(req.url, true).query;

const username = queryParams.username || 'N/A';


const password = queryParams.password || 'N/A'; // In real cases, never print passwords
const skills = queryParams.skills
? Array.isArray(queryParams.skills)
? queryParams.skills.join(', ')
: queryParams.skills
: 'None';
const gender = queryParams.gender || 'Not specified';
const location = queryParams.location || 'Not specified';

const responseHTML = `
<html>
<head><title>Form Submission</title></head>
<body>
<h2>Submitted Data</h2>
<p><strong>Username:</strong> ${username}</p>
<p><strong>Password:</strong> ${password}</p>
<p><strong>Skills:</strong> ${skills}</p>
<p><strong>Gender:</strong> ${gender}</p>
<p><strong>Location:</strong> ${location}</p>
<a href="/">Go Back</a>
</body>
</html>
`;

res.writeHead(200, { 'Content-Type': 'text/html' });


res.end(responseHTML);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});

server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});

3. User login using nodejs using file module


Explanation about program
There are two files. One is users.html with two text fields like username and pwd. Enter details and
submit. Server file gets the data and validates it by comparing user provided password with actual
password stored in text file. Here file module is used.
First run server.js file and open browser. Type localhost:3000 to load user login page.
1. login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="/login" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>

<input type="submit" value="Login">


</form>

<p id="message"></p>
</body>
</html>
2. Server.js
const http = require('http');
const fs = require('fs');
const url = require('url');
const querystring = require('querystring');

const usersFile = 'users.txt';


const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);

if (req.method === 'GET' && req.url === '/') {


// Serve the login form
fs.readFile('login.html', 'utf8', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error loading login page');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else if (req.method === 'POST' && parsedUrl.pathname === '/login') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});

req.on('end', () => {
const postData = querystring.parse(body);
const { username, password } = postData;

fs.readFile(usersFile, 'utf8', (err, data) => {


if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error reading user data');
return;
}

const storedPassword = data.trim();

if (password === storedPassword) {


res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome, ' + username + '!');
} else {
// Reload login page with error message
fs.readFile('login.html', 'utf8', (err, pageData) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error loading login page');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
const modifiedPage = pageData.replace('<p id="message"></p>', '<p
id="message" style="color:red;">Incorrect password. Please try again.</p>');
res.end(modifiedPage);
}
});
}
});
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});

server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});

3. text file in same directory – users.txt


12345

********************************************************************************
*****************
OS Module in Nodejs
The os module in Node.js is a built-in module that provides operating system-related utility
methods and properties. It allows you to interact with the underlying operating system, retrieve
system-related information, and perform various OS-level operations. This module is useful for
system monitoring, logging, and performance optimization in Node.js applications
How to Use the os Module
To use the os module, you need to require it in your Node.js script:
const os = require('os');
Commonly Used Methods
1. Get OS Platform
console.log(os.platform()); // Outputs: 'win32', 'linux', 'darwin' (macOS)
2. Get OS Architecture
console.log(os.arch()); // Outputs: 'x64', 'arm', 'ia32', etc.
3. Get CPU Information
console.log(os.cpus()); // Returns an array of CPU core details
4. Get Free Memory
console.log(os.freemem()); // Returns available system memory in bytes
5. Get Total Memory
console.log(os.totalmem()); // Returns total system memory in bytes
6. Get Hostname
console.log(os.hostname()); // Returns the system's hostname
7. Get Network Interfaces
console.log(os.networkInterfaces()); // Returns an object with network details
8. Get OS Uptime
console.log(os.uptime()); // Returns system uptime in seconds
9. Get User Info
console.log(os.userInfo()); // Returns information about the current user
10. Get Home Directory
console.log(os.homedir()); // Returns the home directory path

********************************************************************************
********************
UTIL Module in nodejs :-
The util module in Node.js provides utility functions that help with debugging, formatting, and
working with objects, callbacks, and inheritance. It is part of Node.js's standard library and does not
require installation.
How to Use the util Module
First, you need to import the module:
javascript
CopyEdit
const util = require('util');
Key Functions in util:
1. util.format()
Formats strings like printf in C.
console.log(util.format('%s is %d years old.', 'Alice', 25));
// Output: Alice is 25 years old.
2. util.promisify()
Converts a callback-based function into a Promise-based function.Example:
const fs = require('fs');
const readFile = util.promisify(fs.readFile);

readFile('example.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
3. util.inherits()
Helps with prototype-based inheritance.
Example:
const EventEmitter = require('events');

function MyClass() {
EventEmitter.call(this);
}

util.inherits(MyClass, EventEmitter);

const obj = new MyClass();


obj.on('event', () => console.log('Event triggered!'));
obj.emit('event');
4. util.inspect()
Returns a string representation of an object, useful for debugging.
const obj = { a: 1, b: [2, 3], c: { d: 4 } };
console.log(util.inspect(obj, { depth: null, colors: true }));
5. util.types
Contains type-checking functions. Example:
console.log(util.types.isPromise(Promise.resolve())); // true
********************************************************************************
**************

DNS Module in Nodejs :-

The dns module in Node.js provides functions to perform Domain Name System (DNS) lookups
and resolve domain names into IP addresses. It allows applications to interact with DNS servers,
retrieve records, and perform hostname resolution.
How to Use the dns Module in Node.js
The dns module comes built-in with Node.js, so you don’t need to install it separately. You can use
it by requiring the module.
1. Import the dns module
const dns = require('dns');

2. Basic DNS Lookups


A) dns.lookup()
Resolves a hostname into an IP address (similar to getaddrinfo in POSIX).

dns.lookup('google.com', (err, address, family) => {


if (err) throw err;
console.log(`IP Address: ${address}, IPv${family}`);
});
 Returns a single IPv4 or IPv6 address.

B) dns.resolve()
Retrieves DNS records for a given hostname.

dns.resolve('google.com', 'A', (err, addresses) => {


if (err) throw err;
console.log(`A Records: ${addresses}`);
});
 Can fetch different record types like 'A', 'AAAA', 'MX', 'CNAME', 'TXT', 'NS', etc.

C) dns.reverse()
Finds the hostname for a given IP address.

dns.reverse('8.8.8.8', (err, hostnames) => {


if (err) throw err;
console.log(`Hostnames: ${hostnames}`);
});
 Useful for reverse DNS lookups.

D) dns.resolveMx()
Retrieves Mail Exchange (MX) records for email routing.

dns.resolveMx('gmail.com', (err, addresses) => {


if (err) throw err;
console.log('MX Records:', addresses);
});

3. Using the dns.promises API (Async/Await)


If you prefer using Promises instead of callbacks, use dns.promises.

const dnsPromises = require('dns').promises;

async function resolveDNS() {


try {
const addresses = await dnsPromises.resolve4('google.com');
console.log(`Resolved IPs: ${addresses}`);
} catch (err) {
console.error(err);
}
}

resolveDNS();
4. Configure Custom DNS Server
By default, Node.js uses the system’s DNS settings. You can change the DNS server using:

dns.setServers(['8.8.8.8', '8.8.4.4']); // Google Public DNS


The dns module in Node.js is useful for performing domain name lookups, retrieving different types
of DNS records, and even reverse lookups. You can use either the callback-based API or the
dns.promises API for asynchronous operations.

********************************************************************************
*************
CRYPTO Module in Nodejs
The crypto module in Node.js provides cryptographic functionality, including hashing, encryption,
and decryption. It allows you to perform operations like password hashing, data encryption, and
secure random number generation.
1. Importing the crypto Module
The crypto module is built into Node.js, so you don’t need to install it separately. Import it using:
const crypto = require('crypto');

2. Common Uses of the crypto Module


A) Hashing Data (SHA, MD5, etc.)
Hashing is a one-way process that converts data into a fixed-length string.
Example: Creating a SHA-256 Hash
const hash = crypto.createHash('sha256').update('Hello World').digest('hex');
console.log(`SHA-256 Hash: ${hash}`);
 .update() adds the input data.
 .digest('hex') outputs the hash as a hexadecimal string.
Supported Hash Algorithms
 md5
 sha1
 sha256
 sha512
 And more (use crypto.getHashes() to see all available algorithms).

B) Generating HMAC (Hash-Based Message Authentication Code)


HMAC is used for message authentication.
Example: HMAC with SHA-256

const hmac = crypto.createHmac('sha256', 'my-secret-key')


.update('Hello World')
.digest('hex');

console.log(`HMAC: ${hmac}`);
 Uses a secret key for additional security.

C) Symmetric Encryption and Decryption (AES)


AES (Advanced Encryption Standard) is used for encrypting and decrypting data.
Example: Encrypting and Decrypting with AES-256

const algorithm = 'aes-256-cbc';


const key = crypto.randomBytes(32); // Secret key (32 bytes for AES-256)
const iv = crypto.randomBytes(16); // Initialization vector

// Encrypt
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}

// Decrypt
function decrypt(encryptedText) {
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}

const message = "Hello, Secure World!";


const encrypted = encrypt(message);
const decrypted = decrypt(encrypted);

console.log(`Encrypted: ${encrypted}`);
console.log(`Decrypted: ${decrypted}`);
 Uses a secret key and IV to encrypt and decrypt messages.
 AES-256-CBC is a secure and widely used encryption method.

D) Generating Secure Random Bytes


To generate cryptographically secure random values, use:

crypto.randomBytes(16, (err, buffer) => {


if (err) throw err;
console.log(`Random Bytes: ${buffer.toString('hex')}`);
});
 Useful for generating secure tokens and keys.

E) Key Pair Generation (RSA)


RSA is commonly used for public-private key encryption.
Example: Generating RSA Key Pair

crypto.generateKeyPair('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
}, (err, publicKey, privateKey) => {
if (err) throw err;
console.log('Public Key:', publicKey);
console.log('Private Key:', privateKey);
});
 RSA is widely used for secure communications.

3. Using the crypto.promises API (Async/Await)


For modern asynchronous programming, use crypto.promises.
const { randomBytes } = require('crypto').promises;
async function generateRandomBytes() {
const buffer = await randomBytes(16);
console.log(`Random Bytes (Async): ${buffer.toString('hex')}`);
}

generateRandomBytes();

Conclusion
The crypto module is essential for security-related tasks in Node.js, including:
Hashing (SHA, MD5)
HMAC authentication
Encryption/Decryption (AES, RSA)
Generating secure random values
********************************************************************************
****************

UNIT -3

Why NoSQL Databases?


NoSQL (Not Only SQL) databases emerged as a response to the limitations of traditional relational
database management systems (RDBMS) in dealing with modern application requirements. The
explosion of big data, real-time web apps, and cloud computing created challenges that RDBMS
could not handle efficiently due to their rigid schema, complex joins, and scaling difficulties.
Key reasons why NoSQL databases are needed include:
1. Scalability: Traditional RDBMS are difficult to scale horizontally. NoSQL databases are
designed to scale out easily across multiple servers or clusters, which is essential for handling large
volumes of data like those in social media platforms or IoT systems.
2. Schema Flexibility: RDBMS enforce strict schema, making changes time-consuming and
risky. NoSQL databases offer schema-less or dynamic schema structures that can easily evolve
with the application without downtime.
3. High Performance: NoSQL databases are optimized for specific access patterns and can
deliver faster performance by reducing or eliminating complex joins and normalizations.
4. Handling Unstructured Data: RDBMS are suitable for structured data with predefined
columns. NoSQL can store unstructured, semi-structured, or multi-structured data (like JSON,
XML, images, logs) efficiently.
5. Cost-Effectiveness: Open-source NoSQL databases can run on commodity hardware,
reducing infrastructure costs.
6. Cloud-Native Design: Most NoSQL databases are designed to work in distributed, cloud-
based environments, offering fault tolerance and high availability.

Differences Between RDBMS and NoSQL


Feature RDBMS (Relational DB) NoSQL (Non-relational DB)
Document, Key-Value, Column,
Data Model Tabular (rows and columns)
Graph
Schema Fixed schema (rigid) Dynamic schema (flexible)
Joins Supports complex joins Limited or no join support
Vertical scaling (add more power Horizontal scaling (add more
Scalability
to one server) servers)
BASE model (eventual
Transactions ACID-compliant
consistency)
Slower with complex queries on Optimized for fast reads/writes at
Performance
large data scale
Data Integrity High due to strict constraints Less strict, more flexibility
MySQL, PostgreSQL, Oracle, MongoDB, Cassandra, Redis,
Examples
SQL Server Neo4j

Popular NoSQL Databases


NoSQL is not a single type of database but an umbrella term for various models:
1. Document-Oriented Databases:
a. MongoDB: Stores data in JSON-like BSON documents. It’s one of the most popular and
general-purpose NoSQL databases.
b. CouchDB: Also document-based, known for its multi-master sync features.
2. Key-Value Stores:
a. Redis: An in-memory key-value store ideal for caching, real-time analytics, and message
brokering.
b. Amazon DynamoDB: Fully managed, scalable key-value and document DB offered by
AWS.
3. Column-Family Stores:
a. Apache Cassandra: Highly scalable, used for handling massive volumes of structured data
across many commodity servers.
b. HBase: Built on top of Hadoop HDFS, ideal for sparse data and high write throughput.
4. Graph Databases:
a. Neo4j: Stores data as nodes and relationships. Excellent for use cases like social networks
and fraud detection.
b. ArangoDB: A multi-model database that supports graph, document, and key-value models.
Major Applications of NoSQL Databases
NoSQL databases have become a backbone in many modern applications. Key use cases include:
1. Real-Time Analytics: Applications like social media monitoring, clickstream analysis, and
recommendation engines (Netflix, Spotify) use NoSQL for fast, real-time processing.
2. IoT and Sensor Data: NoSQL handles high-volume time-series data from smart devices
(e.g., smart homes, manufacturing sensors).
3. Content Management Systems: Websites and applications with rich media and user-
generated content benefit from document-based databases like MongoDB.
4. E-Commerce and Retail: Product catalogs with varied attributes are better managed in a
flexible schema (e.g., Amazon, eBay).
5. Gaming: Game states, user sessions, and leaderboards need real-time performance and
scalability, making NoSQL ideal.
6. Fraud Detection: Graph databases like Neo4j detect relationships and anomalies
effectively, crucial for security systems.
7. Big Data Applications: Platforms like Hadoop and Spark integrate with NoSQL databases
for storage and processing of massive datasets.
Real-Time Applications of NoSQL Databases
1. Facebook – Social Graph and Real-Time Feed Management
 Use Case: Managing social connections (friends, likes, comments, groups) and delivering
real-time news feeds.
 NoSQL Used:
o Cassandra: Originally developed at Facebook to handle massive real-time write throughput
(e.g., inbox search).
o TAO (Facebook's own NoSQL store): For reading and writing social graph data efficiently
with low latency.
 Why NoSQL: Needs to store billions of nodes and edges representing users, posts, likes,
and relationships, all with millisecond-level access speed.

2. Amazon – Product Catalog and User Sessions


 Use Case: Storing dynamic and large-scale product catalogs with varying attributes, user
preferences, and shopping carts.
 NoSQL Used:
o DynamoDB: A key-value and document store for high-availability, low-latency operations.
 Why NoSQL: Offers horizontal scalability, low-latency data access, and high availability
for personalized shopping experiences.

3. Netflix – Content Recommendations and User Activity


 Use Case: Real-time recommendation engine, video metadata storage, and streaming data
logs.
 NoSQL Used:
o Cassandra: For storing viewing history, user profiles, and recommendations.
o DynamoDB: For faster metadata retrieval and session management.
 Why NoSQL: Supports global distribution, high availability, and fast writes with no single
point of failure.

4. Google – Bigtable for Search Indexing and Analytics


 Use Case: Search engine indexing, Gmail backend storage, and analytics data.
 NoSQL Used:
o Bigtable: Google's column-oriented database that inspired HBase and Cassandra.
 Why NoSQL: Handles petabytes of data across thousands of servers with low-latency
random reads/writes.

5. Twitter – Real-Time Tweet Management and User Graphs


 Use Case: Tweets, retweets, mentions, user timelines, and follower relationships.
 NoSQL Used:
o Manhattan: Twitter’s distributed storage platform built to manage multiple data models
(key-value, graph, etc.)
o Earlier used Cassandra for message and activity storage.
 Why NoSQL: Supports billions of tweets, real-time updates, and high-speed writes globally.

6. LinkedIn – Messaging, Feed, and Activity Streams


 Use Case: User profile storage, real-time activity feed, and job recommendations.
 NoSQL Used:
o Voldemort: Key-value store used earlier for session storage.
o Kafka (streaming, not NoSQL but complements it) + Document stores for flexible data.
 Why NoSQL: Allows horizontal scaling and low latency across its professional network
infrastructure.

7. Uber – Dynamic Pricing and Real-Time Location Tracking


 Use Case: Tracking vehicles in real-time, fare calculation, and surge pricing.
 NoSQL Used:
o Schemaless (Uber’s custom document store built on top of MySQL-like system with
NoSQL capabilities)
o Uses Redis for caching and Cassandra for geospatial data and trip logs.
 Why NoSQL: Geographically distributed, real-time access to location and driver-passenger
data.

8. Instagram – Metadata Storage and Feed Generation


 Use Case: Handling user posts, likes, comments, and stories.
 NoSQL Used:
o Cassandra for feed generation.
o Redis for session caching and quick lookups.
 Why NoSQL: High throughput, eventual consistency, and horizontal scalability for billions
of users.

9. Spotify – Playlist and User Behavior Tracking


 Use Case: Store user playlists, music preferences, playback activity.
 NoSQL Used:
o Cassandra: To store real-time activity logs and listening history.
 Why NoSQL: Handles massive volume of user activity data with high availability.
10. Snapchat – Message Delivery and Story Storage
 Use Case: Ephemeral messaging, story updates, and image storage.
 NoSQL Used:
o Cassandra: Used for storing messages and story metadata.
o Google Bigtable and Cloud Datastore: For structured but flexible user data.
 Why NoSQL: Quick expiration, large scale write throughput, low-latency requirements.
********************************************************************************
*****
What is MongoDB?
MongoDB is a NoSQL, open-source, document-oriented database system developed by
MongoDB Inc. It stores data in flexible, JSON-like documents (called BSON - Binary JSON),
making it ideal for applications that require fast development, scalability, and real-time data
processing.
Key features
It’s designed to handle large volumes of unstructured or semi-structured data, which traditional
relational databases (RDBMS) struggle with.

Feature Description

Data is stored in flexible, JSON-like documents. Each


Document-Oriented
document can have a different structure.
No predefined schema. Fields can vary between
Schema-less
documents in the same collection.
Supports horizontal scaling using sharding, making it
Scalability
ideal for big data and distributed systems.
Uses replica sets for automatic failover and
High Availability
redundancy.
Supports various types of indexes (single field,
Indexing
compound, text, geospatial) for fast queries.
Offers powerful data transformation and analytics
Aggregation Framework
capabilities using pipelines.
Automatically distributes large datasets across multiple
Built-in Sharding
servers.
Since version 4.0+, it supports multi-document ACID
Support for Transactions
transactions.

MongoDB Data Types


MongoDB stores data in documents using BSON (Binary JSON), which extends JSON by adding
additional data types that are useful for database storage and querying. This makes MongoDB
flexible and powerful in handling complex data.
Common MongoDB Data Types:
 String: This is the most common data type used to store text data. For example, a document
may have { name: "John Doe" }.
 Integer: Used for whole numbers. MongoDB supports both 32-bit and 64-bit integers. For
example, { age: 30 }.
 Double: Represents floating-point numbers. For instance, { price: 19.99 }.
 Boolean: Stores true or false values. Example: { isActive: true }.
 Array: Represents an ordered list of values, which can be of mixed types. For example,
{ tags: ["mongodb", "database", "NoSQL"] }.
 Object (Embedded Document): Stores nested documents inside a document, enabling
complex data structures. For example:
{
address: {
street: "123 Main St",
city: "New York",
zip: 10001
}
}

 Null: Represents a null or missing value. Example: { middleName: null }.


 Date: Stores date and time values using the ISODate format. For example, { createdAt:
ISODate("2024-06-04T10:00:00Z") }.
 ObjectId: This is a unique 12-byte identifier automatically created for the _id field if no
value is provided. For example: { _id: ObjectId("60c72b2f9e7d9b5f4e3a6d8a") }.
 Binary Data: Used to store binary information such as files or images, represented as
base64 encoded data internally.
 Regular Expression: Stores regex patterns for pattern matching queries. For instance,
{ username: /^admin/i }.
 JavaScript Code: Allows storing JavaScript functions for server-side evaluation, e.g.,
{ validator: function() { return true; } }.
 Timestamp: A special internal data type used mainly for replication and sharding. Example:
{ lastModified: Timestamp(12345, 1) }.
 Min Key / Max Key: Special comparison types where MinKey is less than any other value
and MaxKey is greater than any other value, useful for query comparisons.
********************************************************************************
************
How to Plan NoSQL Data Model
1. Understand Your Application Requirements
 What kind of data will you store?
 What are the main operations (queries) your application will perform?
 How will the data be accessed? (By ID, by range, by secondary attributes?)
 What kind of relationships exist between your data? (One-to-one, one-to-many, many-to-
many)
 What is the expected read/write ratio?

2. Identify Access Patterns First


 NoSQL design is often query-driven.
 List all the queries your application needs to run efficiently.
 Example: "Find all orders by user", "Get user profile by user ID", "Get all products in a
category", etc.

3. Choose the Appropriate NoSQL Database Type


 Document Store (MongoDB, Couchbase): Good for hierarchical or nested data.
 Key-Value Store (Redis, DynamoDB): Simple lookup by key.
 Column-Family Store (Cassandra, HBase): Optimized for large scale and write-heavy
workloads.
 Graph DB (Neo4j): For complex relationships and traversals.

4. Design Schema Based on Queries


 Model your data to optimize the most frequent queries.
 This often means denormalization — storing related data together to avoid joins.
 Embedding documents inside other documents vs. referencing other collections depends on
query needs and data size.

5. Define Collections and Documents


 For a document store, decide what collections you will have and what fields each document
will contain.
 Include nested sub-documents or arrays if it makes sense for your queries.
 Keep documents under the size limit (e.g., MongoDB has 16MB max per document).

6. Consider Data Consistency and Atomicity


 Understand your application's tolerance for eventual consistency.
 Plan how to handle updates on denormalized data (since duplication is common).
 Use transactions if supported and necessary.

7. Plan for Growth and Scalability


 Design for horizontal scaling.
 Avoid joins and complex transactions if possible.
 Use sharding keys (for distributed NoSQL like MongoDB) aligned with your query patterns.

8. Prototype and Test


 Create sample data and test your queries.
 Measure query performance and tweak your model accordingly.
 Refine data model based on feedback and application behavior.

Example: Simple E-commerce NoSQL Data Model (MongoDB)


Collection: users

{
_id: ObjectId,
name: "Alice",
email: "[email protected]",
address: { street, city, zip }
}

Collection: orders
(Embed order items inside the order for quick retrieval)
{
_id: ObjectId,
userId: ObjectId,
orderDate: ISODate,
items: [
{ productId: ObjectId, quantity: 2, price: 50 },
{ productId: ObjectId, quantity: 1, price: 100 }
],
status: "shipped"
}

********************************************************************************
******

Building Mongodb environment


MongoDB Installation on Windows
1. Download the MongoDB Community Server MSI installer from the official MongoDB
website.
2. Run the MSI installer:
a. Choose “Complete” setup.
b. Optionally, install MongoDB as a Windows Service.
c. Select “Install MongoDB Compass” if needed.
3. After installation, MongoDB service usually starts automatically.
Or manually start it via Services app or command prompt:
net start MongoDB
4. To use MongoDB shell, open Command Prompt and type:
Mongosh or you can also launch it from compass client GUI tool

// same process in linux – except you have to download appropriate installation file from
official website

********************************************************************************
*****

Important Contents in a MongoDB Database


1. Collections
 Like tables in SQL.
 Hold groups of related documents.
 Example: users, products, orders

2. Documents
 Like rows in SQL, but stored in BSON (Binary JSON) format.
 Flexible schema: each document can have different fields.
 Example:
{
_id: ObjectId("..."),
name: "Alice",
age: 25
}

3. Indexes
 Improve query performance.
 Similar to indexes in SQL databases.
 Example:
db.users.createIndex({ email: 1 })

4. Validators
 Define rules for documents in a collection.
 Help maintain data quality.
 Example: Ensuring a price field must be a number > 0.

5. Views (optional)
 Read-only, queryable collections based on aggregation pipelines.
 Like virtual tables in SQL.

6. System Collections (internal)


 Special collections used by MongoDB.
 Examples:
o system.indexes – stores index info (pre-3.0)
o system.users – stores authentication info
o system.profile – stores database profiling data if enabled
7. Schema (optional/enforced via validation)
 MongoDB is schema-less, but you can define schema rules using validation and tools like
Mongoose (for Node.js).

**************************************************************************

After fresh installation, you will be connected to default database test. With default user with
no name that is anonymous user. No pwd is required. You can create objects like collections ,
documents etc
You can:
 Create databases
 Create collections
 Insert documents
 Read documents
 Delete and update documents
 Drop collections/databases
MongoDB gives full access by default in no-auth mode. This is very common in
local/development environments.
your data will persist even after you:
 Close the terminal or shell (mongosh)
 Restart your computer
 Reconnect to MongoDB later
How to start and stop Mongodb service in Windows though command prompt
Run cmd as administrator and run this command to start
net start MongoDB
To stop the service
net stop MongoDB
Two ways to access database, one is through mongodb compass which is GUI but its
developers GUI, you cannot perform adminstrative tasks like user creation etc. Another is
mongosh which is CUI. You will get compass by mondodb installation you can also launch
mongosh from compass to perform administrative tasks
*************************************************************************
Collections vs documents in mongodb
Feature Collection Document

A container or group A single data record


What it is
of documents (like a row in SQL)
Equivalent in
Table Row
SQL
JSON-like object
Contains many
Structure (BSON in
documents
MongoDB)

No fixed schema —
Schema-less, fields
Schema can contain varied
can differ per doc
docs

You query a
You read/write/update
Operations collection to get
individual docs
documents

Key Relationship
 A collection is like a folder.
 A document is like a file inside that folder.
***************************************************************************
Create collections in db
MongoDB is schema-less, so you don’t define fields in advance like in SQL.
Instead, you create fields while inserting documents.

1. Creating student collection


db.createCollection("student")
2. Inserting records into student
First record
db.student.insertOne({
student_id: 101,
name: "Alice",
age: 21,
course: "CSE",
address: {
city: "Hyderabad",
pincode: "500001"
},
marks: [85, 92, 78]
})
3. displaying all contents from student collection
db.student.find().pretty()
Output
[
{
_id: ObjectId('684094168927d1bb8750eb67'),
student_id: 101,
name: 'Alice',
age: 21,
course: 'CSE',
address: { city: 'Hyderabad', pincode: '500001' },
marks: [ 85, 92, 78 ]
}
]

4. In the same way inser another record with name rahul and display all records as follows
test> db.student.find().pretty()
[
{
_id: ObjectId('684094168927d1bb8750eb67'),
student_id: 101,
name: 'Alice',
age: 21,
course: 'CSE',
address: { city: 'Hyderabad', pincode: '500001' },
marks: [ 85, 92, 78 ]
},
{
_id: ObjectId('684094df8927d1bb8750eb68'),
student_id: 102,
name: 'Rahul',
age: 22,
course: 'ECE',
address: { city: 'Bangalore', pincode: '560001' },
marks: [ 88, 79, 91 ]
}
]
5. Applying projection – Project only student student names
Query - db.student.find({}, { name: 1, _id: 0 })
Output - [ { name: 'Alice' }, { name: 'Rahul' } ]
Explanation:
 {} → No filter (i.e., select all documents)
 { name: 1 } → Project only the name field (1 means show)
 { _id: 0 } → Hide the _id field (which appears by default)

6. Displaying student names and courses from student collection

Query --- test> db.student.find({}, { student_id: 1, course: 1, _id: 0 })


Output ---
[ { student_id: 101, course: 'CSE' }, { student_id: 102, course: 'ECE' } ]
******************************************************************************
For upcoming concepts, let use the following data to learn Json querying
Note – This is for learning purpose, in exams you need NOT to take such large input file.

Address
id name gender salary Dept
city country
1 Aarav Mehta Male Hyderabad India 78 CSE
2 Diya Sharma Female Mumbai India 65 CSE
3 Kunal Deshmukh Male Hyderabad India 55 CSE
4 Meera Joshi Female Mumbai India 80 CSE
5 Rahul Verma Male Hyderabad India 42 CSE
6 Sneha Kapoor Female Mumbai India 72 ECE
7 Ankit Reddy Male Hyderabad India 35 ECE
8 Pooja Nair Female Mumbai India 60 ECE
9 Rohan Malhotra Male Hyderabad India 47 ECE
10 Shivani Iyer Female Mumbai India 85 ECE
11 Vikram Kumar Male Hyderabad India 53 IT
12 Nikita Shah Female Mumbai India 66 IT
13 Arjun Rao Male Hyderabad India 73 IT
14 Trisha Kulkarni Female Mumbai India 28 IT
15 Neeraj Patil Male Hyderabad India 39 IT
16 Gauri Bhatt Female Mumbai India 76 AIML
17 Rakesh Jain Male Hyderabad India 62 AIML
18 Sanjana Rao Female Mumbai India 50 AIML
19 Dhruv Singh Male Hyderabad India 83 AIML
20 Aisha Khan Female Mumbai India 44 AIML

Lets convert the above table to Json file. The following is the Json file. Name of the collection is
employee and there will be 20 documents in it.

[
{
"id": 1,
"name": "Aarav Mehta",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 78,
"department": "CSE"
},
{
"id": 2,
"name": "Diya Sharma",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 65,
"department": "CSE"
},
{
"id": 3,
"name": "Kunal Deshmukh",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 55,
"department": "CSE"
},
{
"id": 4,
"name": "Meera Joshi",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 80,
"department": "CSE"
},
{
"id": 5,
"name": "Rahul Verma",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 42,
"department": "CSE"
},
{
"id": 6,
"name": "Sneha Kapoor",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 72,
"department": "ECE"
},
{
"id": 7,
"name": "Ankit Reddy",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 35,
"department": "ECE"
},
{
"id": 8,
"name": "Pooja Nair",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 60,
"department": "ECE"
},
{
"id": 9,
"name": "Rohan Malhotra",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 47,
"department": "ECE"
},
{
"id": 10,
"name": "Shivani Iyer",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 85,
"department": "ECE"
},
{
"id": 11,
"name": "Vikram Kumar",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 53,
"department": "IT"
},
{
"id": 12,
"name": "Nikita Shah",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 66,
"department": "IT"
},
{
"id": 13,
"name": "Arjun Rao",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 73,
"department": "IT"
},
{
"id": 14,
"name": "Trisha Kulkarni",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 28,
"department": "IT"
},
{
"id": 15,
"name": "Neeraj Patil",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 39,
"department": "IT"
},
{
"id": 16,
"name": "Gauri Bhatt",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 76,
"department": "AIML"
},
{
"id": 17,
"name": "Rakesh Jain",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 62,
"department": "AIML"
},
{
"id": 18,
"name": "Sanjana Rao",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 50,
"department": "AIML"
},
{
"id": 19,
"name": "Dhruv Singh",
"gender": "Male",
"address": { "city": "Hyderabad", "country": "India" },
"salary": 83,
"department": "AIML"
},
{
"id": 20,
"name": "Aisha Khan",
"gender": "Female",
"address": { "city": "Mumbai", "country": "India" },
"salary": 44,
"department": "AIML"
}
]
Steps to insert above documents in mongodb
1. Copy all entries
2. Create collection as follows db.createCollection("employee")
3. Use db.employee.insertMany( here paste all entries ) and execute

Alright , we are now ready with input file for learning JSON query language.

*******************************************************************************
Necessary commands
1. To show all collections you have created
Show collections
2. To show all documents in collection employee
Db.employee.find()
3. To show only necessary fields you want like name and dept only
db.employee.find({}, { name: 1, department: 1, _id: 0 })
*******************************************************************************
Applying conditions and logical operators and , or in JSON
1. Find employee details who are working for cse dept
db.employee.find({ department: "CSE" })
2. Find employee details who either work for cse or work for ece depts
Note In MongoDB, using a comma , between fields in the query works like a logical AND — it's
shorthand for combining multiple conditions.

You need to use logical operator $or here.


db.employee.find({
$or: [
{ department: "CSE" },
{ department: "ECE" }
]
})
3. find employee details who are working in cse and from hyderabad
db.employee.find({
department: "CSE",
"address.city": "Hyderabad"
})
Note that assignment in Mongodb is just by using :
********************************************************************************
**
Comparision operators in Mongodb
Operator Meaning Example Usage

$eq Equal to { age: { $eq: 25 } }

$ne Not equal to { dept: { $ne: "CSE" } }

$gt Greater than { salary: { $gt: 50000 } }

Greater than or
$gte { marks: { $gte: 40 } }
equal to
$lt Less than { salary: { $lt: 30000 } }
Less than or
$lte { age: { $lte: 60 } }
equal to

$in In a list of values { dept: { $in: ["CSE", "ECE"] } }

Not in a list of
$nin { city: { $nin: ["Delhi", "Pune"] } }
values

$exists Field exists or not { address: { $exists: true } }

********************************************************************************
**
Update and Delete operations
1. Update Vikram kumars salary to 60k who is an employee from IT dept.
db.employees.updateOne(
{ name: "Vikram Kumar", dept: "it" },
{ $set: { sal: 60000 } }
)
Note :- if you dont specify it dept condition then all vikarm kumars from all dept will be changed.

2. Delete employee details whose name is Dhruv Singh and works for AIML dept.
db.employees.deleteOne(
{ name: "Dhruv Singh", dept: "AIML" }
)
Notes:
 deleteOne removes the first matching document. If multiple such records exist and you
want to delete all of them, use deleteMany() instead:
***************************************************************************
Find operation – similar to select in SQL
***********************************************************************
1. find employees who either work for CSE or AIML and have salary > 40
db.employee.find({
$or: [
{ department: "CSE" },
{ department: "AIML" }
],
salary: { $gt: 40 }
})
As an alternative to or in this query , you could also write the query as follows
db.employee.find({
department: { $in: ["CSE", "AIML"] },
salary: { $gt: 40 }
})
Note – in operator is easy but you cannot use where ever you use or operator. in many cases where
you're using $or for the same field, you can replace it with the simpler and more readable $in
operator.

2. find only employee names who either work for CSE or AIML and have salary > 40
db.employee.find(
{
$or: [
{ department: "CSE" },
{ department: "AIML" }
],
salary: { $gt: 40 }
},
{
name: 1,
_id: 0
}
)
**************************************************************************
Aggregation functions and Group by operations in Mongodb
The 5 main aggregate functions in MongoDB (min, max, sum, avg, count) using the aggregation
pipeline ($group):
1. Find the minimum salary across all employees.
db.employee.aggregate([
{
$group: {
_id: null,
minSalary: { $min: "$salary" }
}
}
])
2. Count total number of employees in the organization
db.employee.aggregate([
{
$group: {
_id: 0,
count: { $sum: 1 }
}
}
])
Note that even if you use id or not, it will be displayed as part of result. In compass, though
you make id as 0, it may still visible along with output

3. Find avg sal of all employees


db.employee.aggregate([
{
$group: {
_id: null,
avgSalary: { $avg: "$salary" }
}
}
])
4. Find the maximum salary from only the CSE department

db.employee.aggregate([
{ $match: { department: "CSE" } },
{
$group: {
_id: null,
maxSalary: { $max: "$salary" }
}
}
])
Explanation:
 $match filters documents where department is "CSE".
 $group groups all those documents (using _id: null to group all together) and calculates the
max salary with $max.
5. Count total number of employees who are from cse and having sal >40
db.employee.aggregate([
{
$match: {
department: "CSE",
salary: { $gt: 40 }
}
},
{
$group: {
_id: null,
totalEmployees: { $sum: 1 }
}
}
])
**********************************************************************
Other commands – limit, sort, skip operations in mongodb
Limit :-
In MongoDB, limit is a method used to restrict the number of documents returned by a query.
Syntax:
db.collection.find(query).limit(n)
n is the maximum number of documents to return and query is your filter condition. Beyond limit n,
other documents will be not be returned and not printed.

Sort :-
it's used to order query results based on one or more fields.
db.collection.find(query).sort({ field: order })
eg :- db.students.find().sort({ marks: 1 }) // this is asc
eg :- db.students.find().sort({ marks: -1 }) // this is desc

What Does "Sort by More Than One Column" Mean?


You sort documents based on multiple fields, where:
 The first field decides the primary order.
 The second field is used only when the first field has duplicates (tie-breaker).
Eg :- db.students.find().sort({ marks: -1, name: 1 })
Sorting Logic:
1. First, sort all documents by marks from high to low.
2. If two students have the same marks, break the tie using name alphabetically.

Skip operation -

The skip(n) method in MongoDB is used to skip the first n documents from the query result set and
return the remaining documents.
Syntax:

db.collection.find(query).skip(n)
 n: The number of documents to skip from the beginning of the query results.
 Returns documents starting from the (n + 1)th document onward.
Example:

db.students.find().skip(5)
 Skips the first 5 documents in the result.
 Returns documents starting from the 6th document to the end.
db.collection.find().skip(5).limit(5) -- guess what this does ?
skip(5): skips the first 5 documents → so the result set starts from the 6th document onward.

limit(5): then takes only the first 5 documents from that result.

So if you have 15 documents numbered 1 to 15, this will return documents:

6, 7, 8, 9, 10

***********************************************************************
Creating and managing user accounts in mongodb
In MongoDB, roles define what a user can do. A role is a set of privileges (actions allowed on
resources like collections or databases). MongoDB has both:
1. Built-in roles (commonly used, predefined by MongoDB)
2. Custom roles (user-defined, if more control is needed)
Database-Specific Roles
These roles apply only within a specific database:
Role Description
read Can read all non-system collections. Cannot write.
readWrite Can read and write data (insert, update, delete).
Can perform administrative tasks like indexing,
dbAdmin
schema viewing. No read/write access by default.
Can create and manage users/roles in that
userAdmin
database.
Full control over the database (includes all of the
dbOwner
above).
readWriteAnyDatabase (admin only) Read/write access on all databases.

Backup and Monitoring Roles


Useful for DevOps and support tools:
Role Description
backup Allows backing up the database.
restore Allows restoring backups.
Role Description

clusterMonitor Allows monitoring the cluster, useful for ops dashboards.

There are two powerful roles to manage all databases


1. dbAdminAnyDatabase
2. root.
Note - When you install a fresh copy of mongodb, you will be connected as anonymous user with
out pwd and default to test database with dba roles.

Create a dba user with user name and pwd with dba roles such that he/she can control only
test database
db.createUser({
user: "sateesh",
pwd: "sateesh123",
roles: [
{ role: "dbAdmin", db: "test" },
{ role: "readWrite", db: "test" }
]
})

To login- issue the following command


mongosh -u sateesh -p sateesh123 "test"

*********************************************************************
Connecting node with Node ( with out express )
Steps :-
1. Make sure you already installed node and mongodb.
2. Download and install mongodb driver.
Command ==> npm install mongodb
***********************************************************************
1. Consider the following nodejs program to insert one record in student collection
Steps :-
1. create collection named student in your mongodb
2. run your insertstudent.js file in node. The command is as follows
npm install mongodb
Make sure, your driver package is installed

The following program runs and prints output in console screen.


const { MongoClient } = require("mongodb");

// MongoDB connection URI


const uri = "mongodb://localhost:27017";

// Database and Collection names


const dbName = "test"; // Change this to your database name
const collectionName = "student"; // Your collection name

async function run() {


const client = new MongoClient(uri);

try {
// Connect to MongoDB
await client.connect();
console.log("Connected to MongoDB");

// Get database and collection


const db = client.db(dbName);
const collection = db.collection(collectionName);

// Student record to insert


const student = {
id: 101,
name: "John Doe"
};

// Insert into collection


const result = await collection.insertOne(student);
console.log("Record inserted with _id:", result.insertedId);
} catch (err) {
console.error("Error inserting student:", err);
} finally {
await client.close();
}
}
run();

output
Record inserted with _id: with some id value here
*********************************************************************
2. Nodejs program to take two input parameters say Student id and student name from user
through html form and prints if data is inserted successfully on web page.
Steps
1. Write index.html file
2. write insertstudent.js file
3. run the js file and also Make sure you have already student collection in mongodb. To check
whether insert happened successfully, go to mongodb and retrieve student collection.

(I) index.html file


<!DOCTYPE html>
<html>
<head>
<title>Insert Student Details</title>
</head>
<body>
<h2>Student Details Form</h2>
<form action="/submit" method="POST">
<label for="studentId">Student ID:</label><br>
<input type="text" id="studentId" name="studentId" required><br><br>

<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>

<button type="submit">Submit</button>
</form>
</body>
</html>

2. insertrecordthroughhtmlform.js
const http = require('http');
const fs = require('fs');
const path = require('path');
const { MongoClient } = require('mongodb');
const querystring = require('querystring');

const uri = 'mongodb://localhost:27017';


const client = new MongoClient(uri);
const dbName = 'test';

async function insertStudent(student) {


try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('student');
const result = await collection.insertOne(student);
return result.insertedId;
} catch (err) {
throw err;
}
}
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
// Serve the HTML form
const filePath = path.join(__dirname, 'index.html');
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error loading form');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else if (req.method === 'POST' && req.url === '/submit') {
// Collect POST data
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});

req.on('end', async () => {


const parsed = querystring.parse(body);
const studentId = parsed.studentId;
const name = parsed.name;

if (!studentId || !name) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Student ID and Name are required');
return;
}
try {
const insertedId = await insertStudent({ studentId, name });
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Student details inserted successfully with id: ${insertedId}`);
} catch (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error inserting student details');
}
});
} else {
// Handle 404
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
});

const PORT = 3000;


server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

Output:-
you can see – insert successfully on webpage. Also go to mongodb and check your student
collection.
**********************************************************************

3. Write Nodejs program which takes student id as input parameter through html form and
prints concern student name on web page.

Steps :-
1. create index.html
2. write js file
3. run the js file

(I) index.html file


<!DOCTYPE html>
<html>
<head>
<title>Find Student Name</title>
</head>
<body>
<h2>Find Student Name by ID</h2>
<form action="/find" method="POST">
<label for="studentId">Student ID:</label><br>
<input type="text" id="studentId" name="studentId" required><br><br>

<button type="submit">Submit</button>
</form>
</body>
</html>

(ii). js file.
const http = require('http');
const fs = require('fs');
const path = require('path');
const { MongoClient } = require('mongodb');
const querystring = require('querystring');

const uri = 'mongodb://localhost:27017';


const client = new MongoClient(uri);
const dbName = 'test';

async function findStudentNameById(studentId) {


try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('student');
const student = await collection.findOne({ studentId: studentId });
return student ? student.name : null;
} catch (err) {
throw err;
}
}

const server = http.createServer((req, res) => {


if (req.method === 'GET' && req.url === '/') {
// Serve the HTML form
const filePath = path.join(__dirname, 'index-retrievename.html');
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error loading form');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else if (req.method === 'POST' && req.url === '/find') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});

req.on('end', async () => {


const parsed = querystring.parse(body);
const studentId = parsed.studentId;

if (!studentId) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Student ID is required');
return;
}

try {
const name = await findStudentNameById(studentId);
res.writeHead(200, { 'Content-Type': 'text/plain' });
if (name) {
res.end(`Student Name for ID ${studentId} is: ${name}`);
} else {
res.end(`No student found with ID: ${studentId}`);
}
} catch (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error querying student details');
}
});
} else {
// 404 Not Found
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
});

const PORT = 3000;


server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

Output:- student name


******************************************************************
UNIT – 4
What is the importance of AngularJS
AngularJS (the original version of Angular, released by Google in 2010) was a front-end JavaScript
framework that played a major role in shaping the development of dynamic single-page applications
(SPAs).
Importance of AngularJS
1. Introduced Two-Way Data Binding
 Automatically synchronized data between model and view.
 Saved developers from manually writing DOM manipulation code.
2. Promoted MVC Architecture
 Encouraged a clear separation of concerns:
 Model = data
 View = UI
 Controller = logic
 Made it easier to structure large web applications.
3. Directives & Custom HTML Elements
 Allowed developers to extend HTML with custom behavior (like ng-model, ng-if, ng-
repeat).
 Helped create reusable and modular components.
4. Dependency Injection
 Made code more testable and modular.
 Automatically provided required services to components.
5. Single Page Applications (SPA) Made Easy
 With built-in routing, services, and templating, AngularJS made SPA development
accessible and streamlined.
6. Testability
 AngularJS was built with testing in mind.
 Supported unit testing and end-to-end testing out of the box with tools like Jasmine and
Karma.
7. Open Source and Backed by Google
 Strong community and corporate support made it trustworthy and widely adopted.
************************************************************************
What are the components of Angular
In modern Angular (Angular 2+), the architecture is based on components, and the application is
structured using several key building blocks.
1. Component
 Definition: A component controls a part of the UI (a view).
 Consists of:
 .ts file (TypeScript class with logic)
 .html file (template)
 .css or .scss file (styling)
 Example:
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
export class HelloComponent { }
2. Module
 Definition: A container that groups related components, directives, pipes, and services.
 Every Angular app must have at least one root module (AppModule).
 Decorated with @NgModule.
 Example:
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent]
})
export class AppModule { }
3. Template
 Definition: HTML with Angular-specific syntax that defines the view.
 Can include:
 *ngIf, *ngFor, {{ }} interpolation
 Event binding: (click)="doSomething()"
4. Directive
 Definition: A class that adds behavior to elements in the DOM.
 Types:
 Structural directives (change layout): *ngIf, *ngFor
 Attribute directives (change appearance/behavior): ngClass, ngStyle, or custom
5. Pipe
 Definition: Used to transform data in the template.
 Example: {{ price | currency }}, {{ dateVal | date:'short' }}
 You can also create custom pipes.
6. Service
 Definition: A class used to encapsulate logic like data access, APIs, or business rules.
 Injected using Dependency Injection (DI).
 Example:
ts
CopyEdit
@Injectable({ providedIn: 'root' })
export class UserService {
getUsers() { ... }
}
7. Routing Module
 Defines routes (URLs) and maps them to components.
 Uses RouterModule to configure navigation.

const routes: Routes = [


{ path: 'home', component: HomeComponent },
{ path: '**', redirectTo: 'home' }
];
************************************************************************
Expression in Angular
Expressions in Angular are snippets of code written inside interpolation syntax {{ ... }} or in
Angular directives. They are used to bind data to HTML.
Angular Expressions Syntax
<p>{{ 5 + 5 }}</p>
<p>{{ name }}</p>
<p>{{ getFullName() }}</p>
Angular 2+ (Modern Angular) – Expressions Usage
In Angular 2+, expressions are mainly used in template binding, such as:
1. Interpolation
 Syntax: {{ expression }}
 Purpose: Insert data into HTML.
 Example:
html
CopyEdit
<p>Hello, {{ user.firstName + ' ' + user.lastName }}</p>
2. Property Binding
 Syntax: [property]="expression"
 Example:
html
CopyEdit
<img [src]="user.profilePictureUrl">
3. Event Binding
 Syntax: (event)="expression"
 Example:

<button (click)="logout()">Logout</button>
4. Attribute/Style/Class Binding

<div [class.active]="isActive"></div>
<div [style.color]="isWarning ? 'red' : 'black'"></div>
Features of Angular Expressions
Feature Description
No this keyword You refer to component properties directly (name, not this.name)
No control flow Cannot use if, for, while, etc.
Type-safe Only access component members (properties/methods)
Safe navigation Use ?. to avoid errors with null/undefined: user?.name
Not Allowed in Angular Expressions
 Assignments: a = 10
 Declarations: let, var, const
 Loops or conditionals: if, for
 Accessing global variables like window, document, console (for security reasons)
AngularJS Expressions (for comparison)
In AngularJS (1.x), expressions looked similar:
<p>{{ 1 + 2 }}</p>
<p>{{ user.name }}</p>
But they were evaluated differently (in the scope context, not component class), and you could use
filters like:

{{ price | currency:"USD$" }}
Summary
Use Case Expression Format Example
Interpolation {{ expression }} {{ username }}
Property Binding [property]="expression" [src]="imageUrl"
Event Binding (event)="expression" (click)="save()"
Style/Class [class.xyz]="isTrue" [style.color]="color"

************************************************************************
Data Binding in Angular
Data binding in Angular is a powerful feature that connects the component (TypeScript logic) with
the view (HTML template). It allows data to flow between the UI and the component automatically.
Purpose of Data Binding
 Display dynamic data in the view.
 Respond to user interactions.
 Synchronize data between component and template.
Types of Data Binding in Angular
Angular provides 4 main types of data binding:
1. Interpolation – One-Way (Component ➡️ View)
 Displays data from the component in the template.
 Syntax: {{ expression }}
 Example:
tml
CopyEdit
<p>Hello, {{ username }}</p>
2. Property Binding – One-Way (Component ➡️ View)
 Binds DOM properties to component values.
 Syntax: [property]="expression"
 Example:
<img [src]="user.profilePictureUrl">
<button [disabled]="isLoading">Submit</button>
3. Event Binding – One-Way (View ➡️ Component)
 Sends user actions (clicks, typing, etc.) to the component.
 Syntax: (event)="handlerFunction()"
 Example:

<button (click)="logout()">Logout</button>
4. Two-Way Binding – (Component ⬌ View)
 Syncs data both ways using [(ngModel)].
 Requires importing FormsModule.
 Syntax: [(ngModel)]="property"
 Example:

<input [(ngModel)]="user.name">
*************************************************************************
Built in Directive vs Custom Directives
Types of Directives in Angular
Angular provides two categories:
1. Built-in Directives
These are provided by Angular itself.
2. Custom Directives
These are user-defined and extend or customize behavior.
1. Built-in Directives
There are three types of built-in directives:
A. Structural Directives
Change the structure/layout of the DOM (add/remove elements).
Directive Purpose
Conditionally include or remove an
*ngIf
element
*ngFor Repeat a block for each item in a list
*ngSwitch, *ngSwitchCase, *ngSwitchDefault Conditional multi-branch rendering
Example:
<div *ngIf="isLoggedIn">Welcome!</div>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
B. Attribute Directives
Change the appearance or behavior of an element.
Directive Purpose
ngClass Dynamically set CSS classes
ngStyle Dynamically set styles
ngModel Two-way data binding to form inputs (in FormsModule)
Example:
html
CopyEdit
<p [ngClass]="{active: isActive}">Status</p>
<p [ngStyle]="{'color': isError ? 'red' : 'green'}">Message</p>
<input [(ngModel)]="user.name">
C. Component Directives
Technically, every component is a directive with a template.
2. Custom Directives
You can build your own directives for reusable logic or custom DOM behavior.
Example: Custom Attribute Directive
Step 1: Create Directive
bash
CopyEdit
ng generate directive highlight
Step 2: Code – highlight.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]' // use like an attribute
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight('');
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
Step 3: Use in Template
<p appHighlight>Hover over this text to highlight it!</p>
Summary Table
Type Examples Purpose
Structural *ngIf, *ngFor, *ngSwitch Add/remove DOM elements
Attribute ngClass, ngStyle, ngModel Change look/behavior
Custom appHighlight, appAutoFocus Your own DOM behavior

*************************************************************************
MEAN STACK – ENVIRONMENT CREATION
The below 10 steps are common for both MERN and MEAN stack. Later steps differentiate
with react and angular
1. Create fullstack directory and go to that directory
2. Go to that directory and install node and npm
3. Create backend directory (all your server app files will be here) and run this command
npm init -y
4. In the same directory install express using this command npm install express
5. In the same directory install mongodb from official website and mongodb driver using npm
command.
6. Create server.js file in same directory and copy the below content to it. This is your actually http
server. You may have to add paths in it when ever you wanted to add server side applications and
access them through http request that is you need to define route.
const express = require('express');
const app = express();
const PORT = 3000;
// Define a basic route
app.get('/', (req, res) => {
res.send('Hello, world!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
7. Check whether you installed node correctly or not. Type the following command
node -v
8. check whether your nodes server is running correctly by starting it.
node server.js
9. check whether your mongodb is installed correctly. Start its service by using following command
in linux --> sudo systemctl start mongod
in windows -- >net start MongoDB or goto services and start manually
To connect to mongodb, run command mongosh ( mongosh )
10. check whether express is installed correctly
npm list express
If above 10 steps are correct then it means you have node, express and mongodb perfectly in your
machine.
Installing ANGULAR– Above 10 steps are common. Below are additional steps for react.
1. Create Frontend-angular-client folder, go to that folder and Install react.
npm install -g @angular/cli (cli-command line interface)
2. To check if installation happened successfully – run this command
ng version
3. To create angular app folder, run this command
ng new my-angular-app
3. To start angulars – Development server , run this command
ng serve
go to localhost:4200 to check your angular development server is up and running.
**********************************************************************
Important -- Creating routing in Angular
1. Generate an application
The following command uses the Angular CLI to generate a basic Angular application with
application routes. The application name in the following example is routing-app.
ng new routing-app
2. Adding components for routing
To use the Angular router, an application needs to have at least two components so that it can
navigate from one to the other. To create a component using the CLI, enter the following at the
command line where first is the name of your component:
ng generate component first
Repeat this step for a second component but give it a different name. Here, the new name is second.
ng generate component second
The CLI automatically appends Component, so if you were to write first-component, your
component would be FirstComponentComponent.
3. Importing your new components in routes.ts file in app folder
To use your new components, import them into app.routes.ts at the top of the file, as follows:
import {FirstComponent} from './first/first.component';
import {SecondComponent} from './second/second.component';
Also update routes in same file
content_copyconst routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
];
4. Add your routes to your application in appcomponent.html
Now that you have defined your routes, add them to your application. First, add links to the two
components. Assign the anchor tag that you want to add the route to the routerLink attribute.
Set the value of the attribute to the component to show when a user clicks on each link. Next,
update your component template to include <router-outlet>. This element informs Angular to
update the application view with the component for the selected route.
<h1>Angular Router App</h1>
<nav>
<ul>
<li><a routerLink="/first-component" routerLinkActive="active"
ariaCurrentWhenActive="page">First Component</a></li>
<li><a routerLink="/second-component" routerLinkActive="active"
ariaCurrentWhenActive="page">Second Component</a></li>
</ul>
</nav>
<!-- The routed views render in the <router-outlet>-->
<router-outlet></router-outlet>
Now, you can access first and second components using urls
**********************************************************************
UNIT-V
REACT
*********************************************************************
What is the importance of React
React is a JavaScript library for building user interfaces, primarily maintained by Facebook. It is
widely used in modern web development for building dynamic, responsive, and high-performance
web applications. Here’s why React is important:
Importance of React

1. Component-Based Architecture
 React breaks the UI into reusable components.
 Each component manages its own state and logic, which leads to modular, maintainable
code.
 Encourages reusability, reducing development time.
2. Virtual DOM for Better Performance
 React uses a Virtual DOM to track changes in the UI.
 Instead of reloading the whole DOM, React efficiently updates only the changed parts,
improving performance.
3. Declarative UI
 React allows developers to describe what the UI should look like for a given state.
 Easier to debug and understand compared to imperative code.
4. Strong Community and Ecosystem
 Massive support from Facebook, open-source contributors, and developers.
 Rich ecosystem: tools like Redux, React Router, Next.js, etc., are widely used with React.
5. Unidirectional Data Flow
 Data flows in a single direction (from parent to child), making the app easier to reason
about and debug.
6. JSX – JavaScript + HTML
 React uses JSX, which allows writing HTML inside JavaScript.
 Makes code more readable and expressive.
7. Cross-Platform Capabilities
 With tools like React Native, you can build mobile apps for iOS and Android using the
same React principles.
8. SEO-Friendly
 React (especially when used with server-side rendering tools like Next.js) improves SEO
compared to traditional JavaScript-heavy frameworks.
Use Cases
 Single Page Applications (SPAs)
 Dashboards
 E-commerce websites
 Social media platforms
 Progressive Web Apps (PWAs)
******************************************************************
What is Virtual DOM
The Virtual DOM (V-DOM) is a core concept in React (and some other frameworks), designed to
improve the performance and efficiency of web applications by minimizing direct manipulations to
the real DOM.
DOM (Document Object Model) is a programming interface provided by browsers. It represents
the structure of your webpage as a tree of objects (called nodes), where each element in HTML
becomes a node.
Problem with Real DOM:
 The real DOM is slow to update, especially when many changes are made.
 Every DOM update triggers re-rendering, recalculating styles, reflowing layout, and
repainting the screen.
 This slows down performance in complex, dynamic apps.
What is Virtual DOM?

Definition:
The Virtual DOM is an in-memory, lightweight JavaScript representation of the real DOM. It
allows React to perform updates more efficiently.
How Virtual DOM Works (Step-by-Step):
1. Initial Render:
 React creates a Virtual DOM tree based on your components (JSX code).
 It then renders the actual DOM for the first time.
2. State or Props Change:
 When something changes (e.g., user input), React:
 Creates a new Virtual DOM.
 Compares it with the previous Virtual DOM (this is called diffing).
3. Diffing Algorithm:
 React identifies the minimal set of changes needed.
 It determines which elements actually changed and need to be updated in the real
DOM.
4. Efficient Update:
 React updates only the changed parts in the real DOM (not the whole tree).
 This makes the update fast and efficient.

Real DOM vs Virtual DOM – A Comparison


Feature Real DOM Virtual DOM
Update speed Slow Fast (batch updates, selective rendering)
Re-rendering cost High Low
Abstraction Browser-provided React’s internal JS object
Performance Lower for frequent updates Optimized for frequent UI changes

******************************************************************
What are important files or folder structure of React
Key Files Explained
Application/
├── UI Elements → Reusable building blocks (buttons, inputs, cards)
├── Screens/Views → User-facing pages or route-based layouts
├── State Management → Data flow, global state, shared context
├── Data Layer → External communication (APIs, services, storage)
├── Behavior Logic → Business rules, custom logic, side effects
├── Utilities → Helpers, constants, formatters
├── Static Resources → Media, styles, themes, icons
├── Entry & Bootstrapping → App startup logic, mounting, configuration
File/Folder Purpose
public/index.html Main HTML file where React mounts (<div id="root">)
src/index.js Entry point, renders <App /> using ReactDOM
src/App.jsx Root React component
components/ Holds small, reusable components
pages/ Components mapped to routes (like Home, About)
services/ Functions for making API calls (e.g., using axios)
context/ For global state using React Context API
hooks/ Custom hooks like useFetch, useToggle
assets/ Static files like images, logos, fonts
styles/ CSS or SASS files, sometimes organized per component

******************************************************************
MERN – STACK – CREATING ENVIRONMENT
1. Create fullstack directory and go to that directory
2. Go to that directory and install node and npm
3. Create backend directory (all your server app files will be here) and run this command
npm init -y
4. In the same directory install express using this command npm install express
5. In the same directory install mongodb from official website and mongodb driver using npm
command.
6. Create server.js file in same directory and copy the below content to it. This is your actually http
server. You may have to add paths in it when ever you wanted to add server side applications and
access them through http request that is you need to define route.
const express = require('express');
const app = express();
const PORT = 3000;
// Define a basic route
app.get('/', (req, res) => {
res.send('Hello, world!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
run this server.js using node command. -- node server.js
7. Check whether you installed node correctly or not. Type the following command
node -v
8. check whether your nodes server is running correctly by starting it.
node server.js
Note:- in the same folder, you need to install mongodb driver and packages
npm install mongod -- driver
npm install mongodb -- packages
9. check whether your mongodb is installed correctly. Start its service by using following command
in linux --> sudo systemctl start mongod
in windows -- >net start MongoDB or goto services and start manually
To connect to mongodb, run command mongosh ( mongosh )

10. check whether express is installed correctly


npm list express
If above 10 steps are correct then it means you have node, express and mongodb perfectly in your
machine.

Installing REACT– Above 10 steps are common. Below are additional steps for react.
Now, come back to fullstack folder and create react-client folder and go to that folder.
1. Create Frontend-react-client folder, go to that folder and Install react.
npx create-react-app . ( “.” means use currect directory , i.e react-client folder)
2. Check wheter you have installed react perfectly by running this command
npm start
You can see that your app.js will execute automatically by this command and displayed the result in
localhost:3000 . This will start your client side development server. Dont confuse it with node
server. This is just temporary client server runs in clients memory.
Important – How react router works and how to route our own app called as myapp2
1. Inside same folder, install React Router. This will enable you to create more client app files and
route them through developement server.
npm install react-router-dom
2. To check whether you have installed react-router-dom perfectly then you create one app called
myapp2.js with following code
import React from 'react';
function Myapp2() {
return (
<div>
<h1>Hello, this is my own page in myapp2</h1>
</div>
);
}
export default Myapp2;
Now, add copy the following code in app.js. In which we address how to reach myapp2.
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Myapp2 from './myapp2';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<h1>Home Page</h1>} />
<Route path="/myapp2" element={<Myapp2 />} />
</Routes>
</Router>
);
}
export default App;
Now open localhost:3000/myapp2 , you should see Hello, this is my own page in myapp2 on the
web page.
Important Note :- Since you have reacts developments server and nodes backend server in same
machine, by default both take 3000 as default port. Change one of them, the best thing to change is
nodes servers port. Open server.js from your backend folder and change port value 3000 to 5000.
***********************************************************************
Write an application to insert student details in mongodb database using react, express and node.
1. Create reactjs file called Myreactdbform.js
import React, { useState } from 'react';
function Myreactdbform() {
const [studentId, setStudentId] = useState('');
const [studentName, setStudentName] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch('http://localhost:5000/api/students', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ studentId, studentName }),
});
const result = await response.json();
if (result.success) {
setMessage('Student details successfully inserted');
setStudentId('');
setStudentName('');
} else {
setMessage('Insertion failed');
}
};
return (
<div style={{ padding: '20px' }}>
<h2>Enter Student Details</h2>
<form onSubmit={handleSubmit}>
<label>Student ID:</label>
<input
type="text"
value={studentId}
onChange={(e) => setStudentId(e.target.value)}
required
/><br /><br />
<label>Student Name:</label>
<input
type="text"
value={studentName}
onChange={(e) => setStudentName(e.target.value)}
required
/><br /><br />
<button type="submit">Submit</button>
</form>
<p>{message}</p>
</div>
);
}
export default Myreactdbform;

2. Update your app.js file as below


import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Myapp2 from './myapp2';
import Myreactdbform from './Myreactdbform';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<h1>Home Page-- REACT- Development Server- Client
Side</h1>} />
<Route path="/myapp2" element={<Myapp2 />} />
<Route path="/Myreactdbform" element={<Myreactdbform />} />
</Routes>
</Router>
);
}
export default App;

3. Create expressnodejs file in backend folder


const express = require('express');
const { MongoClient } = require('mongodb');
const router = express.Router();
const mongoUrl = 'mongodb://localhost:27017';
const dbName = 'test';
router.post('/api/students', async (req, res) => {
const { studentId, studentName } = req.body;
if (!studentId || !studentName) {
return res.status(400).json({ success: false, message: 'Missing fields' });
}
try {
const client = await MongoClient.connect(mongoUrl, { useUnifiedTopology: true });
const db = client.db(dbName);
const collection = db.collection('student');
await collection.insertOne({ studentId, studentName });
client.close();
res.json({ success: true });
} catch (err) {
console.error(err);
res.status(500).json({ success: false });
}
});
module.exports = router;
4. Install Cross-Origin Resource Sharing (CORS)
npm install cors
5. update your server.js file as follows

const express = require('express');


const app = express();
const submitStudent = require('./submitStudent');
const cors = require('cors');
const PORT = 5000;
// Define a basic route
app.get('/', (req, res) => {
res.send('Hello, world!--Node server is successfully running');
});
app.use(cors()); // Enable CORS (must be before routes)
app.use(express.json());
app.use('/', submitStudent);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

Run mongodb, server.js and react development server.. run your reactapp , you can successfully
insert values in mongodb.

************************************************************************

You might also like