0% found this document useful (0 votes)
35 views74 pages

Full Stack Development Lab

This document provides a comprehensive guide on installing Visual Studio Code and Node.js on Windows, detailing step-by-step procedures for both installations. It also includes examples of basic Node.js applications, Express.js routing, HTTP methods, middleware, and templating, along with code snippets for practical implementation. Additionally, it covers handling form data and demonstrates how to create a simple server using Express.js.

Uploaded by

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

Full Stack Development Lab

This document provides a comprehensive guide on installing Visual Studio Code and Node.js on Windows, detailing step-by-step procedures for both installations. It also includes examples of basic Node.js applications, Express.js routing, HTTP methods, middleware, and templating, along with code snippets for practical implementation. Additionally, it covers handling form data and demonstrates how to create a simple server using Express.js.

Uploaded by

bonduanitha384
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 74

FULL STACK DEVELOPMENT

LAB-2
 HOW TO INSTALL VISUAL STUDIO CODE ON
WINDOWS?
→ Steps to install visual studio code on windows :

STEP: 1 Visit the official website VISUAL STUDIO CODE and using any web
browser like GOOGLE CHROME and MICROSOFT EDGE, etc..,

STEP:2 Press the “DOWNLOAD FOR WINDOWS” button on the website to start
the download of the visual studio code application.

STEP: 3 when the download finishes, then the VISUAL STUDIO CODE ICON
appears in the downloads folder.

STEP: 4 Click on the installer icon to start the installation process of the visual
studio code.

STEP: 5 After the installer opens, it will ask you to accept the terms and conditions
of the visual studio code. Click on I accept the agreement and then click the next
button.

STEP:6
Choose the location data for running the visual studio code. It will then ask you to
browse the location. Then click the next button.

STEP:7
Then it will ask to begin the installation setup. Click on the install button.

STEP:8
After clicking on Install, it will take about 1 minute to install the Visual Studio Code
on your device.

STEP:9
After the Installation setup for Visual Studio Code is finished, it will show a
window like this below. Tick the "Launch Visual Studio Code" checkbox and then
click Next.

STEP: 10 After the previous step, the Visual Studio Code window opens
successfully. Now you can create a new file in the Visual Studio Code window and
choose a language of yours to begin your programming journey
 INSTALLATION PROCESS ON NODE.JS :
How to Install Node.js on Windows
Installing Node.js on Windows is a straightforward process, but it's essential to follow
the right steps to ensure smooth setup and proper functioning of Node Package
Manager (NPM), which is crucial for managing dependencies and packages. This
guide will walk you through the official site, NVM, Windows Subsystem, and
Package Manager for Windows 7, 8, 10, and 11.
Method 1: Use the Official Website
Follow these steps to install the Node.js on your Windows:

Step 1: Download Node.js Installer

 Visit the official Node.js websiteto download the Node.js


Download the Windows Installer based on your system architecture (32-bit or 64-
bit)

Step 2: Run the Installer

 Locate the downloaded .msi file and double-click to run it.


 Follow the prompts in the setup wizard, accept the license agreement, and use the
default settings for installation.
 Select features to install such as:
 npm: to manage packages for Node.js applications
o Native modules: for building native C++ modules

→ Wait for "Finish" to complete the setup.


Step 3:
Verify the Installation
Open Command Prompt or PowerShell > Check the installed versions by running
these commands:
 Type node -v and press Enter to check the Node.js version.
 Type npm -v and press Enter to check the npm version.
 Both commands should return version numbers, confirming successful
installation.

C:\Users\Admin> node -v

Method 2: Use Windows Subsystem (WSL)

Windows Subsystem for Linux (WSL) is a great option for those who prefer
a Linux environment. You can run a Linux distribution on your Windows machine
and use Linux tools like apt-get for installation.

Step 1: Open PowerShell

Open PowerShell as Administrator and run the following command:

This will install the WSL feature and the default Ubuntu distribution.
Step 2: Set up a Linux Distribution
Once WSL is installed, launch the Ubuntu (or another Linux distro) app from
the Start Menu and set up your Linux distribution by creating a user and password.

Step 3: Install Node.js and NPM via apt

Open the WSL terminal (Ubuntu or your chosen distribution) and update your
package list:
sudo apt update

Once the update is done, Install Node.js using the following command:
sudo apt install nodejs
sudo apt install npm

Step 4: Verify Node.js and NPM Installation

Once the installation is complete, verify the installation by entering the following
command:
node -v
npm -v
Method 4: Install Node.js & NPM using WPM
Windows 10 and 11 users can use winget, the Windows Package Manager, to easily
install Node.js.
→ Verify Installation for Node.js and NPM
After installation, check if Node.js is installed correctly:
node -v
npm -v

✅ 1. Basic Console Output (Node.js):


// hello.js
console.log("Hello, World!");
 How to run:
1. Save as hello.js.
2. In terminal/cmd, run: node hello.js
3. You’ll see: Hello, World!

 2. Hello World HTTP Server:


// server.js
const http = require("http");

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


res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello, World!\n");
});

server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
// server.js
const http = require("http");
 How to run:
1. Save as server.js.
2. Run: node server.js
3. Then open a browser at http://localhost:3000 and you see "Hello, World!".

 Hello World with Express.js


If you want a cleaner server using the Express framework:

// express-hello.js

const express = require("express");

const app = express();

const port = 3000;

app.get("/", (req, res) => {

res.send("Hello, World!");

});

app.listen(port, () => {

console.log(`Example app listening at http://localhost:${port}`);

});

1. Install Express first:

npm init -y
npm install express
2.Then run: node express-hello.js

3.You’ll see: Example app listening at http://localhost:3000


EXPERIMENTS:
1. Express JS – Routing, HTTP Methods, Middleware.

1. Routing in Express.js

Routing defines how your Express app responds to client requests for specific
endpoints (paths and methods).

Basic Route Example:

const express = require("express");

const app = express();

// Route for GET request to "/"

app.get("/", (req, res) => {

res.send("Home Page");

});

// Route for GET request to "/about"

app.get("/about", (req, res) => {

res.send("About Page");

});
2. HTTP Methods in Express.js

Express supports all common HTTP methods used in RESTful APIs:

Method Purpose Example


GET Read data app.get("/items", ...)
POST Create new data app.post("/items", ...)
PUT Update entire resource app.put("/items/:id", ...)
PATCH Update part of resource app.patch("/items/:id", ...)
DELETE Delete data app.delete("/items/:id", ...)

Example with Multiple Methods:

app.post("/submit", (req, res) => {

res.send("Form submitted");

});

app.put("/update/:id", (req, res) => {

res.send(`Update item ${req.params.id}`);

});

app.delete("/delete/:id", (req, res) => {

res.send(`Deleted item ${req.params.id}`);

});

3. Middleware in Express.js

Middleware are functions that run during the lifecycle of a request to the server.
They can: 1. Modify request/response objects

2.End the request-response cycle

3. Call the next middleware in the stack

 Basic Middleware Example:


const express = require("express");

const app = express();

// Global middleware

app.use((req, res, next) => {

console.log(`${req.method} ${req.url}`);

next(); // Move to next middleware or route handler

});

