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

Installing VS Code and Node.js on Windows

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)
17 views74 pages

Installing VS Code and Node.js on Windows

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

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 [Link] :
How to Install [Link] on Windows
Installing [Link] 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 [Link] on your Windows:

Step 1: Download [Link] Installer

 Visit the official [Link] websiteto download the [Link]


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 [Link] 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 [Link] 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 [Link] 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 [Link] using the following command:
sudo apt install nodejs
sudo apt install npm

Step 4: Verify [Link] and NPM Installation

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

✅ 1. Basic Console Output ([Link]):


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

 2. Hello World HTTP Server:


// [Link]
const http = require("http");

const server = [Link]((req, res) => {


[Link] = 200;
[Link]("Content-Type", "text/plain");
[Link]("Hello, World!\n");
});

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

 Hello World with [Link]


If you want a cleaner server using the Express framework:

// [Link]

const express = require("express");

const app = express();

const port = 3000;

[Link]("/", (req, res) => {

[Link]("Hello, World!");

});

[Link](port, () => {

[Link](`Example app listening at [Link]

});

1. Install Express first:

npm init -y
npm install express
[Link] run: node [Link]

[Link]’ll see: Example app listening at [Link]


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

1. Routing in [Link]

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 "/"

[Link]("/", (req, res) => {

[Link]("Home Page");

});

// Route for GET request to "/about"

[Link]("/about", (req, res) => {

[Link]("About Page");

});
2. HTTP Methods in [Link]

Express supports all common HTTP methods used in RESTful APIs:

Method Purpose Example


GET Read data [Link]("/items", ...)
POST Create new data [Link]("/items", ...)
PUT Update entire resource [Link]("/items/:id", ...)
PATCH Update part of resource [Link]("/items/:id", ...)
DELETE Delete data [Link]("/items/:id", ...)

Example with Multiple Methods:

[Link]("/submit", (req, res) => {

[Link]("Form submitted");

});

[Link]("/update/:id", (req, res) => {

[Link](`Update item ${[Link]}`);

});

[Link]("/delete/:id", (req, res) => {

[Link](`Deleted item ${[Link]}`);

});

3. Middleware in [Link]

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

[Link] the request-response cycle

3. Call the next middleware in the stack

 Basic Middleware Example:


const express = require("express");

const app = express();

// Global middleware

[Link]((req, res, next) => {

[Link](`${[Link]} ${[Link]}`);

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


[Link]([Link]());

// 1. Defining Basic Routes


[Link]('/', (req, res) => {
[Link]('Hello, this is the homepage!');
});

[Link]('/items', (req, res) => {


[Link]('Item created');
});

// 2. Route Parameters
[Link]('/users/:id', (req, res) => {
const userId = [Link];
[Link](`User ID: ${userId}`);
});

// 3. Query Parameters
[Link]('/search', (req, res) => {
const searchTerm = [Link].q;
[Link](`Search term: ${searchTerm}`);
});

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


[Link]('/profile/:username', (req, res) => {
const username = [Link];
const profileUrl = `/users/${username}`;
[Link](`Profile URL: ${profileUrl}`);
});

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


[Link]('/resource')
.get((req, res) => {
[Link]('GET request to /resource');
})
.post((req, res) => {
[Link]('POST request to /resource');
});

[Link](port, () => {
[Link](`Server listening at [Link]
});

OUTPUTS:

 Server running at [Link]

1. Home Route: [Link]


Response: Welcome to the Home Page

[Link] with Route Parameter: [Link]


Response: User ID from route: 123

[Link] with Query Parameters: [Link]


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

[Link] Builder Route: [Link]


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

[Link] Route (Fallback 404): [Link]


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: [Link] (or) [Link]

// [Link]
const express = require('express');
const app = express();
[Link]([Link]()); // parse JSON bodies

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


let nextId = 1;

// Create (accept data via POST)


[Link]('/items', (req, res) => {
const { name } = [Link];
if (!name) return [Link](400).json({ error: 'Name is required' });

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


[Link](item);
[Link](201).json(item);
});

// Retrieve all items (GET)


[Link]('/items', (req, res) => {
[Link](items);
});

// Retrieve specific item by id


[Link]('/items/:id', (req, res) => {
const item = [Link](i => [Link] === parseInt([Link]));
if (!item) return [Link](404).json({ error: 'Item not found' });
[Link](item);
});

// Delete a specified item


[Link]('/items/:id', (req, res) => {
const idx = [Link](i => [Link] === parseInt([Link]));
if (idx === -1) return [Link](404).json({ error: 'Item not found' });

const deleted = [Link](idx, 1);


[Link]({ message: 'Item deleted', item: deleted[0] });
});

// Start the server


const PORT = [Link] || 3000;
[Link](PORT, () => [Link](`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.
[Link]((req, res, next) => {
[Link]([${new Date().toISOString()}] ${[Link]} ${[Link]});
next();
});

// Middleware 2: Authentication check


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

// Route Handler for a root path


[Link]('/', (req, res) => {
[Link]('Hello, this is the home route!');
});

// Route Handler for a secure path


[Link]('/secure', (req, res) => {
[Link]('Welcome to the secure route!');
});

// Start the server


[Link](port, () => {
[Link](`Server is running on [Link]
});

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

[Link] facilitates both templating for dynamic HTML generation and handling
form data submitted from clients.

1. Templating in [Link]:

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: [Link]('view engine', 'ejs');
3. Specify the directory where your template files are located: [Link]('views',
[Link](__dirname, 'views'));

Rendering: Use [Link]() to render a template and pass data to it:

[Link]('/', (req, res) => {


[Link]('index', { title: 'My Page', message: 'Welcome!' });
});

In [Link], you can access the data using embedded JavaScript:


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

2. Handling form Data in [Link]:

 Parsing Middleware: [Link] requires middleware to parse incoming form


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

[Link]([Link]({ extended: true }));

 [Link](): For JSON data (e.g., API requests with Content-Type:


application/json).
[Link]([Link]());

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

const multer = require('multer');


const upload = multer({ dest: 'uploads/' }); // Specify upload directory
[Link]('/upload', [Link]('myFile'), (req, res) => {
// Access file details in [Link] and text fields in [Link]
});

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


accessible in the [Link] object for POST requests, or in [Link] for GET
requests.

[Link]('/submit-form', (req, res) => {


const username = [Link];
const password = [Link];
// 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


[Link](‘view engine’, ‘ejs’);

// Specify the directory where your EJS templates (views) are located
[Link](‘views’, [Link](__dirname, ‘views’));

// Define a route to render the EJS template


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

// Start the server


[Link](3000, () => {
[Link](“Server is running on [Link]
});

Output:
User Information
 coding
 reading
 hiking

[Link](‘view engine’, ‘ejs’); [Link](‘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


[Link]([Link]({ extended: true}));

// Serve HTML form


[Link](‘/’, (req, res) => {
[Link](‘
<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


[Link](‘/submit’, (req, res) => {
const { name,email } = [Link];
[Link](‘Received data: <br>Name: ${name} <br>Email : ${email}’);
});

// Start server
[Link](3000, () => {
[Link](“Server is running on [Link]
});

OUTPUT:
Form Example
Name: [__________]
Email: [_________]
[Submit]
After filling and submitting:
Received data:
Name: Disney
Email: disney@[Link]

3. Express JS – Cookies, Sessions, Authentication


Implementing cookie-based session authentication in an [Link] 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
[Link].
Session ID Cookie:
express-session automatically sets a session ID cookie (typically named [Link])
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.
[Link]:
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.
[Link]():
Used to end a session and remove its data from the session store.
[Link]():
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
[Link](cookieParser());
[Link]([Link]({ extended: true }));

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

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

// Login handler
[Link]('/login', (req, res) => {
const username = [Link];
[Link] = username;
[Link]('user', username); // Set a cookie
[Link]('/');
});

// Logout handler
[Link]('/logout', (req, res) => {
[Link]('user'); // Clear cookie
[Link](); // Destroy session
[Link]('/');
});

// Start server
[Link](3000, () => {
[Link](“Server is running on [Link]
});

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 = [Link](‘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)
[Link](‘1234’, 10, (err, hash) => {
users[0].passwordhash = hash;
});

// Middleware
[Link]([Link]({ extended: true }));
[Link](session({
secret: ‘secretkey123’,
resave: false,
saveunitialized: false
}));

/ Routes
[Link]('/', (req, res) => {
if ([Link]) {
[Link](<h2>Welcome, ${[Link]}!</h2><a
href="/logout">Logout</a>);
} else {
[Link](`<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>`);
}
});

[Link]('/login', (req, res) => {


const { username, password } = [Link];
const user = [Link](u => [Link] === username);
if (!user) {
return [Link]('Invalid username or password');
}

[Link](password, [Link], (err, result) => {


if (result) {
[Link] = [Link];
[Link] = [Link];
[Link]('/');
} else {
[Link]('Invalid username or password');
}
});
});

[Link]('/logout', (req, res) => {


[Link]();
[Link]('/');
});

[Link](3000, () => {
[Link](Server running on [Link]
});

OUTPUT:
Username:
Password:
Login

MongoDB installation process:


Step: 1 Download and install MongoDB
1) Go to this official website: [Link]
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 [Link] 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();


[Link]([Link]());

// MongoDB connection
[Link](‘mongodb://localhost:27017/mydb’, {
useNewUrlparser: true,

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

// Schema & Model


const userSchema = new [Link]({
name: String;
email: String,
age: Number
});

const User = [Link](‘User’, userSchema);

// CREATE
[Link](‘/users’, async (req, res) => {
try {
const user = new User([Link]);
await [Link]();
[Link](user);
} catch (err) {
[Link](400).send(err);
}
});

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

});

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

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

// Start Server
[Link](3000, () => {
[Link](‘Server is running on [Link]
});

OUTPUT: Welcome to the homepage!

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


RESTful APIs.
Folder structure:
spa-app/
|-----[Link]
|-----public/
|-----[Link]

[Link]:
<!DOCTYPE html>
<html>
<title>Test SPA</title>
</head>
<body>
<h1>Hello from [Link]!</h1>
</body>
</html>

[Link]:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const PORT = 3000;

let users = [];

[Link]([Link]());
[Link]([Link]('public'));

// RESTful API endpoints


[Link]('/api/public', (req, res) => {
[Link](public);
});

// Create
[Link]('/api/users', (req, res) => {
const user = [Link];
[Link](user);
[Link](201).json({ message: 'User added', user });
});

[Link]('/api/users/:id', (req, res) => {


const userId = [Link];
const updatedUser = [Link];
users = [Link]((user, index) =>
index == userId ? updatedUser : user
);
[Link]({message: 'User updated', updatedUser });
});

[Link]('/api/users/:id', (req, res) => {


const userId = [Link];
[Link](userId, 1);
[Link]({ message: 'User deleted' });
});

// Start server
[Link](3000, () =>
[Link]('Server is running on [Link]
);

OUTPUT:
Hello from [Link]

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
|-----[Link]
|-----public/
| |-----[Link]

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

[Link]:

const express = require('express');


const path = require('path');

const app = express();

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


[Link]([Link]([Link](__dirname, 'public')));

// Start the server


[Link](3000, () => {
[Link]('Server is running on [Link]
});

OUTPUT: hello from [Link]!


This HTML page is rendered using Express server

b) Write a program for writing markup with JSX.

Folder Structure:

Waiting-markup-app/
|------public/
| |------[Link]
| |------[Link]
|---------src/
| |-----[Link]
|--------[Link]
|--------[Link]
|-------- .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

[Link]:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Waiting Markup</title>
</head>
<body>
<div id="root"></div>
<script src="/[Link]"></script>
</body>
</html>

[Link]:
[Link]("root").innerHTML = "<h1>Hello, this is my
output!</h1>";

[Link]:

// src/[Link]
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 =
[Link]([Link]('root'));
[Link](<App />);

.babelrc:

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

[Link]:

const path = require('path');

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

[Link]:

const express = require('express');


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

const app = express();


const compiler = webpack(config);

[Link]('/', (req, res) => {


[Link](__dirname + '/public/[Link]');
});

[Link](webpackMiddleware(compiler));
[Link]([Link]('public'));

[Link](3000, () => {
[Link]('Server is running on [Link]
});

Output: Please wait…


Loading your content….

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


and class).

Folder structure:

My-node-app/

├── [Link]
└── components/
├── [Link]
└── [Link]

My-node-app/ [Link]:

// Importing child components


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

// Function Component: App


function App() {
[Link]("Rendering App...");

// Nesting other components


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

// Run the App


App();

My-node-app/ components/ [Link]:

// Function Component: Header


function Header() {
[Link]("Rendering Header...");
}

// Function Component: Footer


function Footer() {
[Link]("Rendering Footer...");
}

[Link] = {
Header,
Footer
};

My-node-app/components/[Link]:

// Class Component: Content


class Content {
constructor() {
[Link] = "This is the main content area.";
}

render() {
[Link]("Rendering Content...");
[Link]([Link]);
[Link]();
}

// Simulated nested component


renderNestedComponent() {
const sidebar = new Sidebar();
[Link]();
}
}

// Nested Class Component inside Content


class Sidebar {
constructor() {
[Link] = "Sidebar info here.";
}

render() {
[Link]("Rendering Sidebar...");
[Link]([Link]);
}
}

// Export function to render content


[Link] = {
Content: () => {
const content = new Content();
[Link]();
}
};

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 [Link]: Use create-react-app or Vite to build/run a frontend in a


[Link] 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/
│ └── [Link]
├── frontend/
│ ├── public/
│ │ └── [Link]
│ ├── src/
│ │ ├── [Link]
│ │ └── [Link]
└── [Link]

backend/ [Link]:
const express = require('express');
const cors = require('cors');

const app = express();


const PORT = 5000;

[Link](cors());

[Link]('/api/message', (req, res) => {


[Link]({ message: "Hello from the backend!" });
});

[Link](5000, () => {
[Link](`Backend running on [Link]
});

frontend/public/[Link]:

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

frontend/src/[Link]:

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

const App = () => {


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

useEffect(() => {
fetch('[Link]
.then(res => [Link]())
.then(data => setMessage([Link]))
.catch(err => [Link](err));
}, []);

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

export default App;

frontend/src/[Link]:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = [Link]([Link]('root'));


[Link](<App />);

frontend/[Link]:

{
"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": "[Link]
}

Output:

When fully loaded: React frontend


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

Backend running on [Link]

Frontend (react dev server):


Compiled successfully!
You can now view frontend in the browser.
Local: [Link]

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

Folder structure:

node-css-sass-app/
├── public/
│ ├── styles/
│ │ ├── [Link]
├── views/
│ └── [Link]
├── [Link]

Install packages:

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

Type this in the terminal:

sass public/styles/[Link] public/styles/[Link]

npm run sass


npm start

node-css-sass-app/public/styles/[Link]:

$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/[Link]:

<!DOCTYPE html>
<html>
<head>
<title>Styled Node App</title>
<link rel="stylesheet" href="/styles/[Link]">
</head>
<body>
<h1>Data List</h1>
<ul>
<% [Link](item => { %>
<li><%= item %></li>
<% }) %>
</ul>
</body>
</html>

node-css-sass-app/[Link]:

const express = require('express');


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

const app = express();


const port = 3000;

// Sass middleware
[Link](
sassMiddleware({
src: [Link](__dirname, 'public', 'styles'),
dest: [Link](__dirname, 'public', 'styles'),
debug: true,
outputStyle: 'compressed',
prefix: '/styles',
})
);

// Static files
[Link]([Link]([Link](__dirname, 'public')));

// Set EJS as templating engine


[Link]('view engine', 'ejs');

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

// Routes
[Link]('/', (req, res) => {
[Link]('index', { data });
});

[Link](port, () => {
[Link](`Server is running on [Link]
});

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


[Link]('greet', (name) => {
[Link](`Hello, ${name}! Welcome to the event-driven world of [Link].`);
});

// Define another event listener for 'bye'


[Link]('bye', (name) => {
[Link](`Goodbye, ${name}. See you next time!`);
});

// Emit the 'greet' event


[Link]('greet', 'Alice');

// Emit the 'bye' event


[Link]('bye', 'Alice');

Output:

Hello, Alice! Welcome to the event-driven world of [Link].


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/
│ └── [Link]
├── [Link]
└── [Link]

[Link]:

const express = require('express');


const app = express();
const port = 3000;
// Set EJS as the view engine
[Link]('view engine', 'ejs');

// Serve the index page


[Link]('/', (req, res) => {
const isLoggedIn = false; // You can change this to false to test

[Link]('index', {
user: {
name: 'John Doe',
role: 'admin',
},
isLoggedIn: isLoggedIn
});
});

[Link](port, () => {
[Link](`Server is running on [Link]
});

[Link]:

<!DOCTYPE html>
<html>
<head>
<title>Conditional Rendering</title>
</head>
<body>
<% if (isLoggedIn) { %>
<h1>Welcome, <%= [Link] %>!</h1>
<% if ([Link] === '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>

[Link]:

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

Outputs:

Output 1:

isLoggedIn is true:

isLoggedIn = true

[Link] = 'John Doe'

[Link] = 'admin'

Output 2:

isLoggedIn = false:
Please log in to continue.

b) Write a program for rendering lists.

/node-list-rendering
├── views
│ └── [Link]
└── [Link]

node-list-rendering/views/[Link]:

const express = require('express');


const app = express();
const port = 3000;
// Set EJS as the view engine
[Link]('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


[Link]('/', (req, res) => {
[Link]('users', { users });
});

[Link](port, () => {
[Link](`Server running at [Link]
});

node-list-rendering/[Link]:

<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>List of Users</h1>
<ul>
<% [Link](function(user) { %>
<li><strong><%= [Link] %></strong> - Age: <%= [Link] %></li>
<% }); %>
</ul>
</body>
</html>

Open your browser and go to:


👉 [Link]

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/ <-- [Link] + Express backend
│ └── [Link]
├── client/ <-- React frontend
│ ├── src/
│ │ └── [Link]
│ └── [Link]

form-app/server/[Link]:

const express = require('express');


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

const app = express();


const PORT = 5000;

[Link](cors());
[Link]([Link]());

// GET route
[Link]('/', (req, res) => {
[Link]('Server is up and running!');
});

// POST route for form submission


[Link]('/form-submit', (req, res) => {
[Link]('Received Form Data:', [Link]);
[Link](200).json({ message: 'Form submitted successfully', data: [Link] });
});

[Link](PORT, () => {
[Link](`Server is running at [Link]
});

Install packages:

npm init -y
npm install express cors body-parser
node [Link]
form-app/client/src/[Link]:

import React from 'react';


import './[Link]'; // optional: for external CSS

function App() {
return (
<div className="container">
{/* App Logo */}
<div className="logo-container">
<img src="/[Link]" 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/[Link]:

{
"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/
│ └── [Link]
├── src/
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ └── [Link]
├── [Link]

my-react-router-app/public/[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/[Link]" />
<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/[Link]:

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/[Link]:
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/[Link]:

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/[Link]:

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 } = [Link];
setFormData(prev => ({
...prev,
[name]: value
}));
};

// Handle form submission


const handleSubmit = (e) => {
[Link](); // Prevent page reload
[Link]('Form Submitted:', formData);
setSubmitted(true);
};

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

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

<label>Email:</label><br />
<input
type="email"
name="email"
value={[Link]}
onChange={handleChange}
required
/><br /><br />

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

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

export default Contact;

my-react-router-app/src/[Link]:

import React from 'react';


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

const root = [Link]([Link]('root'));


[Link](
<BrowserRouter>
<App />
</BrowserRouter>
);

my-react-router-app/[Link]:
{
"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


[Link]('\x1B[?25l');

function updateScreen() {
[Link]([Link], 0, 0); // Move cursor to top-left
[Link]([Link]); // Clear screen

const now = new Date();


[Link]('📅 Current Time:');
[Link]([Link]());

[Link]('\nScreen updates every second...');


}

// Initial update
updateScreen();

// Update screen every second


setInterval(updateScreen, 1000);

// Optional: Handle Ctrl+C gracefully


[Link]('SIGINT', () => {
[Link]([Link], 0);
[Link]([Link]);
[Link]('\x1B[?25h'); // Show cursor again
[Link]('\nExiting...');
[Link]();
});

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: [Link]
const mongoose = require('mongoose');

[Link]('mongodb://localhost:27017/hookDemo', {
useNewUrlParser: true,
useUnifiedTopology: true
});

const userSchema = new [Link]({


name: String,
email: String
});

// Pre-save hook (before saving)


[Link]('save', function (next) {
[Link](`📥 About to save user: ${[Link]}`);
next();
});

// Post-save hook (after saving)


[Link]('save', function (doc, next) {
[Link](`✅ User saved: ${[Link]}`);
next();
});

const User = [Link]('User', userSchema);

async function createUser() {


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

createUser().then(() => [Link]());


Output:

📥 About to save user: Alice


✅ User saved: Alice

b) Write a program for sharing data between components.

Folder structure:

node-shared-data-example

├── [Link]

├── [Link]

├── [Link]

└── [Link]

node-shared-data-example/[Link]:

// [Link]
const data = {
message: "Initial message"
};

[Link] = {
getMessage: () => [Link],
setMessage: (newMessage) => {
[Link] = newMessage;
}
};

node-shared-data-example/[Link]:

// [Link]
const sharedData = require('./sharedData');

function updateMessage() {
[Link]("Updated by writer module");
[Link]("✅ Message updated in writer");
}

[Link] = updateMessage;

node-shared-data-example/[Link]:
// [Link]
const sharedData = require('./sharedData');

function readMessage() {
[Link]("📩 Reader got message:", [Link]());
}

[Link] = readMessage;

node-shared-data-example/[Link]:

// [Link]
const updateMessage = require('./writer');
const readMessage = require('./reader');

[Link]("🔹 Before update:");


readMessage(); // Reads the initial message

[Link]("🔹 Updating message...");


updateMessage(); // Writer updates the message

[Link]("🔹 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: [Link]
 Sign up for a free account
 Whitelist your IP and create a user/password.
 Copy your connection string (something like
mongodb+srv://<user>:<pass>@[Link]/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 [Link] (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>@[Link]/database_name?
retryWrites=true&w=majority

Replace <password> with your actual password

Folder structure:

mongo-node-crud

|-------- .env
|-------- [Link]

Install packages: npm install express mongoose dotenv

mongo-node-crud/[Link]:

const express = require('express');


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

const app = express();


const PORT = [Link] || 5000;

[Link]([Link]());

[Link]('/', (req, res) => {


[Link]('API is working');
});

// 👇 Connect to MongoDB Atlas


[Link]([Link].MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
[Link]('✅ Connected to MongoDB Atlas');
[Link](PORT, () => {
[Link]('Server running on [Link]
});
})
.catch((err) => {
[Link]('❌ MongoDB connection error:', err);
});

mongo-node-crud/ .env :

MONGO_URI=mongodb+srv://admin:admin123@[Link]/
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

|----- [Link]

Install package: npm install mongodb

mongo-native-crud/[Link]:

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

const uri = [Link].MONGO_URI;


const dbName = [Link].DB_NAME;

async function main() {


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

try {
await [Link]();
[Link]('✅ Connected to MongoDB');

const db = [Link](dbName);
const users = [Link]('users');

// ----------------------------
// 🔽 INSERT - insertOne()
// ----------------------------
const newUser = { name: 'Alice', email: 'alice@[Link]', age: 25 };
const insertResult = await [Link](newUser);
[Link]('✅ Inserted:', [Link]);

// ----------------------------
// 🔍 READ - find()
// ----------------------------
const allUsers = await [Link]().toArray();
[Link]('📄 All Users:', allUsers);

// ----------------------------
// ✏️UPDATE - updateOne()
// ----------------------------
const updateResult = await [Link](
{ _id: [Link] },
{ $set: { age: 30 } }
);
[Link]('✏️Updated:', [Link], 'document(s)');
// ----------------------------
// ❌ DELETE - remove() is deprecated, use deleteOne()
// ----------------------------
const deleteResult = await [Link]({ _id: [Link] });
[Link](' Deleted:', [Link], 'document(s)');

} catch (err) {
[Link]('❌ Error:', err);
} finally {
await [Link]();
[Link]('🔌 Disconnected');
}
}

main();

mongo-native-crud/ .env:

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

Output:

📄 All Users: [

_id: new ObjectId('6891d91b378e9711c29422ee'),

name: 'Alice',

email: 'alice@[Link]',

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

|------ [Link]

Install package: npm install mongodb

program11a/ .env:

MONGO_URI=mongodb://localhost:27017

program11a/[Link]:

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

const uri = [Link].MONGO_URI;

async function main() {


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

try {
await [Link]();
[Link]('✅ Connected to MongoDB');

// 📂 Create a Database and Collection


const db = [Link]('schoolDB'); // Create/use database
const students = [Link]('students'); // Create/use collection

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


await [Link]({ name: 'Alice', age: 20 });
[Link]('📁 Database and collection created with one document');

// 🔥 Drop Collection
const dropCollectionResult = await [Link]('students').drop();
[Link](' Collection dropped:', dropCollectionResult); // true

// 🔥 Drop Database
const dropDbResult = await [Link]();
[Link](' Database dropped:', dropDbResult); // true
} catch (err) {
[Link]('❌ Error:', err);
} finally {
await [Link]();
[Link]('🔌 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

|------ [Link]

mongo-queries/ .env:

MONGO_URI=mongodb://localhost:27017

mongo-queries/ [Link]:

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

const uri = [Link].MONGO_URI;

async function main() {


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

try {
await [Link]();
[Link]('✅ Connected to MongoDB');

const db = [Link]('companyDB');
const employees = [Link]('employees');
// 🔁 Insert sample records
await [Link]([
{ 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 }
]);
[Link]('📥 Sample data inserted');

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


const all = await [Link]().toArray();
[Link]('\n📄 All Employees:', all);

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


const limited = await [Link]().limit(2).toArray();
[Link]('\n📦 Limited (2) Employees:', limited);

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


const sorted = await [Link]().sort({ salary: -1 }).toArray();
[Link]('\n📊 Sorted by salary (desc):', sorted);

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


const indexResult = await [Link]({ dept: 1 });
[Link]('\n⚙️Index created on dept:', indexResult);

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


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

} catch (err) {
[Link]('❌ Error:', err);
} finally {
await [Link]();
[Link]('\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/

│ └── [Link]

├── public/

│ └── [Link]

├── [Link]

├── [Link]

Install packages:

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

todo-app/views/[Link]:

<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" href="/[Link]">
</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>
<% [Link](task => { %>
<li>
<%= [Link] %>
<a href="/complete/<%= task._id %>">Complete</a>
<form action="/complete/<%= [Link] %>" method="POST";
style="display:inline;">
<button type="submit">
<% if ([Link]) { %> ☐
<% } else { %> ☐ <% } %>
</button>
</form>

<span style "<%= [Link] ? 'text-decoration:line-through; ' : '' %>">


<%= [Link] %>
</span>

<form action="/delete/<%= [Link] %>" method="POST"


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

todo-app/public/[Link]:

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/[Link]:

// [Link]
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
[Link]([Link]({ extended: true }));
[Link]([Link]('public'));
[Link]('view engine', 'ejs');

// Routes
[Link]('/', (req, res) => {
[Link]('index', { tasks });
});

[Link]('/add', (req, res) => {


const newTask = {
id: uuidv4(),
title: [Link],
completed: false
};
[Link](newTask);
[Link]('/');
});

[Link]('/complete/:id', (req, res) => {


const task = [Link](t => [Link] === [Link]);
if (task) [Link] = ![Link];
[Link]('/');
});

[Link]('/delete/:id', (req, res) => {


tasks = [Link](t => [Link] !== [Link]);
[Link]('/');
});
// Start server
[Link](port, () => {
[Link](`To-Do App running at [Link]
});

todo-app/[Link]:

{
"name": "todo-app",
"version": "1.0.0",
"description": "A simple to-do list app using [Link] and [Link]",
"main": "[Link]",
"scripts": {
"start": "node [Link]"
},
"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