a) Write a program to define a route, Handling Routes, Route Parameters,


Query
Parameters and URL building

const express = require('express');


const app = express();
const port = 3000;

// Middleware for parsing JSON bodies


app.use(express.json());

// 1. Defining Basic Routes


app.get('/', (req, res) => {
res.send('Hello, this is the homepage!');
});

app.post('/items', (req, res) => {


res.send('Item created');
});

// 2. Route Parameters
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});

// 3. Query Parameters
app.get('/search', (req, res) => {
const searchTerm = req.query.q;
res.send(`Search term: ${searchTerm}`);
});

// 4. URL Building (Example using template literals)


app.get('/profile/:username', (req, res) => {
const username = req.params.username;
const profileUrl = `/users/${username}`;
res.send(`Profile URL: ${profileUrl}`);
});

// 5. Handling Multiple HTTP Methods on the same route


app.route('/resource')
.get((req, res) => {
res.send('GET request to /resource');
})
.post((req, res) => {
res.send('POST request to /resource');
});

app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});

OUTPUTS:

 Server running at http://localhost:3000

1. Home Route: http://localhost:3000/


Response: Welcome to the Home Page

2.Route with Route Parameter: http://localhost:3000/user/123


Response: User ID from route: 123

3.Route with Query Parameters: http://localhost:3000/search?


q=nodejs&sort=asc
Response: Search Query: nodejs, Sort By: asc

4.URL Builder Route: http://localhost:3000/build-url


Response: Built URL: /user/42?sort=desc&limit=10

5.Invalid Route (Fallback 404): http://localhost:3000/unknown


Response: Page not found

b) Write a program to accept data, retrieve data and delete a


specified resource using http methods

npm install express body-parser

· Accept data using the POST method.

· Retrieve data using the GET method.


· Delete a resource using the DELETE method.

Folder structure: app.js (or) package.json

// server.js
const express = require('express');
const app = express();
app.use(express.json()); // parse JSON bodies

let items = []; // in-memory store


let nextId = 1;

// Create (accept data via POST)


app.post('/items', (req, res) => {
const { name } = req.body;
if (!name) return res.status(400).json({ error: 'Name is required' });

const item = { id: nextId++, name };


items.push(item);
res.status(201).json(item);
});

// Retrieve all items (GET)


app.get('/items', (req, res) => {
res.json(items);
});

// Retrieve specific item by id


app.get('/items/:id', (req, res) => {
const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).json({ error: 'Item not found' });
res.json(item);
});

// Delete a specified item


app.delete('/items/:id', (req, res) => {
const idx = items.findIndex(i => i.id === parseInt(req.params.id));
if (idx === -1) return res.status(404).json({ error: 'Item not found' });

const deleted = items.splice(idx, 1);


res.json({ message: 'Item deleted', item: deleted[0] });
});

// Start the server


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));

Output:
1. POST /items — Add data

Request:

http
CopyEdit
POST /items HTTP/1.1
Content-Type: application/json

{
"name": "Laptop"
}

Response:

json
CopyEdit
{
"id": 1,
"name": "Laptop"}

Status Code: 201 Created

2. POST /items — Add another item

json
CopyEdit
{
"name": "Phone"}

Response:

json
CopyEdit
{
"id": 2,
"name": "Phone"}

C) Write a program to show the working of middleware


const express = require('express');
const app = express();
const port = 3000;

// Middleware 1: Request Logger


// This middleware logs the HTTP method and URL of every incoming request.
app.use((req, res, next) => {
console.log([${new Date().toISOString()}] ${req.method} ${req.url});
next();
});

// Middleware 2: Authentication check


app.use('/secure', (req, res, next) => {
if (req.headers['x-auth-token'] === 'mysecrettoken') {
console.log('Authentication successful for /secure route.');
next();
} else {
console.log('Authentication failed for /secure route.');
res.status(401).send('Unauthorized: Missing or invalid authentication token.');
}
});

// Route Handler for a root path


app.get('/', (req, res) => {
res.send('Hello, this is the home route!');
});

// Route Handler for a secure path


app.get('/secure', (req, res) => {
res.send('Welcome to the secure route!');
});

// Start the server


app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

OUTPUT :
Visit the home page: Hello, this is the main route!
2. Express JS – Templating, Form Data

Express.js facilitates both templating for dynamic HTML generation and handling
form data submitted from clients.

1. Templating in Express.js:

Purpose : Templating engines allow embedding dynamic data and logic within static
HTML structures, generating personalized content for users.

Common engines: Popular choices include Ejs (Embedded JavaScript), Pug (formely
jade), and Handlebars.

Setup:
1. Install the desired templating engine (e.g., npm install ejs).
2. Configure Express to use the engine: app.set('view engine', 'ejs');
3. Specify the directory where your template files are located: app.set('views',
path.join(__dirname, 'views'));

Rendering: Use res.render() to render a template and pass data to it:

app.get('/', (req, res) => {


res.render('index', { title: 'My Page', message: 'Welcome!' });
});

In index.ejs, you can access the data using embedded JavaScript:


<h1><%= title %></h1>
<p><%= message %></p>

2. Handling form Data in Express.js:

 Parsing Middleware: Express.js requires middleware to parse incoming form


data.
express.urlencoded( ): For URL-encoded data (e.g., standard HTML form
submissions with Content-Type: application/x-www-form-urlencoded).

app.use(express.urlencoded({ extended: true }));

 express.json(): For JSON data (e.g., API requests with Content-Type:


application/json).
app.use(express.json());

 multer: For multipart/form-data (primarily used for file uploads).

const multer = require('multer');


const upload = multer({ dest: 'uploads/' }); // Specify upload directory
app.post('/upload', upload.single('myFile'), (req, res) => {
// Access file details in req.file and text fields in req.body
});

 Accessing Data: Once parsed by the appropriate middleware, form data is


accessible in the req.body object for POST requests, or in req.query for GET
requests.

app.post('/submit-form', (req, res) => {


const username = req.body.username;
const password = req.body.password;
// Process the data
});

a) Write a program using templating engine

npm install express ejs body-parser

const express = require(‘express’);


const path = require(‘path’); // Required to join directory paths
const app = express();
const PORT = 3000;

// Set EJS as the view engine


app.set(‘view engine’, ‘ejs’);

// Specify the directory where your EJS templates (views) are located
app.set(‘views’, path.join(__dirname, ‘views’));

// Define a route to render the EJS template


app.get(‘/ ‘ , (req, res) => {
// Data to be passed to the template
const UserData = {
name: ‘John Doe’,
age: 30,
hobbies: [‘coding’, ‘reading’, ‘hiking’]
});
// Render the ‘index.ejs’ template and pass the UserData
res.render(‘index’, { data: userData });
});

// Start the server


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

Output:
User Information
 coding
 reading
 hiking

app.set(‘view engine’, ‘ejs’); app.set(‘views’,__dirname + ‘/views’);

b) Write a program to work with form data.

const express = require(‘express’);


const app = express();
const port = 3000;

// Middleware to parse form data


app.use(express.urlencoded({ extended: true}));

// Serve HTML form


app.get(‘/’, (req, res) => {
res.send(‘
<h2>Form Example</h2>
<form action=”/submit” method=”post”>
Name: <input type=”text” name=”name” /><br/>
Email: <input type=”email” name=”email” /><br/>
<button> type=”submit”>Submit</button>
</form>
‘):
});

// Handle form submission


app.post(‘/submit’, (req, res) => {
const { name,email } = req.body;
res.send(‘Received data: <br>Name: ${name} <br>Email : ${email}’);
});

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

OUTPUT:
Form Example
Name: [__________]
Email: [_________]
[Submit]
After filling and submitting:
Received data:
Name: Disney
Email: [email protected]

3. Express JS – Cookies, Sessions, Authentication


Implementing cookie-based session authentication in an Express.js application
involves using the express-session middleware to manage sessions and cookie-parser
to handle cookies.

Installation: Install the necessary packages:

npm install express express-session cookie-parser

Explanation:
express-session:
This middleware creates and manages sessions. It assigns a unique session ID to each
user and stores session data on the server (or a chosen session store).
cookie-parser:
This middleware parses incoming request cookies, making them accessible via
req.cookies.
Session ID Cookie:
express-session automatically sets a session ID cookie (typically named connect.sid)
in the user's browser, which is used to identify the session on subsequent requests.
secret:
A crucial security measure, used to sign the session ID cookie, preventing tampering.
secure and httpOnly cookie options:
Enhance security by ensuring the cookie is only sent over HTTPS and cannot be
accessed by client-side JavaScript, respectively.
req.session:
This object is provided by express-session and allows you to store and retrieve
session-specific data.

isAuthenticated middleware:
A common pattern to protect routes, ensuring only authenticated users can access
them.
req.session.destroy():
Used to end a session and remove its data from the session store.
res.clearCookie():
Removes the session ID cookie from the client's browser.

a) Write a program for session management using cookies and


sessions.

const express = require('express');


const session = require('express-session');
const cookieParser = require('cookie-parser');

const app = express();


const PORT = 3000;

// Middleware
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));

// Configure session
app.use(session({
secret: 'mysecretkey123', // Secret for signing the session ID cookie
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 } // Session expires after 1 minute
}));

// Homepage
app.get('/', (req, res) => {
if (req.session.username) {
res.send(`<h2>Welcome back, ${req.session.username}!</h2>
<a href="/logout">Logout</a>`);
} else {
res.send(`<form method="POST" action="/login">
<input type="text" name="username" placeholder="Enter username"
required />
<button type="submit">Login</button>
</form>`);
}
});

// Login handler
app.post('/login', (req, res) => {
const username = req.body.username;
req.session.username = username;
res.cookie('user', username); // Set a cookie
res.redirect('/');
});

// Logout handler
app.get('/logout', (req, res) => {
res.clearCookie('user'); // Clear cookie
req.session.destroy(); // Destroy session
res.redirect('/');
});

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

OUTPUT:
Enter username: cartoon
login
Welcome back, cartoon
Logout

b) Write a program for user authentication.

npm install express express-session bcrypt

 Express - web framework


 bcrypt - to hash passwords
 express-session - to manage sessions
 A dummy in-memory user database

const express = require(‘express’);


const session = require(‘express-session’);
const bcrypt = require(‘bcrypt’);
const hash = bcrypt.hashSync(‘1234, 10’);

const app = express();


const PORT = 3000;

// Dummy user database (in-memory)


const users = [
{
Id: 1, username: ‘cartoon’, passwordhash = hash;
}
];

// Hash the user’s password once (in real apps, this would be stored already)
bcrypt.hash(‘1234’, 10, (err, hash) => {
users[0].passwordhash = hash;
});

// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: ‘secretkey123’,
resave: false,
saveunitialized: false
}));

/ Routes
app.get('/', (req, res) => {
if (req.session.userId) {
res.send(<h2>Welcome, ${req.session.username}!</h2><a
href="/logout">Logout</a>);
} else {
res.send(`<form method="POST" action="/login">
<input name="username" placeholder="Username" required />
<input name="password" type="password" placeholder="Password"
required />
<button type="submit">Login</button>
</form>`);
}
});

app.post('/login', (req, res) => {


const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user) {
return res.send('Invalid username or password');
}

bcrypt.compare(password, user.passwordHash, (err, result) => {


if (result) {
req.session.userId = user.id;
req.session.username = user.username;
res.redirect('/');
} else {
res.send('Invalid username or password');
}
});
});

app.get('/logout', (req, res) => {


req.session.destroy();
res.redirect('/');
});

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

OUTPUT:
Username:
Password:
Login

MongoDB installation process:


Step: 1 Download and install MongoDB
1) Go to this official website: https://www.mongodb.com/try/download/community
2) Choose the following: version: latest (eg:- 6.0+)
Platform: Windows
Package: .msi (Windows Installer)
3) Click Download and run the installer
4) During installation: select complete setup
Check the box “Install MongoDB as a service”

Step: 2 Add MongoDB to system path


1) Go to: Start Menu -> search -> “Environment variables”->open “Edit system
environment variables”
2) Click Environment variables button
3) Under System variables, find path, click Edit
4) Click new, then paste this path: C:\program Files\MongoDB\Server\8.0\bin
5) Click OK on all windows.

Step 3: Open new terminal


1) Now open a new powershell (or) CMD window and run: mongod
2) You see: waiting for connections on port 27017.

Step 4: we have to select run service as network service user


1) Do not select “ run service as a local (or) domain user”- it needs extra setup
(username / password)
2) Your screen should look like this: “ Install MongoDB as a service”- checked
“Run service as Network service user” - selected
Service name: MongoDB
Data directory: leave it as it is
Log directory: leave it as it is
3) Now just click next and continue the installation
4) Once installation is complete, MongoDB will automatically run in the background
every time your computer starts.
Step 5: After Installation:-
1) Open a new terminal (powershell (or) CMD)
2) Run this to confirm MongoDB is working: mongod

4) Express JS – Database, RESTful APIs

1) Express + Database (MongoDB)


You can connect Express to a database like : MongoDB using mongoose.
Example: connect Express with MongoDB

npm install express mongoose

2) RESTful APIs in node.js with Express


RESTful APIs = Create,Read,Update, Delete (CRUD)

HTTP method Route Action


POST /users Create user

GET /users Get all users

GET /users/:id Get one users

PUT /users/:id Update user

DELETE /users/:id Delete user

a) Write a program to connect MongoDB database using Mongoose


and perform CRUD operations.

 Install MongoDB locally or use MongoDB Atlas (cloud)


 Install dependencies using:
npm install express mongoose body-parser

const express = require(‘express’);


const mongoose = require(‘mongoose’);
const bodyParser = require(‘body-parser’);

const app = express();


app.use(bodyParser.json());

// MongoDB connection
mongoose.connect(‘mongodb://localhost:27017/mydb’, {
useNewUrlparser: true,

useUnifiedTopology: true
})
.then(() => console.log(‘ MongoDB connected’))
.catch(err => console.log(‘ MongoDB connection error:’, err));

// Schema & Model


const userSchema = new mongoose.schema({
name: String;
email: String,
age: Number
});

const User = mongoose.model(‘User’, userSchema);

// CREATE
app.post(‘/users’, async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.send(user);
} catch (err) {
res.status(400).send(err);
}
});

// READ ONE
app.get(‘/users/:id’, async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).send(‘User not found’);
res.send(user);
} catch (err) {
res.status(400).send(err);
}

});

// UPDATE
app.pu(‘/users/:id’, async (req, res) => {
try {
const user = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
if (!user) return res.status(404).send(‘User not found’);
res.send(user);
} catch (err) {
res.status(400).send(err);
}
});

// DELETE
app.delete(‘/users/:id’, async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) return res.status(404).send(‘User not found’);
res.send(‘User deleted’);
} catch (err) {
res.status(400).send(err);
}
});

// Start Server
app.listen(3000, () => {
console.log(‘Server is running on http://localhost:3000’);
});

OUTPUT: Welcome to the homepage!

b) Write a program to develop a single page application using


RESTful APIs.
Folder structure:
spa-app/
|-----server.js
|-----public/
|-----index.html

Index.html:
<!DOCTYPE html>
<html>
<title>Test SPA</title>
</head>
<body>
<h1>Hello from index.html!</h1>
</body>
</html>

server.js:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const PORT = 3000;

let users = [];

app.use(bodyParser.json());
app.use(express.static('public'));

// RESTful API endpoints


app.get('/api/public', (req, res) => {
res.json(public);
});

// Create
app.post('/api/users', (req, res) => {
const user = req.body;
user.push(user);
res.status(201).json({ message: 'User added', user });
});

app.put('/api/users/:id', (req, res) => {


const userId = req.params.id;
const updatedUser = req.body;
users = users.map((user, index) =>
index == userId ? updatedUser : user
);
res.json({message: 'User updated', updatedUser });
});

app.delete('/api/users/:id', (req, res) => {


const userId = req.params.id;
users.splice(userId, 1);
res.json({ message: 'User deleted' });
});

// Start server
app.listen(3000, () =>
console.log('Server is running on http://localhost:3000')
);

OUTPUT:
Hello from index.html

5) ReactJS – Render HTML, JSX, Components – function & Class

 We have to install packages:

npx create- react-app react-render-html

npm start

a) Write a program to render HTML to a web page.

Folder structure:

my-html-app
|-----index.js
|-----public/
| |-----index.html

Index.html:
<!DOCTYPE html>
<html>
<head>
<title>My HTML Page</title>
</head>
<body>
<h1>Hello from Node.js!</h1>
<p>This HTML page is rendered using Express server.</p>
</body>
</html>

Index.js:

const express = require('express');


const path = require('path');

const app = express();

// Serve static files the from the 'public' folder


app.use(express.static(path.join(__dirname, 'public')));

// Start the server


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

OUTPUT: hello from node.js!


This HTML page is rendered using Express server

b) Write a program for writing markup with JSX.

Folder Structure:

Waiting-markup-app/
|------public/
| |------index.html
| |------bundle.js
|---------src/
| |-----App.jsx
|--------server.js
|--------webpack.config.js
|-------- .babelrc

 We have to install some packages:

npm install express react react-dom


npm install --save-dev @babel/core @babel/preset-env @babel/preset-react
babel-loader webpack webpack-cli webpack-dev-middleware

index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Waiting Markup</title>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
</html>

bundle.js:
document.getElementById("root").innerHTML = "<h1>Hello, this is my
output!</h1>";

App.jsx:

// src/App.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';

const App = () => {


return (
<div style={{ textAlign: 'center', paddingTop: '100px' }}>
<h1>Please Wait...</h1>
<p>Loading your content...</p>
</div>
);
};

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

.babelrc:

{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

webpack.config.js:

const path = require('path');

module.exports = {
entry: './src/App.jsx',
output: {
path: path.resolve(__dirname, 'public/'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
mode: 'development'
};

server.js:

const express = require('express');


const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const config = require('./webpack.config');

const app = express();


const compiler = webpack(config);

app.get('/', (req, res) => {


res.sendFile(__dirname + '/public/index.html');
});

app.use(webpackMiddleware(compiler));
app.use(express.static('public'));

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

Output: Please wait…


Loading your content….

c) Write a program for creating and nesting components (function


and class).

Folder structure:

My-node-app/

├── index.js
└── components/
├── Layout.js
└── Content.js

My-node-app/ Index.js:

// Importing child components


const { Header, Footer } = require('./components/Layout');
const { Content } = require('./components/Content');

// Function Component: App


function App() {
console.log("Rendering App...");

// Nesting other components


Header();
Content();
Footer();
}

// Run the App


App();

My-node-app/ components/ layout.js:

// Function Component: Header


function Header() {
console.log("Rendering Header...");
}

// Function Component: Footer


function Footer() {
console.log("Rendering Footer...");
}

module.exports = {
Header,
Footer
};

My-node-app/components/content.js:

// Class Component: Content


class Content {
constructor() {
this.message = "This is the main content area.";
}

render() {
console.log("Rendering Content...");
console.log(this.message);
this.renderNestedComponent();
}

// Simulated nested component


renderNestedComponent() {
const sidebar = new Sidebar();
sidebar.render();
}
}

// Nested Class Component inside Content


class Sidebar {
constructor() {
this.info = "Sidebar info here.";
}

render() {
console.log("Rendering Sidebar...");
console.log(this.info);
}
}

// Export function to render content


module.exports = {
Content: () => {
const content = new Content();
content.render();
}
};

Output:

Rendering App...
Rendering Header...
Rendering Content...
This is the main content area.
Rendering Sidebar...
Sidebar info here.
Rendering Footer...

6) ReactJS – Props and States, Styles, Respond to Events

· Props and State: Component communication and internal data.

· Styling: Inline styles and CSS.

· Event Handling: Respond to user actions.

· Run in Node.js: Use create-react-app or Vite to build/run a frontend in a


Node.js environment.

a) Write a program to work with props and states.

for frontend:

npm install react react-dom


npm install --save-dev vite @vitejs/plugin-react

Folder structure:

my-app/
├── backend/
│ └── server.js
├── frontend/
│ ├── public/
│ │ └── index.html
│ ├── src/
│ │ ├── App.jsx
│ │ └── index.js
└── package.json

backend/ server.js:
const express = require('express');
const cors = require('cors');

const app = express();


const PORT = 5000;

app.use(cors());

app.get('/api/message', (req, res) => {


res.json({ message: "Hello from the backend!" });
});

app.listen(5000, () => {
console.log(`Backend running on http://localhost:5000`);
});

frontend/public/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

frontend/src/App.jsx:

import React, { useEffect, useState } from 'react';

const App = () => {


const [message, setMessage] = useState('');

useEffect(() => {
fetch('http://localhost:5000/api/message')
.then(res => res.json())
.then(data => setMessage(data.message))
.catch(err => console.error(err));
}, []);

return (
<div>
<h1>React Frontend</h1>
<p>{message ? message : "Loading..."}</p>
</div>
);
};

export default App;

frontend/src/index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<App />);

frontend/package.json:

{
"name": "frontend",
"version": "0.1.0",
"private": "true",
"dependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "^5.0.1"
},
"scripts": {
"start": "react-scripts start"
},
"proxy": "http://localhost:5000"
}

Output:

When fully loaded: React frontend


Hello from the backend!
While loading(for a brief moment): React frontend
Loading….
Backend(node.js):

Backend running on http://localhost:5000

Frontend (react dev server):


Compiled successfully!
You can now view frontend in the browser.
Local: http://localhost:3000

b) Write a program to add styles (CSS & Sass Styling) and display
data.

Folder structure:

node-css-sass-app/
├── public/
│ ├── styles/
│ │ ├── main.scss
├── views/
│ └── index.ejs
├── app.js

Install packages:

npm init -y
npm install express ejs
npm install sass-middleware

Type this in the terminal:

sass public/styles/main.scss public/styles/main.css

npm run sass


npm start

node-css-sass-app/public/styles/main.scss:

$primary-color: #3498db;

body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
h1 {
color: $primary-color;
}

ul {
list-style: none;
padding: 0;

li {
background: white;
margin: 10px 0;
padding: 10px;
border-left: 5px solid $primary-color;
}
}
}

node-css-sass-app/views/index.ejs:

<!DOCTYPE html>
<html>
<head>
<title>Styled Node App</title>
<link rel="stylesheet" href="/styles/main.css">
</head>
<body>
<h1>Data List</h1>
<ul>
<% data.forEach(item => { %>
<li><%= item %></li>
<% }) %>
</ul>
</body>
</html>

node-css-sass-app/app.js:

const express = require('express');


const path = require('path');
const sassMiddleware = require('sass-middleware');

const app = express();


const port = 3000;

// Sass middleware
app.use(
sassMiddleware({
src: path.join(__dirname, 'public', 'styles'),
dest: path.join(__dirname, 'public', 'styles'),
debug: true,
outputStyle: 'compressed',
prefix: '/styles',
})
);

// Static files
app.use(express.static(path.join(__dirname, 'public')));

// Set EJS as templating engine


app.set('view engine', 'ejs');

// Sample data
const data = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

// Routes
app.get('/', (req, res) => {
res.render('index', { data });
});

app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

Output :

+------------------------------+
| Data List | ← blue heading
| |
| ┌────────────────────────┐ |
| | Apple | | ← white box with blue border
| └────────────────────────┘ |
| ┌────────────────────────┐ |
| | Banana | |
| └────────────────────────┘ |
| ... |
+------------------------------+

c)Write a program for responding to events.

// Import the events module


const EventEmitter = require('events');

// Create a class that extends EventEmitter


class MyEmitter extends EventEmitter {}
// Create an instance of the class
const myEmitter = new MyEmitter();

// Define an event listener for the 'greet' event


myEmitter.on('greet', (name) => {
console.log(`Hello, ${name}! Welcome to the event-driven world of Node.js.`);
});

// Define another event listener for 'bye'


myEmitter.on('bye', (name) => {
console.log(`Goodbye, ${name}. See you next time!`);
});

// Emit the 'greet' event


myEmitter.emit('greet', 'Alice');

// Emit the 'bye' event


myEmitter.emit('bye', 'Alice');

Output:

Hello, Alice! Welcome to the event-driven world of Node.js.


Goodbye, Alice. See you next time!

7) ReactJS – Conditional Rendering, Rendering Lists, React Forms

a) Write a program for conditional rendering


Install packages:
npm install express ejs

Folder structure:

project/
├── views/
│ └── index.ejs
├── server.js
└── package.json

server.js:

const express = require('express');


const app = express();
const port = 3000;
// Set EJS as the view engine
app.set('view engine', 'ejs');

// Serve the index page


app.get('/', (req, res) => {
const isLoggedIn = false; // You can change this to false to test

res.render('index', {
user: {
name: 'John Doe',
role: 'admin',
},
isLoggedIn: isLoggedIn
});
});

app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

Index.ejs:

<!DOCTYPE html>
<html>
<head>
<title>Conditional Rendering</title>
</head>
<body>
<% if (isLoggedIn) { %>
<h1>Welcome, <%= user.name %>!</h1>
<% if (user.role === 'admin') { %>
<p>You have admin privileges.</p>
<% } else { %>
<p>You are a regular user.</p>
<% } %>
<% } else { %>
<h1>Please log in to continue.</h1>
<% } %>
</body>
</html>

Package.json:

{
"name": "conditional-rendering",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"ejs": "^3.1.10",
"express": "^4.21.2"
},
"description": "",
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs"
}

Outputs:

Output 1:

isLoggedIn is true:

isLoggedIn = true

user.name = 'John Doe'

user.role = 'admin'

Output 2:

isLoggedIn = false:
Please log in to continue.

b) Write a program for rendering lists.

/node-list-rendering
├── views
│ └── users.ejs
└── app.js

node-list-rendering/views/users.ejs:

const express = require('express');


const app = express();
const port = 3000;
// Set EJS as the view engine
app.set('view engine', 'ejs');

// Sample user list


const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 28 }
];

// Route to render the list


app.get('/', (req, res) => {
res.render('users', { users });
});

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

node-list-rendering/app.js:

<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>List of Users</h1>
<ul>
<% users.forEach(function(user) { %>
<li><strong><%= user.name %></strong> - Age: <%= user.age %></li>
<% }); %>
</ul>
</body>
</html>

Open your browser and go to:


👉 http://localhost:3000

Output in the Browser:

List of Users

- Alice - Age: 25
- Bob - Age: 30
- Charlie - Age: 28

c) Write a program for working with different form fields using react
forms.

Folder Structure:
form-app/
├── server/ <-- Node.js + Express backend
│ └── index.js
├── client/ <-- React frontend
│ ├── src/
│ │ └── App.js
│ └── package.json

form-app/server/index.js:

const express = require('express');


const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();


const PORT = 5000;

app.use(cors());
app.use(bodyParser.json());

// GET route
app.get('/', (req, res) => {
res.send('Server is up and running!');
});

// POST route for form submission


app.post('/form-submit', (req, res) => {
console.log('Received Form Data:', req.body);
res.status(200).json({ message: 'Form submitted successfully', data: req.body });
});

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

Install packages:

npm init -y
npm install express cors body-parser
node index.js
form-app/client/src/App.js:

import React from 'react';


import './App.css'; // optional: for external CSS

function App() {
return (
<div className="container">
{/* App Logo */}
<div className="logo-container">
<img src="/mylogo.png" alt="App Logo" className="logo" />
</div>

{/* Form Table */}


<form className="form-container">
<form style={{ width: '10,000px' }}>
{/* form content */}
</form>
<table>
<tbody>
<tr>
<td><label htmlFor="name">Name:</label></td>
<td><input type="text" id="name" name="name" /></td>
</tr>
<tr>
<td><label htmlFor="email">Email:</label></td>
<td><input type="email" id="email" name="email" /></td>
</tr>
<tr>
<td><label htmlFor="password">Password:</label></td>
<td><input type="password" id="password" name="password" /></td>
</tr>
<tr>
<td colSpan="2" style={{ textAlign: 'center' }}>
<button type="submit">Submit</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
);
}

export default App;

form-app/client/package.json:

{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.6.4",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Output:

Name:
Email:
Passwor
d:
Submit

8. ReactJS – React Router, Updating the Screen

a) Write a program for routing to different pages using react router.

my-react-router-app/

├── public/
│ └── index.html
├── src/
│ ├── App.js
│ ├── Home.js
│ ├── About.js
│ ├── Contact.js
│ └── index.js
├── package.json

my-react-router-app/public/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<title>React Router App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

my-react-router-app/src/App.js:

import React from 'react';


import { Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
function App() {
return (
<div>
<nav style={{ marginBottom: '20px' }}>
<Link to="/" style={{ marginRight: '10px' }}>Home</Link>
<Link to="/about" style={{ marginRight: '10px' }}>About</Link>
<Link to="/contact">Contact</Link>
</nav>

<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
);
}

export default App;

my-react-router-app/src/Home.js:
import React from 'react';

function Home() {
return (
<div>
<h1>Welcome to My Website</h1>
<p>This is a simple React Router demo app.</p>
</div>
);
}

export default Home;

my-react-router-app/src/About.js:

import React from 'react';

function About() {
return (
<div>
<h1>About This App</h1>
<p>This app demonstrates routing in React using React Router.</p>
<p>Built with 😆 by OpenAI and you!</p>
</div>
);
}

export default About;

my-react-router-app/src/contact.js:

import React, { useState } from 'react';

function Contact() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});

const [submitted, setSubmitted] = useState(false);

// Handle input changes


const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};

// Handle form submission


const handleSubmit = (e) => {
e.preventDefault(); // Prevent page reload
console.log('Form Submitted:', formData);
setSubmitted(true);
};

return (
<div>
<h1>Contact Us</h1>

{submitted ? (
<p style={{ color: 'green' }}>
✅ Thank you, <strong>{formData.name}</strong>! Your message has been
sent.
</p>
):(
<form onSubmit={handleSubmit}>
<label>Name:</label><br />
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
required
/><br /><br />

<label>Email:</label><br />
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/><br /><br />

<label>Message:</label><br />
<textarea
name="message"
value={formData.message}
onChange={handleChange}
required
rows="4"
></textarea><br /><br />

<button type="submit">Send</button>
</form>
)}
</div>
);
}

export default Contact;

my-react-router-app/src/index.js:

import React from 'react';


import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);

my-react-router-app/package.json:
{
"name": "my-react-router-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.30.1",
"react-scripts": "^0.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Output:

Home: Welcome to My Website


This is a simple React Router demo app.

About: About This App

This app demonstrates routing in React using React Router.

Built with by😊 OpenAI and you!

Contact: Contact Us

Name:

Email:
Message:

Send

b) Write a program for updating the screen.

const readline = require('readline');

// Hide cursor for cleaner output


process.stdout.write('\x1B[?25l');

function updateScreen() {
readline.cursorTo(process.stdout, 0, 0); // Move cursor to top-left
readline.clearScreenDown(process.stdout); // Clear screen

const now = new Date();


console.log('📅 Current Time:');
console.log(now.toLocaleTimeString());

console.log('\nScreen updates every second...');


}

// Initial update
updateScreen();

// Update screen every second


setInterval(updateScreen, 1000);

// Optional: Handle Ctrl+C gracefully


process.on('SIGINT', () => {
readline.cursorTo(process.stdout, 0);
readline.clearScreenDown(process.stdout);
process.stdout.write('\x1B[?25h'); // Show cursor again
console.log('\nExiting...');
process.exit();
});

Output:

📅 Current Time:
4:51:38 pm

Screen updates every second…

9. ReactJS – Hooks, Sharing data between Components

a) Write a program to understand the importance of using hooks.

Install package:

npm install mongoose

//file: mongoose-hooks-example.js
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/hookDemo', {
useNewUrlParser: true,
useUnifiedTopology: true
});

const userSchema = new mongoose.Schema({


name: String,
email: String
});

// Pre-save hook (before saving)


userSchema.pre('save', function (next) {
console.log(`📥 About to save user: ${this.name}`);
next();
});

// Post-save hook (after saving)


userSchema.post('save', function (doc, next) {
console.log(`✅ User saved: ${doc.name}`);
next();
});

const User = mongoose.model('User', userSchema);

async function createUser() {


const user = new User({ name: 'Alice', email: '[email protected]' });
await user.save(); // hooks are triggered here
}

createUser().then(() => mongoose.disconnect());


Output:

📥 About to save user: Alice


✅ User saved: Alice

b) Write a program for sharing data between components.

Folder structure:

node-shared-data-example

├── sharedData.js

├── writer.js

├── reader.js

└── main.js

node-shared-data-example/sharedData.js:

// sharedData.js
const data = {
message: "Initial message"
};

module.exports = {
getMessage: () => data.message,
setMessage: (newMessage) => {
data.message = newMessage;
}
};

node-shared-data-example/writer.js:

// writer.js
const sharedData = require('./sharedData');

function updateMessage() {
sharedData.setMessage("Updated by writer module");
console.log("✅ Message updated in writer");
}

module.exports = updateMessage;

node-shared-data-example/reader.js:
// reader.js
const sharedData = require('./sharedData');

function readMessage() {
console.log("📩 Reader got message:", sharedData.getMessage());
}

module.exports = readMessage;

node-shared-data-example/main.js:

// main.js
const updateMessage = require('./writer');
const readMessage = require('./reader');

console.log("🔹 Before update:");


readMessage(); // Reads the initial message

console.log("🔹 Updating message...");


updateMessage(); // Writer updates the message

console.log("🔹 After update:");


readMessage(); // Reader sees updated message

Output:

Before update:
📩 Reader got message: Initial message
🔹 Updating message...
✅ Message updated in writer
🔹 After update:
📩 Reader got message: Updated by writer module

10. MongoDB – Installation, Configuration, CRUD operations

a) Install MongoDB and configure ATLAS

PART 1: Set Up MongoDB Atlas (Cloud Database)

✅ Step 1: Create a Free Atlas Account


 Visit: https://www.mongodb.com/cloud/atlas
 Sign up for a free account
 Whitelist your IP and create a user/password.
 Copy your connection string (something like
mongodb+srv://<user>:<pass>@cluster0.mongodb.net/test)

✅ Step 2: Create a Cluster

 Choose Shared Cluster (Free Tier)


 Pick a cloud provider and region
 Give it a name (or leave default)
 Click "Create Cluster"

✅ Step 3: Create a Database User

 Go to Database > Database Access


 Add a new user
 Username: myUser
 Password: myPassword123 (use a secure one!)
 Select Role: Read and write to any database

✅ Step 4: Whitelist IP Address

 Go to Network Access
 Click Add IP Address
 Choose 0.0.0.0 (allow from anywhere — for dev only!)
 Or your IP for security

✅ Step 5: Connect to Your Cluster

 Go to Clusters > Connect


 Choose "Connect your application"
 Copy the Connection String:

mongodb+srv://username:<password>@cluster0.xxxxx.mongodb.net/database_name?
retryWrites=true&w=majority

Replace <password> with your actual password

Folder structure:

mongo-node-crud

|-------- .env
|-------- sever.js

Install packages: npm install express mongoose dotenv

mongo-node-crud/server.js:

const express = require('express');


const mongoose = require('mongoose');
require('dotenv').config(); // 👈 Load .env variables

const app = express();


const PORT = process.env.PORT || 5000;

app.use(express.json());

app.get('/', (req, res) => {


res.send('API is working');
});

// 👇 Connect to MongoDB Atlas


mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('✅ Connected to MongoDB Atlas');
app.listen(PORT, () => {
console.log('Server running on http://localhost:5000');
});
})
.catch((err) => {
console.error('❌ MongoDB connection error:', err);
});

mongo-node-crud/ .env :

MONGO_URI=mongodb+srv://admin:[email protected]/
testdb?retryWrites=true&w=majority
PORT=5000

Output: API is working

b) Write MongoDB queries to perform CRUD operations on


document using insert(), find(), update(), remove()
Folder structure:

mongo-native-crud

|----- .env

|----- crud.js

Install package: npm install mongodb

mongo-native-crud/crud.js:

require('dotenv').config();
const { MongoClient, ObjectId } = require('mongodb');

const uri = process.env.MONGO_URI;


const dbName = process.env.DB_NAME;

async function main() {


const client = new MongoClient(uri, { useUnifiedTopology: true });

try {
await client.connect();
console.log('✅ Connected to MongoDB');

const db = client.db(dbName);
const users = db.collection('users');

// ----------------------------
// 🔽 INSERT - insertOne()
// ----------------------------
const newUser = { name: 'Alice', email: '[email protected]', age: 25 };
const insertResult = await users.insertOne(newUser);
console.log('✅ Inserted:', insertResult.insertedId);

// ----------------------------
// 🔍 READ - find()
// ----------------------------
const allUsers = await users.find().toArray();
console.log('📄 All Users:', allUsers);

// ----------------------------
// ✏️UPDATE - updateOne()
// ----------------------------
const updateResult = await users.updateOne(
{ _id: insertResult.insertedId },
{ $set: { age: 30 } }
);
console.log('✏️Updated:', updateResult.modifiedCount, 'document(s)');
// ----------------------------
// ❌ DELETE - remove() is deprecated, use deleteOne()
// ----------------------------
const deleteResult = await users.deleteOne({ _id: insertResult.insertedId });
console.log(' Deleted:', deleteResult.deletedCount, 'document(s)');

} catch (err) {
console.error('❌ Error:', err);
} finally {
await client.close();
console.log('🔌 Disconnected');
}
}

main();

mongo-native-crud/ .env:

MONGO_URI=mongodb://localhost:27017
DB_NAME=testdb

Output:

📄 All Users: [

_id: new ObjectId('6891d91b378e9711c29422ee'),

name: 'Alice',

email: '[email protected]',

age: 25

✏️Updated: 1 document(s)

Deleted: 1 document(s)

🔌 Disconnected

11) MongoDB – Databases, Collections and Records


a) Write MongoDB queries to Create and drop databases and
collections.

Folder structure:

program11a

|------ .env

|------ manageDb.js

Install package: npm install mongodb

program11a/ .env:

MONGO_URI=mongodb://localhost:27017

program11a/manageDb.js:

require('dotenv').config();
const { MongoClient } = require('mongodb');

const uri = process.env.MONGO_URI;

async function main() {


const client = new MongoClient(uri, { useUnifiedTopology: true });

try {
await client.connect();
console.log('✅ Connected to MongoDB');

// 📂 Create a Database and Collection


const db = client.db('schoolDB'); // Create/use database
const students = db.collection('students'); // Create/use collection

// 👉 Inserting one document will create both DB and collection


await students.insertOne({ name: 'Alice', age: 20 });
console.log('📁 Database and collection created with one document');

// 🔥 Drop Collection
const dropCollectionResult = await db.collection('students').drop();
console.log(' Collection dropped:', dropCollectionResult); // true

// 🔥 Drop Database
const dropDbResult = await db.dropDatabase();
console.log(' Database dropped:', dropDbResult); // true
} catch (err) {
console.error('❌ Error:', err);
} finally {
await client.close();
console.log('🔌 Disconnected from MongoDB');
}
}

main();

Output:

Database and collection created with one document


Collection dropped: true
Database dropped: true
🔌 Disconnected from MongoDB

b) Write MongoDB queries to work with records using find(), limit(),


sort(), createIndex(), aggregate().

Folder structure:

mongo-queries

|------ .env

|------ queries.js

mongo-queries/ .env:

MONGO_URI=mongodb://localhost:27017

mongo-queries/ queries.js:

require('dotenv').config();
const { MongoClient } = require('mongodb');

const uri = process.env.MONGO_URI;

async function main() {


const client = new MongoClient(uri, { useUnifiedTopology: true });

try {
await client.connect();
console.log('✅ Connected to MongoDB');

const db = client.db('companyDB');
const employees = db.collection('employees');
// 🔁 Insert sample records
await employees.insertMany([
{ name: 'Alice', age: 25, dept: 'HR', salary: 3000 },
{ name: 'Bob', age: 30, dept: 'IT', salary: 5000 },
{ name: 'Carol', age: 28, dept: 'IT', salary: 4500 },
{ name: 'Dave', age: 35, dept: 'Finance', salary: 6000 },
{ name: 'Eve', age: 22, dept: 'HR', salary: 3200 }
]);
console.log('📥 Sample data inserted');

// 📄 1. find() - Get all documents


const all = await employees.find().toArray();
console.log('\n📄 All Employees:', all);

// 📄 2. limit() - Get only 2 records


const limited = await employees.find().limit(2).toArray();
console.log('\n📦 Limited (2) Employees:', limited);

// 📄 3. sort() - Sort by salary descending


const sorted = await employees.find().sort({ salary: -1 }).toArray();
console.log('\n📊 Sorted by salary (desc):', sorted);

// ⚡ 4. createIndex() - Create index on "dept"


const indexResult = await employees.createIndex({ dept: 1 });
console.log('\n⚙️Index created on dept:', indexResult);

// 📊 5. aggregate() - Group by dept and get average salary


const aggregation = await employees.aggregate([
{ $group: { _id: '$dept', avgSalary: { $avg: '$salary' } } },
{ $sort: { avgSalary: -1 } }
]).toArray();
console.log('\n📈 Average salary by department:', aggregation);

} catch (err) {
console.error('❌ Error:', err);
} finally {
await client.close();
console.log('\n🔌 Disconnected');
}
}

main();

Output:

📥 Sample data inserted


📄 All Employees: [

_id: new ObjectId('6891ae61c87819a49997af2d'),

name: 'Alice',

age: 25,

dept: 'HR',

salary: 3000

},

_id: new ObjectId('6891ae61c87819a49997af2e'),

name: 'Bob',

age: 30,

dept: 'IT',

salary: 5000

},

_id: new ObjectId('6891ae61c87819a49997af2f'),

name: 'Carol',

age: 28,

dept: 'IT',

salary: 4500

},

_id: new ObjectId('6891ae61c87819a49997af30'),

name: 'Dave',
age: 35,

dept: 'Finance',

salary: 6000

},

_id: new ObjectId('6891ae61c87819a49997af31'),

name: 'Eve',

age: 22,

dept: 'HR',

salary: 3200

},

_id: new ObjectId('6891d5c4f6ec906331833023'),

name: 'Alice',

age: 25,

dept: 'HR',

salary: 3000

},

_id: new ObjectId('6891d5c4f6ec906331833024'),

name: 'Bob',

age: 30,

dept: 'IT',

salary: 5000

},
{

_id: new ObjectId('6891d5c4f6ec906331833025'),

name: 'Carol',

age: 28,

dept: 'IT',

salary: 4500

},

_id: new ObjectId('6891d5c4f6ec906331833026'),

name: 'Dave',

age: 35,

dept: 'Finance',

salary: 6000

},

_id: new ObjectId('6891d5c4f6ec906331833027'),

name: 'Eve',

age: 22,

dept: 'HR',

salary: 3200

},

_id: new ObjectId('6891df5603e52cad326b62e6'),

name: 'Alice',

age: 25,
dept: 'HR',

salary: 3000

},

_id: new ObjectId('6891df5603e52cad326b62e7'),

name: 'Bob',

age: 30,

dept: 'IT',

salary: 5000

},

_id: new ObjectId('6891df5603e52cad326b62e8'),

name: 'Carol',

age: 28,

dept: 'IT',

salary: 4500

},

_id: new ObjectId('6891df5603e52cad326b62e9'),

name: 'Dave',

age: 35,

dept: 'Finance',

salary: 6000

},

{
_id: new ObjectId('6891df5603e52cad326b62ea'),

name: 'Eve',

age: 22,

dept: 'HR',

salary: 3200

📦 Limited (2) Employees: [

_id: new ObjectId('6891ae61c87819a49997af2d'),

name: 'Alice',

age: 25,

dept: 'HR',

salary: 3000

},

_id: new ObjectId('6891ae61c87819a49997af2e'),

name: 'Bob',

age: 30,

dept: 'IT',

salary: 5000

📊 Sorted by salary (desc): [

{
_id: new ObjectId('6891ae61c87819a49997af30'),

name: 'Dave',

age: 35,

dept: 'Finance',

salary: 6000

},

_id: new ObjectId('6891d5c4f6ec906331833026'),

name: 'Dave',

age: 35,

dept: 'Finance',

salary: 6000

},

_id: new ObjectId('6891df5603e52cad326b62e9'),

name: 'Dave',

age: 35,

dept: 'Finance',

salary: 6000

},

_id: new ObjectId('6891ae61c87819a49997af2e'),

name: 'Bob',

age: 30,

dept: 'IT',
salary: 5000

},

_id: new ObjectId('6891d5c4f6ec906331833024'),

name: 'Bob',

age: 30,

dept: 'IT',

salary: 5000

},

_id: new ObjectId('6891df5603e52cad326b62e7'),

name: 'Bob',

age: 30,

dept: 'IT',

salary: 5000

},

_id: new ObjectId('6891ae61c87819a49997af2f'),

name: 'Carol',

age: 28,

dept: 'IT',

salary: 4500

},

_id: new ObjectId('6891d5c4f6ec906331833025'),


name: 'Carol',

age: 28,

dept: 'IT',

salary: 4500

},

_id: new ObjectId('6891df5603e52cad326b62e8'),

name: 'Carol',

age: 28,

dept: 'IT',

salary: 4500

},

_id: new ObjectId('6891ae61c87819a49997af31'),

name: 'Eve',

age: 22,

dept: 'HR',

salary: 3200

},

_id: new ObjectId('6891d5c4f6ec906331833027'),

name: 'Eve',

age: 22,

dept: 'HR',

salary: 3200
},

_id: new ObjectId('6891df5603e52cad326b62ea'),

name: 'Eve',

age: 22,

dept: 'HR',

salary: 3200

},

_id: new ObjectId('6891ae61c87819a49997af2d'),

name: 'Alice',

age: 25,

dept: 'HR',

salary: 3000

},

_id: new ObjectId('6891d5c4f6ec906331833023'),

name: 'Alice',

age: 25,

dept: 'HR',

salary: 3000

},

_id: new ObjectId('6891df5603e52cad326b62e6'),

name: 'Alice',
age: 25,

dept: 'HR',

salary: 3000

⚙️Index created on dept: dept_1

📈 Average salary by department: [

{ _id: 'Finance', avgSalary: 6000 },

{ _id: 'IT', avgSalary: 4750 },

{ _id: 'HR', avgSalary: 3100 }

🔌 Disconnected

12) Augmented Programs:

a) Design a to-do list application using NodeJS and ExpressJS.

Folder Structure:

todo-app/

├── views/

│ └── index.ejs

├── public/

│ └── styles.css

├── app.js

├── package.json

Install packages:

npm init -y
npm install express ejs body-parser uuid

todo-app/views/index.ejs:

<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>To-Do List</h1>
<form action="/add" method="POST">
<input type="text" name="task" placeholder="New Task name" required>
<button type="submit">Add Task</button>
</form>

<ul>
<% tasks.forEach(task => { %>
<li>
<%= task.name %>
<a href="/complete/<%= task._id %>">Complete</a>
<form action="/complete/<%= task.id %>" method="POST";
style="display:inline;">
<button type="submit">
<% if (task.completed) { %> ☐
<% } else { %> ☐ <% } %>
</button>
</form>

<span style "<%= task.completed ? 'text-decoration:line-through; ' : '' %>">


<%= task.title %>
</span>

<form action="/delete/<%= task.id %>" method="POST"


style="display:inline;">
<button type="submit"></button>
</form>
</li>
<% }) %>
</ul>
</body>
</html>

todo-app/public/styles.css:

body {
font-family: Arial, sans-serif;

width: 50%;

margin: auto;

padding-top: 40px;

h1 {

text-align: center;

form {

margin-bottom: 20px;

ul {

list-style-type: none;

padding-left: 0;

li {

margin-bottom: 10px;

display: flex;

align-items: center;

}
button {

margin-right: 10px;

todo-app/app.js:

// app.js
const express = require('express');
const bodyParser = require('body-parser');
const { v4: uuidv4 } = require('uuid');

const app = express();


const port = 3000;

// In-memory task list


let tasks = [];

// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.set('view engine', 'ejs');

// Routes
app.get('/', (req, res) => {
res.render('index', { tasks });
});

app.post('/add', (req, res) => {


const newTask = {
id: uuidv4(),
title: req.body.task,
completed: false
};
tasks.push(newTask);
res.redirect('/');
});

app.post('/complete/:id', (req, res) => {


const task = tasks.find(t => t.id === req.params.id);
if (task) task.completed = !task.completed;
res.redirect('/');
});

app.post('/delete/:id', (req, res) => {


tasks = tasks.filter(t => t.id !== req.params.id);
res.redirect('/');
});
// Start server
app.listen(port, () => {
console.log(`To-Do App running at http://localhost:${port}`);
});

todo-app/package.json:

{
"name": "todo-app",
"version": "1.0.0",
"description": "A simple to-do list app using Node.js and Express.js",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"keywords": [
"todo",
"nodejs",
"express"
],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"body-parser": "^1.20.3",
"ejs": "^3.1.10",
"express": "^4.21.2",
"uuid": "^9.0.1"
},
"type": "commonjs"
}

Output:

To-Do List

Add Task

You might also like