Full Stack Web Lab Manual GPR
Full Stack Web Lab Manual GPR
</body>
</html>
Output:
.job h3 {
margin-top: 0;
}
.skills ul,
.certifications ul {
list-style-type: none;
padding: 0;
4. Write a to build a resume using html and css }
<!DOCTYPE html>
<html lang="en"> .skills li,
<head> .certifications li {
<meta charset="UTF-8"> margin-bottom: 10px;
<meta name="viewport" content="width=device-width, }
initial-scale=1.0">
<title>Visual Resume</title> .skills li::before,
<style> .certifications li::before {
body { content: attr(data-skill) ": ";
font-family: Arial, sans-serif; font-weight: bold;
margin: 0; }
padding: 0;
} .certifications li::before {
content: attr(data-certification) ": ";
.container { font-weight: bold;
max-width: 800px; }
margin: 20px auto;
padding: 20px; .awards ul {
background-color: #f9f9f9; list-style-type: none;
border-radius: 8px; padding: 0;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); }
}
.awards li {
header h1 { margin-bottom: 10px;
margin: 0; }
color: #333;
}
<ul>
<li data-certification="Certification Name
.awards li::before { 1">May 2020</li>
content: attr(data-award) ": "; <li data-certification="Certification Name
font-weight: bold; 2">June 2021</li>
} <!-- Add additional certification entries here if
needed -->
.declaration { </ul>
margin-top: 20px; </section>
border-top: 2px solid #ccc; <section class="section awards">
padding-top: 20px; <h2>Awards & Honors</h2>
} <ul>
</style> <li data-award="Dean's List">New York
</head> University</li>
<body> <li data-award="Outstanding Achievement in
<div class="container"> Software Engineering">XYZ Software Company</li>
<header> <!-- Add additional award entries here if needed
<h1>G. Pradeep Reddy</h1> -->
<p>Software Engineer</p> </ul>
</header> </section>
<section class="section about"> <section class="section contact">
<h2>Objective</h2> <h2>Contact</h2>
<p>Software Engineer with a passion for <p>Phone: (123) 456-7890</p>
developing robust and scalable software solutions. <p>Email: [email protected]</p>
Experienced in full-stack development and proficient in <p>LinkedIn: <a
various programming languages and technologies.</p> href="https://www.linkedin.com/in/gpradeep/">linkedin.c
</section> om/in/gpradeep/</a></p>
<section class="section education"> </section>
<h2>Education</h2> <section class="section experience">
<div class="job"> <h2>Professional Experience</h2>
<h3>New York University</h3> <div class="job">
<p>New York, NY</p> <h3>ABC Software Solutions</h3>
<p>Bachelor of Science, Computer Science</p> <p>New York, NY</p>
<p>Honors: magna cum laude (GPA: <p>Software Engineer</p>
3.8/4.0)</p> <p>September 2021 – Present</p>
</div> <ul>
<!-- Add additional education entries here if needed <li>Designed and developed scalable web
--> applications using Java, Spring Boot, and React.js</li>
</section> <li>Collaborated with cross-functional teams
<section class="section skills"> to deliver high-quality software solutions within project
<h2>Relevant Skills</h2> deadlines</li>
<ul> <li>Implemented unit tests and participated in
<li data-skill="Java">90%</li> code reviews to ensure code quality and
<li data-skill="JavaScript">85%</li> maintainability</li>
<li data-skill="Python">80%</li> </ul>
<li data-skill="HTML/CSS">85%</li> </div>
<li data-skill="React.js">85%</li> <div class="job">
<li data-skill="Node.js">80%</li> <h3>XYZ Tech</h3>
<!-- Add additional skills here if needed --> <p>New York, NY</p>
</ul> <p>Software Development Intern</p>
</section> <p>June 2020 – August 2021</p>
<section class="section certifications"> <ul>
<h2>Certifications</h2> <li>Assisted in the development of RESTful
APIs using Node.js and Express.js</li> 5. Create a html css and java script program to accept
<li>Contributed to the frontend development payment by debit and credit card.
using HTML, CSS, and JavaScript frameworks</li> <!DOCTYPE html>
<li>Participated in agile development <html lang="en">
processes including sprint planning, daily stand-ups, and <head>
retrospectives</li> <meta charset="UTF-8">
</ul> <meta name="viewport" content="width=device-width,
</div> initial-scale=1.0">
</section> <title>Payment Page</title>
<section class="section declaration"> <style>
<h2>Declaration</h2> body {
<p>I hereby declare that the above-mentioned font-family: Arial, sans-serif;
information is correct up to my knowledge and I bear the background-color: #f4f4f4;
responsibility for the correctness of the above-mentioned margin: 0;
particulars.</p> padding: 0;
</section> display: flex;
</div> justify-content: center;
</body> align-items: center;
</html> height: 100vh;
}
.payment-container {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
padding: 20px;
text-align: center;
}
h1 {
margin-top: 0;
color: #333;
}
input[type="number"],
input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border-radius: 4px;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
var creditCard =
button:hover { document.getElementById('creditCard');
background-color: #0056b3;
} if (debitCard.checked) {
cardNumberInput.style.display = 'block';
.success-message { cvvInput.style.display = 'block';
color: #4caf50; } else if (creditCard.checked) {
font-weight: bold; cardNumberInput.style.display = 'block';
} cvvInput.style.display = 'none';
</style> } else {
</head> cardNumberInput.style.display = 'none';
<body> cvvInput.style.display = 'none';
<div class="payment-container"> }
<h1>Payment Page</h1> }
<label for="debitCard">Debit Card</label>
<input type="radio" id="debitCard" function makePayment() {
name="paymentType" value="debit" var amount =
onchange="showCardInput()"> document.getElementById('amount').value;
<label for="creditCard">Credit Card</label> var cardNumber =
<input type="radio" id="creditCard" document.getElementById('cardNumber').value;
name="paymentType" value="credit" var cvv = document.getElementById('cvv').value;
onchange="showCardInput()"> var paymentType =
<br> document.querySelector('input[name="paymentType"]:ch
<div id="cardNumberInput" style="display: none;"> ecked').value;
<label for="cardNumber">Card Number:</label>
<input type="text" id="cardNumber" if (!validateCardNumber(cardNumber)) {
placeholder="Enter card number"> alert('Please enter a valid card number.');
<br> return;
</div> }
<div id="cvvInput" style="display: none;">
<label for="cvv">CVV:</label> if (paymentType === 'debit' && cvv.trim() === '')
<input type="text" id="cvv" placeholder="Enter {
CVV"> alert('Please enter CVV.');
<br> return;
</div> }
<label for="amount">Enter Amount:</label>
<input type="number" id="amount" // Simulate payment process (in real-world
placeholder="Enter amount" min="1"> application, this would be done server-side)
<br> setTimeout(function() {
<button onclick="makePayment()">Pay var message = 'Payment of $' + amount + '
Now</button> successful!';
<div id="successMessage" class="success-message" if (cardNumber) {
style="display: none;"></div> message += ' Card Number: ' + cardNumber;
</div> }
if (paymentType === 'debit' && cvv) {
<script> message += ' CVV: ' + cvv;
function showCardInput() { }
var cardNumberInput =
document.getElementById('cardNumberInput'); document.getElementById('successMessage').innerHTML
var cvvInput = = message;
document.getElementById('cvvInput');
var debitCard = document.getElementById('successMessage').style.displa
document.getElementById('debitCard'); y = 'block';
}, 1000); // Simulating a delay of 1 second for Karnataka.html
payment processing <HTML>
} <HEAD>
<TITLE>About Karnataka</TITLE> </HEAD>
function validateCardNumber(cardNumber) { <BODY>
// Simple validation (for demonstration purposes <CENTER><H1>Karnataka</H1></CENTER>
only) <HR>
return cardNumber.length === 16 && <UL>
!isNaN(cardNumber); <LI>Area : 1,91,791 Sq. Kms</LI>
} <LI>Capital : Bangalore</LI>
</script> <LI>Language : Kannada</LI>
</body> <LI>Population : 5,27,33,958</LI>
</html> </UL>
<hr>
<a href='ImageMap.html'>India Map</a>
</BODY>
</HTML>
Andhrapradesh.html
<HTML>
<HEAD>
<TITLE>About Andhra Pradesh</TITLE> </HEAD>
<BODY>
<CENTER><H1>Andhra Pradesh</H1></CENTER>
<HR>
<UL>
<LI>Area : 2,75,068 Sq. Kms</LI>
6. Create a web page which includes a map and display the <LI>Capital : Vishakapatnam</LI>
related information when a hot spot is clicked in the map. <LI>Language : Telugu</LI>
Imagemap.html <LI>Population : 7,57,27,541</LI>
<HTML> </UL>
<HEAD> <hr>
<TITLE>Image Map</TITLE> </HEAD> <a href='ImageMap.html'>India Map</a>
<BODY> </BODY>
<img src="india_map.jpg" usemap="#metroid" </HTML>
ismap="ismap" > <map name="metroid" Telengana.html
id="metroid"> <HTML>
<area href="Telengana.html" shape="rect" <HEAD>
coords="230,501,276,539" title="Telengana"/> <TITLE>About Telengana</TITLE> </HEAD>
<area href="AndhraPradesh.html" shape="rect" coords = <BODY>
"277,574,238,606" title ="Andhra Pradesh" /> <CENTER><H1>Telengana</H1></CENTER> <HR>
<area href="Karnataka.html" shape="rect" coords = <UL>
"195,576,156,608" title ="Karnataka" /> <LI>Area : 2,75,068 Sq. Kms</LI>
<area href="TamilNadu.html" shape="rect" <LI>Capital : Hyderabad</LI>
coords="277,660,225,705" title="TamilNadu"/> <LI>Language : Telugu</LI>
<area href="Kerala.html" shape="poly" coords = <LI>Population : 7,57,27,541</LI>
"162,647,207,691,209,753" title ="Kerala" /> </map> </UL>
</BODY> <hr>
</HTML> <a href='ImageMap.html'>India Map</a>
</BODY>
</HTML>
Kerala.html 7. Create a photo gallery using HTML, CSS, and
<HTML> JavaScript. Add functionality to allow users to filter and
<HEAD> sort images based on different criteria.
<TITLE>About Kerala</TITLE> <!DOCTYPE html>
</HEAD> <html lang="en">
<BODY> <head>
<CENTER> <meta charset="UTF-8">
<H1>Kerala</H1></CENTER> <meta name="viewport" content="width=device-width,
<HR> initial-scale=1.0">
<UL> <title>Photo Gallery</title>
<LI>Area : 38,863 Sq. Kms.</LI> <style>
<LI>Capital : Thiruvananthapuram</LI> /* Styles for gallery */
<LI>Language : Malayalam</LI> .gallery {
<LI>Population : 3,18,38,619</LI> display: grid;
</UL> grid-template-columns: repeat(auto-fill,
<hr> minmax(200px, 1fr));
<a href='ImageMap.html'>India Map</a> grid-gap: 10px;
</BODY></HTML> }
Output:
Note: .gallery-item {
You can use https://www.image-map.net/ to find display: block;
coordinates from any map border: 1px solid #ccc;
padding: 10px;
text-align: center;
}
.gallery-item img {
max-width: 100%;
height: auto;
}
.controls select {
padding: 5px;
font-size: 16px;
}
</style>
</head>
<body>
<div class="controls">
<label for="filter">Filter by:</label>
<select id="filter">
<option value="all">All</option>
<option value="nature">Nature</option>
<option value="city">City</option>
<option value="animals">Animals</option>
</select>
<label for="sort">Sort by:</label> a.querySelector('img').alt.toUpperCase();
<select id="sort"> const nameB =
<option value="none">None</option> b.querySelector('img').alt.toUpperCase();
<option value="name">Name</option> return nameA.localeCompare(nameB);
<option value="date">Date</option> });
</select> } else if (criteria === 'date') {
</div> items.sort((a, b) => {
const dateA = new
<div class="gallery" id="gallery"> Date(a.querySelector('img').getAttribute('src'));
<div class="gallery-item nature"> const dateB = new
<img src="nature1.jpg" alt="Nature 1"> Date(b.querySelector('img').getAttribute('src'));
</div> return dateA - dateB;
<div class="gallery-item city"> });
<img src="city1.jpg" alt="City 1"> }
</div>
<div class="gallery-item animals"> items.forEach(item => gallery.appendChild(item));
<img src="animals1.jpg" alt="Animals 1"> });
</div> </script>
<!-- Add more images here -->
</div> </body>
</html>
<script> Output:
// Filter images based on category
document.getElementById('filter').addEventListener('chang
e', function() {
const category = this.value;
const items = document.querySelectorAll('.gallery-
item');
items.forEach(item => {
if (category === 'all' ||
item.classList.contains(category)) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
});
});
document.getElementById('sort').addEventListener('change'
, function() {
const criteria = this.value;
const gallery = document.getElementById('gallery');
const items =
Array.from(gallery.getElementsByClassName('gallery-
item'));
// Main code
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
4. Node.js script that reads the name of a directory from the output: process.stdout
command-line arguments and displays the list of directory });
contents using the fs module.
listDirectoryContents.js rl.question("Enter the current date (DD-MM-YY): ",
var fs = require("fs"); (currentDateInput) => {
const [day, month, year] = currentDateInput.split('-
if (process.argv.length <= 2) {
').map(Number);
console.log("Usage: node listDirectoryContents.js
const currentDate = new Date(year + 2000, month - 1,
<Path/to/directory>");
day); // Month is 0-based index in JavaScript Date object
process.exit(-1);
}
const diffDaysNewYear =
daysUntilNewYear(currentDate);
var path = process.argv[2];
console.log('Number of Days till New Year: ' +
diffDaysNewYear);
fs.readdir(path, function(err, items) {
if (err) {
rl.close();
console.log("Error:", err);
});
} else {
console.log("Directory contents:", items);
for (var i = 0; i < items.length; i++) {
console.log(items[i]); 5. Create a Chat application using Node JS
} server.js:
} const express = require('express');
}); const bodyParser = require('body-parser');
5. Function calculates the number of days until New Year's const EventEmitter = require('events');
Day (January 1st) of the next year.
// Combined program const app = express();
const port = 3000;
// Define the daysUntil function to calculate the number of
days until a target date // Create an EventEmitter to handle chat messages
const daysUntil = (currentDate, targetDate) => { const chatEmitter = new EventEmitter();
const oneDay = 24 * 60 * 60 * 1000; // hours * minutes *
seconds * milliseconds // Middleware to parse JSON bodies
const diffDays = app.use(bodyParser.json());
Math.round(Math.abs((currentDate.getTime() -
targetDate.getTime()) / oneDay)); // Route to handle incoming chat messages
return diffDays; app.post('/chat', (req, res) => {
}; const { message } = req.body;
chatEmitter.emit('message', message);
res.sendStatus(200); const form = document.getElementById('form');
}); const input = document.getElementById('input');
// Server-Sent Events (SSE) route to stream chat messages // Function to add a new message to the chat
to clients function addMessage(message) {
app.get('/sse', (req, res) => { const p = document.createElement('p');
res.setHeader('Content-Type', 'text/event-stream'); p.textContent = message;
res.setHeader('Cache-Control', 'no-cache'); messagesDiv.appendChild(p);
res.setHeader('Connection', 'keep-alive'); }
// Event listener for the form submission
const messageHandler = (message) => { form.addEventListener('submit', function (evt) {
res.write(`data: ${message}\n\n`); evt.preventDefault();
}; const message = input.value.trim();
if (message !== '') {
// Listen for incoming chat messages and send them to addMessage(message);
the client sendMessage(message);
chatEmitter.on('message', messageHandler); input.value = '';
}
// Remove the message handler when the client });
disconnects // Function to send a message to the server
req.on('close', () => { function sendMessage(message) {
chatEmitter.off('message', messageHandler); // Here you would send an HTTP request to your
}); server to handle the message
}); // For example, you can use fetch or
XMLHttpRequest
// Serve static files (HTML, CSS, JavaScript) // Example using fetch:
app.use(express.static('public')); fetch('/chat', {
method: 'POST',
// Start the server headers: {
app.listen(port, () => { 'Content-Type': 'application/json'
console.log(`Server running at http://localhost:${port}`); },
}); body: JSON.stringify({ message })
index.html: })
<!DOCTYPE html> .then(response => {
<html lang="en"> if (!response.ok) {
<head> throw new Error('Failed to send message to
<meta charset="UTF-8"> server');
<title>Chat App</title> }
<link rel="stylesheet" href="styles.css"> })
</head> .catch(error => {
<body> console.error('Error sending message:', error);
<div id="messages"> });
<h4>Chat Messages</h4> }
</div>
<form id="form"> // Function to handle incoming messages from the
<input id="input" type="text" placeholder="Your server (using SSE)
message..."> const eventSource = new EventSource('/sse');
<button type="submit">Send</button> eventSource.onmessage = function (event) {
</form> addMessage(event.data);
};
<script> </script>
const messagesDiv = </body>
document.getElementById('messages'); </html>
styles.css Server.js
/* styles.css */ const fs = require('fs');
body { const express = require('express');
font-family: Arial, sans-serif; const EventEmitter = require('events');
}
const chatEmitter = new EventEmitter();
#messages { const port = process.env.PORT || 1337;
margin-bottom: 20px; const app = express();
}
app.get('/', (req, res) => {
#input { res.sendFile( dirname + '/index.html');
margin-right: 10px; });
}
app.get('/sse', (req, res) => {
(Or) res.writeHead(200, {
Index.html 'Content-Type': 'text/event-stream',
<!DOCTYPE html> 'Connection': 'keep-alive'
<html lang="en"> });
<head>
<meta charset="UTF-8"> const onMessage = msg => res.write(`data:
<title>Chat App</title> ${msg}\n\n`);
<link rel="stylesheet" href="tachyons.min.css"> chatEmitter.on('message', onMessage);
<link rel="stylesheet" href="chat.css">
</head> res.on('close', function () {
<body> chatEmitter.off('message', onMessage);
<div id="messages"> });
<h4>Chat Messages</h4> });
</div>
<form id="form"> app.get('/chat', (req, res) => {
<input id="input" type="text" placeholder="Your const { message } = req.query;
message..."> chatEmitter.emit('message', message);
<button type="submit">Send</button> res.end();
</form> });
<script src='chat.js'></script>
</body> app.listen(port, () => {
</html> console.log(`Server listening on port ${port}`);
Chat.js });
// chat.js Chat.css
new EventSource('/sse').onmessage = function (event) { /* styles.css */
document.getElementById('messages').innerHTML += body {
`<p>${event.data}</p>`; font-family: Arial, sans-serif;
}; }
document.getElementById('form').addEventListener('submi #messages {
t', function (evt) { margin-bottom: 20px;
evt.preventDefault(); }
const message =
document.getElementById('input').value.trim(); #input {
if (message !== '') { margin-right: 10px;
fetch('/chat?message=' + }
encodeURIComponent(message));
document.getElementById('input').value = '';
}});
Output:
button:hover {
background-color: #e6e6e6;
}
button:active {
transform: translateY(1px);
}
3. Develop a simple Angular JS calculator application that
can perform basic mathematical operations (addition, button.operator {
subtraction, multiplication, division) based on user input. background-color: #ff6347;
<!DOCTYPE html> color: white;
<html ng-app="calculatorApp"> border-color: #ff6347;
<head> }
<title>AngularJS Calculator App</title>
<style> button.operator:hover {
#calculator { background-color: #ff6347;
width: 300px; }
margin: auto; </style>
border: 1px solid #ccc; <script
padding: 10px; src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/
border-radius: 5px; angular.min.js"></script>
text-align: center; </head>
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); <body>
$scope.performOperation = function (operator) {
<div ng-controller="calculatorCtrl" id="calculator"> $scope.appendToDisplay(' ' + operator + ' ');
<h2>Simple Calculator</h2> };
<div class="row">
<button ng-click="appendToDisplay('7')">7</button>
<button ng-click="appendToDisplay('8')">8</button>
<button ng-click="appendToDisplay('9')">9</button>
<button ng-click="performOperation('*')"
class="operator">*</button>
</div>
<div class="row">
<button ng-click="appendToDisplay('0')">0</button>
<button ng-click="clearDisplay()">C</button>
<button ng-click="calculateResult()"
class="operator">=</button>
<button ng-click="performOperation('/')"
class="operator">/</button>
</div>
</div>
<script>
var app = angular.module('calculatorApp', []);
$scope.clearDisplay = function () {
$scope.display = '';
};
4. Write an AngularJS program to create a simple CRUD <input type="email" id="userEmail" ng-
application (Create, Read, Update, and Delete) for model="newUser.email" required>
managing users. <button type="submit">Add User</button>
<!DOCTYPE html> </form>
<html ng-app="crudApp">
<head> <table ng-show="users.length > 0">
<title>AngularJS CRUD Application</title> <tr>
<style> <th>Name</th>
#userList { <th>Email</th>
width: 600px; <th>Actions</th>
margin: auto; </tr>
border: 1px solid #ccc; <tr ng-repeat="user in users">
border-radius: 5px; <td>{{ user.name }}</td>
padding: 20px; <td>{{ user.email }}</td>
margin-top: 20px; <td>
} <button ng-click="editUser(user)">Edit</button>
<button ng-
table { click="deleteUser(user)">Delete</button>
width: 100%; </td>
border-collapse: collapse; </tr>
margin-top: 10px; </table>
} </div>
<script>
th, td { var app = angular.module('crudApp', []);
border: 1px solid #ddd;
padding: 8px; app.controller('crudCtrl', function ($scope) {
text-align: left; $scope.users = [
} { name: 'G. Pradeep Reddy', email:
'[email protected]' },
button { { name: 'G. Diwakar Reddy', email:
background-color: darkblue; '[email protected]' }
color: #fff; ];
border: none;
padding: 5px 10px; $scope.newUser = {};
border-radius: 3px;
cursor: pointer; $scope.addUser = function () {
} if ($scope.newUser.name && $scope.newUser.email)
</style> {
<script $scope.users.push(angular.copy($scope.newUser));
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/a $scope.newUser = {};
ngular.min.js"></script> }
</head> };
<body>
$scope.editUser = function (user) {
<div ng-controller="crudCtrl" id="userList"> var editedName = prompt("Edit user's name:",
<h2>Users List</h2> user.name);
var editedEmail = prompt("Edit user's email:",
<form ng-submit="addUser()"> user.email);
<label for="userName">Name:</label>
<input type="text" id="userName" ng- if (editedName !== null && editedEmail !== null) {
model="newUser.name" required> user.name = editedName;
user.email = editedEmail;
<label for="userEmail">Email:</label> }
}; import React, { Component } from "react";
import "./index.css";
$scope.deleteUser = function (user) { import {create, all} from "mathjs"; // Import the
var confirmDelete = confirm("Are you sure you want to mathjs library for calculations
delete this user?"); const math = create(all, {});
if (confirmDelete) { class App extends Component {
var index = $scope.users.indexOf(user); constructor() {
$scope.users.splice(index, 1); super();
} this.state = { operations: [] };
}; }
});
</script> handleClick = (e) => {
</body> const value = e.target.getAttribute("data-value");
</html> switch (value) {
Output: case "clear":
this.setState({ operations: [] });
break;
case "equal":
this.calculateOperations();
break;
default:
const newOperations = [...this.state.operations,
value];
this.setState({
operations: newOperations,
});
break;
}
};
calculateOperations = () => {
let result = this.state.operations.join("");
if (result) {
result = math.evaluate(result); // Use
math.evaluate instead of math.eval
result = math.format(result, { precision: 14 });
result = String(result);
this.setState({ operations: [result] });
}
};
React JS: render() {
return (
1. Write a program to create a simple calculator Application <div className="App">
using React JS <Display data={this.state.operations} />
• Install mathjs library in your project <Buttons>
• Update the import statement in your code to import <Button onClick={this.handleClick}
the necessary functions from libraries label="C" value="clear" />
<Button onClick={this.handleClick} label="7"
value="7" />
<Button onClick={this.handleClick} label="8"
value="8" />
<Button onClick={this.handleClick} label="9"
value="9" />
<Button onClick={this.handleClick} label="/"
value="/" />
return <div className="Display">{string}</div>;
<Button onClick={this.handleClick} label="4" value="4" /> }
<Button onClick={this.handleClick} label="5" }
value="5" />
<Button onClick={this.handleClick} label="6" export default App;
value="6" />
<Button onClick={this.handleClick} label="" CSS file:
value="" /> .App {
<Button onClick={this.handleClick} label="1" width: 300px;
value="1" /> margin: auto;
<Button onClick={this.handleClick} label="2" padding: 20px;
value="2" /> border: 2px solid #ccc;
<Button onClick={this.handleClick} label="3" border-radius: 8px;
value="3" /> background-color: #20af1d;
<Button onClick={this.handleClick} label="-" }
value="-" />
<Button onClick={this.handleClick} label="0" .Buttons {
value="0" /> display: grid;
<Button onClick={this.handleClick} label="." grid-template-columns: repeat(4, 1fr);
value="." /> grid-gap: 10px;
<Button onClick={this.handleClick} label="=" }
value="equal" />
<Button onClick={this.handleClick} label="+" .Button {
size="2" value="+" /> cursor: pointer;
{/* Other button components */} padding: 10px;
</Buttons> text-align: center;
</div> border: 1px solid #ccc;
); border-radius: 5px;
} background-color:aqua;
} transition: background-color 0.3s ease;
}
class Buttons extends Component {
render() { .Button:hover {
return <div background-color: #f0f0f0;
className="Buttons">{this.props.children}</div>; }
}
} .Display {
margin-bottom: 10px;
class Button extends Component { padding: 10px;
render() { border: 1px solid #ccc;
return ( border-radius: 5px;
<div background-color: yellow;
onClick={this.props.onClick} text-align: right;
className="Button" font-size: 1.5em;
data-size={this.props.size} min-height: 40px;
data-value={this.props.value} display: flex;
> align-items: center;
{this.props.label} justify-content: flex-end;
</div> }
);
}
}
return (
<div className="app">
<h1>Vote for your favorite candidate</h1>
<div className="candidates-container">
{candidates.map((candidate) => (
<div key={candidate.id}
className="candidate">
<div>{candidate.name}</div>
<button onClick={() =>
handleVote(candidate.id)}>Vote</button>
<div
className="votes">{candidate.votes}</div>
2. Write a program to create a voting application using
</div>
React JS
))}
</div>
import React, { useState } from "react";
<button onClick={handleReset}>Reset</button>
import "./index.css";
</div>
// Import your CSS file
);
}
function App() {
const [candidates, setCandidates] = useState([
export default App;
{ id: 1, name: "Candidate 1", votes: 0 },
{ id: 2, name: "Candidate 2", votes: 0 },
{ id: 3, name: "Candidate 3", votes: 0 },
]);
h1 {
color: #333;
}
.candidates-container {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
}
.candidate {
margin: 20px;
padding: 20px;
background-color: #f0f0f0;
border-radius: 10px;
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
}
button {
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50; /* Green */
border: none;
color: white;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.votes {
font-size: 24px;
color: #333;
}
Expressjs
1. Write a express js program that accepts form content and
Displays on screen using get method.
<!DOCTYPE html>
<html>
<body>
<form action="http://127.0.0.1:8000/get_example">
<table>
<tr><td>Enter First Name:</td><td><input type="text"
name="firstname"/><td></tr>
<tr><td>Enter Last Name:</td><td><input type="text"
name="lastname"/><td></tr>
<tr><td>Enter Password:</td><td><input type="password"
name="password"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"> Male
<input type="radio" name="sex" value="female">Female
</td></tr>
<tr><td>About You :</td><td>
<textarea rows="5" cols="40" name="aboutyou"
placeholder="Write about yourself">
</textarea>
</td></tr>
<tr><td colspan="2"><input type="submit"
value="register"/></td></tr>
</table>
</form> 2. Write a express js program that accepts form content
</body> and Displays on screen using POST method.
</html> <html>
get_example.js <body>
<form action="http://127.0.0.1:8000/process_post"
var express = require('express'); method="POST">
var app=express(); First Name: <input type="text" name="first_name">
<br>
app.get('/get_example3', function (req, res) { Last Name: <input type="text" name="last_name">
res.send('<p>Firstname: ' + req.query['firstname']+'</p> <input type="submit" value="Submit">
<p>Lastname: '+req.query['lastname']+'</p><p>Password: </form>
'+req.query['password']+'</p> </body>
<p>AboutYou: '+req.query['aboutyou']+'</p>'); </html>
}) post_example1.js
var server = app.listen(8000, function () {
var host = server.address().address var express = require('express');
var port = server.address().port var app = express();
console.log("Example app listening at http://%s:%s", host, var bodyParser = require('body-parser');
port) // Create application/x-www-form-urlencoded parser
}) var urlencodedParser = bodyParser.urlencoded({
extended: false })
app.use(express.static('public'));
app.get('/index.html', function (req, res) {
res.sendFile( dirname + "/" + "index.html" );
})
app.post('/process_post', urlencodedParser, function (req, Get cookie:
res) { Now open http://127.0.0.1:8000/cookieget to get the
// Prepare output in JSON format cookie:
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8000, function () { cookies_example.js
var host = server.address().address
var port = server.address().port var express = require('express');
console.log("Example app listening at http://%s:%s", host, var cookieParser = require('cookie-parser');
port) var app = express();
}) app.use(cookieParser());
app.get('/cookieset',function(req, res){
res.cookie('cookie_name', 'cookie_value');
res.cookie('company', 'javatpoint');
res.cookie('name', 'sonoo');
res.status(200).send('Cookie is set');
});
app.get('/cookieget', function(req, res) {
res.status(200).send(req.cookies);
});
app.get('/', function (req, res) {
res.status(200).send('Welcome to JavaTpoint!');
});
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host,
port);
});
3. Write a express js program that accepts COOKIE Open the page http://127.0.0.1:8000/ on your browser:
method.
install cookie-parser middleware through npm by using the
following command:
Set cookie:
app.listen(2000,function(){
console.log("Server is running on port 2000");
});
To install the package.json, execute the following code:
npm install
<html>
<head>
<title>File upload in Node.js by Javatpoint</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquer Select an image to upload and click on "Upload Image"
y.min.js"></script> Button
The default location for the MongoDB data directory is
c:\data\db. So you need to create this folder using the
Command Prompt. Execute the
following command sequence C:\>md data
C:\md data\db
If you have install the MongoDB at different location,
then you need to specify any
alternate path for \data\db by setting the path dbpath in
mongod.exe. For the same issue
following commands
In command prompt navigate to the bin directory present
Here, you see that file is uploaded successfully. You can into the mongodb installation
see the uploaded file in the "Uploads" folder. folder. Suppose my installation folder is D:\set
up\mongodb
C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set
up\mongodb\data"
D:\set up\mongodb\bin>mongo.exe
Mongo dB: MongoDB shell version: 3.4.3
1. Install MongoDB On Windows
To install the MongoDB on windows, first doownload the
latest release of MongoDB from
http://www.mongodb.org/downloads Make sure you get
correct version of MongoDB depending upon your
windows version. To get your windows
version open command prompt and execute following
command.
C:\>wmic os get osarchitecture
2. Demonstrate how to create and drop database in
OSArchitecture
MongoDB.
64-bit
The use Command MongoDB use DATABASE_NAME
C:\>
is used to create database. The
32-bit versions of MongoDB only support databases smaller
command will create a new database, if it doesn't exist
than 2GB and suitable only
otherwise it will return the existing
for testing and evaluation purposes. Now extract your
database. Syntax: Basic syntax of use DATABASE
downloaded file to c:\ drive or any
statement is as follows:
other location. Make sure name of the extracted folder is
use DATABASE_NAME
mongodb-win32-i386-[version]
Example: If you want to create a database with name
or mongodb-win32-x86_64-[version]. Here [version] is the
<mydb>, then use DATABASE
version of MongoDB
statement would be as follows: >use mydb.
download. Now open command prompt and run the
switched to db mydb
following command
To check your currently selected database use the
C:\>move mongodb-win64-* mongodb
command db >db mydb.
1 dir(s) moved
If you want to check your databases list, then use the
1 dir(s) moved.
command show dbs.
C:\>
>show dbs local
In case you have extracted the mondodb at different
0.78125GB test
location, then go to that path by using
0.23012GB
command cd FOOLDER/DIR and now run the above given
Your created database (mydb) is not present in list. To
process. MongoDB requires a
display database you need to insert
data folder to store its files.
atleast one document into it. 3. Creating the Collection in MongoDB
>db.movie.insert({"name":"tutorials point"})
>show dbs local MongoDB db.createCollection(name, options) is used to
0.78125GB mydb create collection.
0.23012GB test Syntax:
0.23012GB Basic syntax of createCollection() command is as follows
In mongodb default database is test. If you didn't create any db.createCollection(name, options)
database then collections will Options parameter is optional, so you need to specify only
be stored in test database. name of the collection.
The dropDatabase () Method Following is the list of options you can use:
MongoDB db.dropDatabase () command is used to drop a While inserting the document, MongoDB first checks size
existing database. Syntax: Basic field of capped collection, then
syn tax of dropDatabase () command is as follows: it checks max field
db.dropDatabase() Basic syntax of createCollection() method without options
This will delete the selected database. If you have not is as follows
selected any database, then it will >use test switched to db test
delete default 'test' database Example: First, check the list >db.createCollection("mycollection")
available databases by using the { "ok" : 1 }
command show dbs You can check the created collection by using the
>show dbs command show collections
local 0.78125GB >show collections
mydb 0.23012GB mycollection
test 0.23012GB system.indexes.
If you want to delete new database <mydb>, then
dropDatabase() command would be as
follows: >use mydb switched to db mydb.
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
Now check list of databases
>show dbs local
0.78125GB test
0.23012GB
>show collections
mycol mycollection
system.indexes
tutorialspoint
> Now drop the collection with the name mycollection
>db.tutorialpoint.drop()
true
> Again check the list of collections into database
>show collections
mycol
system.indexes
To drop the collection, use drop() command. Sometimes,
when doing bulk inserts -
we may insert duplicate values. Specifically, if we try to
insert duplicate _ids, we'll get the
duplicate key error:
Creating new collection:
>db.create("startup")
{ ok: 1 }
inserting many documents
5. MogoDB Insert Document >db.startup.insertMany([
a. Insert single document. {_id:"id1", name:"Uber"},
b. Insert multiple documents in collection. {_id:"id2", name:"Airbnb"},
The insert() Method {_id:"id4", name:"Ola"},
To insert data into MongoDB collection, you need to use ] );
MongoDB's insert() or >db.startup.insertMany( [
save()method {_id:"id4", name:"Uber"},
Example : {_id:"id5", name:"Airbnb"},
db.post.insert([{ {_id:"id6", name:"Ola"},
title: 'MongoDB Overview', ]);
description: 'MongoDB is no sql database', showing all documents
by: 'tutorials point', db.startup.find()
url: 'http://www.tutorialspoint.com', { _id: 'id1', name: 'Uber' }
tags: ['mongodb', 'database', 'NoSQL'], { _id: 'id2', name: 'Airbnb' }
likes: 100 { _id: 'id4', name: 'Uber' }
}, { _id: 'id5', name: 'Airbnb' }
{ { _id: 'id6', name: 'Ola' }
tags: ['mongodb', 'database', 'NoSQL'],
likes: 20, 6. Querying all the documents in json format and
comments: [{ Querying based on the criteria.
user:'user1', creating new collection.
message: 'My first comment', >db.create("startupnew")
dateCreated: new Date(2013,11,10,2,35), { ok: 1 }
like: 0 inserting many documents
}]} >db.startupnew.insertMany( [
]) {_id:"id1", name:"Uber"},
To insert the document you can use db.post.save(document) {_id:"id2", name:"Airbnb"},
also. If you don't specify _id {_id:"id4", name:"Ola"},
in the document ]);
then save() method will work same as insert() method. If >db.startupnew.insertMany( [
you specify _id then it will {_id:"id4", name:"Uber"},
replace whole data of {_id:"id5", name:"Airbnb"},
document containing _id as specified in save() method. {_id:"id6", name:"Ola"},
b. Insert multiple documents in collection. ] );
To insert multiple documents we can use insertMany() - showing all documents
which takes an array of documents as parameter. When db.startupnew.find()
executed, it returns multiple ids for each document in the
array. Output: { _id: 'id1', name: 'Uber' } { _id: 'id2', name:
'Airbnb' } { _id: 'id4', name: 'Uber' } { _id: 'id5', name:
'Airbnb' } { _id: 'id6', name: 'Ola' } Qureying whose name
is Uber >db.startupnew.find({name:"Uber"}) { _id: 'id1',
name: 'Uber' } { _id: 'id4', name: 'Uber' }
>db.startup1.save({
"_id" : "id6", "name":"MangoDB Document Replacing "
})
showing all documents after updation
>db.startup1.find()
Output:
{_id:"id1", name:"Uber"}
{_id:"id2", name:"Airbnb"}
{_id:"id3", name:"Ola"}
{_id:"id4", name:"Amazon"}
{_id:"id5", name:"Microsoft"}
{_id:"id6", name:"MangoDB Document Replacing "}
8. MongoDB delete document from a collection.
a. Using remove() method.
7. MongoDB update document b. Remove only one document matching your criteria
a. Using update() method. c. Remove all documents.
b. Using save() method. a. Using remove() method.
MongoDB's remove() method is used to remove document
a. Using update() method. from the collection.
creating new collection remove() method accepts two parameters. One is deletion
>db.createCollection("startup1") criteria and second is just One
{ ok: 1 } flag.
inserting many documents 1. deletion criteria : (Optional) deletion criteria according
>db.startup1.insertMany([ to documents will be removed.
{_id:"id1", name:"Uber"}, 2. justOne : (Optional) if set to true or 1, then remove only
{_id:"id2", name:"Airbnb"}, one document.
{_id:"id3", name:"Ola"}, Syntax:
{_id:"id4", name:"Amazon"}, Basic syntax of remove() method is as follows
{_id:"id5", name:"Microsoft"}, >db.COLLECTION_NAME.remove(DELLETION_CRIT
{_id:"id6", name:"Google"}, TERIA)
]);
showing all documents Example:
>db.startup1.find() creating new collection “startupnew”
{_id:"id1", name:"Uber"} >db.createCollection("startupnew")
{_id:"id2", name:"Airbnb"} { ok: 1 }
inserting many documents
{_id:"id3", name:"Ola"} >db.startupnew.insertMany([
{_id:"id4", name:"Amazon"} {_id:"id1", name:"Uber"},
{_id:"id5", name:"Microsoft"} {_id:"id2", name:"Airbnb"},
{_id:"id6", name:"Google"} {_id:"id4", name:"Ola"},
The update() method updates values in the existing ] );
document. >db.startupnew.insertMany( [
By default mongodb will update only single document, to {_id:"id4", name:"Uber"},
update multiple you need to set {_id:"id5", name:"Airbnb"},
a paramter 'multi' to true. {_id:"id6", name:"Ola"},
>db.startup1.update({'name':'Ola'},{$set:{'name':'New ] );
MongoDB By RVS'}},{multi:true}) showing all documents
db.startupnew.find()
b. Using save() method.
The save() method replaces the existing document with the
new document passed in save()
method
Output: db.startupnew.find()
{ _id: 'id1', name: 'Uber' } output:
{ _id: 'id2', name: 'Airbnb' } { _id: 'id1', name: 'Uber' }
{ _id: 'id4', name: 'Uber' } { _id: 'id2', name: 'Airbnb' }
{ _id: 'id5', name: 'Airbnb' } { _id: 'id4', name: 'Ola' }
{ _id: 'id6', name: 'Ola' } Following example will display the title of the document
Remove only one document matching your criteria : while quering the document.
>db.startupnew.remove({'name':'Ola'}) >db.startupnew.find({},{"name":1,_id:0})
showing all documents after removing “Ola” Output:
db.startupnew.find() { name: 'Uber' }
{ _id: 'id1', name: 'Uber' } { name: 'Airbnb' }
{ _id: 'id2', name: 'Airbnb' } { name: 'Ola' }
{ _id: 'id4', name: 'Uber' } > Please note _id field is always displayed while
{ _id: 'id5', name: 'Airbnb' } executing find() method, if you don't
Following example will remove all the documents whose want this field,then you need to set it as 0.
title is 'MongoDB Overview'
b. Remove only one document matching your criteria 10. limit() ,skip(), sort() methods in MongoDB
If you don't specify deletion criteria, then mongodb will The limit() Method :
delete whole documents from the To limit the records in MongoDB, you need to use limit()
collection. method. limit() method accepts
This is equivalent of SQL's truncate command. one number type argument, which is number of
>db.startupnew.remove() documents that you want to displayed.
After removing all documents Syntax: Basic syntax of limit() method is as follows
>db.COLLECTION_NAME.find().limit(NUMBER)
9. MongoDB Projection creating new collection “startupnew”
In mongodb projection meaning is selecting only necessary >db. createCollection ("startupnew")
data rather than selecting { ok: 1 }
whole of the data of adocument. If a document has 5 fields inserting many documents
and you need to show only 3, >db.startupnew.insertMany( [
then select only 3 fields from them. {_id:"id1", name:"Uber"},
The find() Method : {_id:"id2", name:"Airbnb"},
MongoDB's find() method accepts second optional {_id:"id4", name:"Ola"},
parameter that is list of fields that you ]);
want to retrieve. In MongoDB when you execute find() showing all documents in startupnew
method, then it displays all fields db.startupnew.find()
of a document. To limit this you need to set list of fields Output:
with value 1 or 0. 1 is used to { _id: 'id1', name: 'Uber' }
show the filed while 0 is used to hide the field. { _id: 'id2', name: 'Airbnb' }
Syntax: { _id: 'id4', name: 'Ola' }
Basic syntax of find() method Following example will display only 2 documents while
with projection is as follows quering the document.
>db.COLLECTION_NAME.find({},{KEY:1}) >db.startupnew.find({},{"name":1,_id:0}).limit(2)
Example : { _id: 'id1', name: 'Uber' }
creating new collection “startupnew” { _id: 'id2', name: 'Airbnb' }
>db.createCollection("startupnew") If you don't specify number argument in limit() method
{ ok: 1 } then it will display all documents
Inserting many documents from the collection.
>db.startupnew.insertMany([ The Skip() method:
{_id:"id1", name:"Uber"}, Apart from limit() method there is one more method
{_id:"id2", name:"Airbnb"}, skip() which also accepts number
{_id:"id4", name:"Ola"}, type argument and used to skip number of documents.
] ); Syntax:
showing all documents in startupnew Basic syntax of skip() method is as follows.
>db.COLLECTION_NAME.find().limit(NUMBER).skip(N >db.COLLECTION_NAME.ensureIndex({KEY:1})
UMBER) Here key is the name of filed on which you want to create
Example: index and 1 is for ascending
Following example will only display only second order. To create index in descending order you need to use
document. -1.
>db.startupnew.find({},{"name":1,_id:0}).limit(1).skip(1) Example :- creating new collection “startupnew” >db.
{ _id: 'id2', name: 'Airbnb' } createCollection ("startupnew") { ok: 1 } inserting many
>Please note default value in skip() method is 0 documents >db.startupnew.insertMany( [ {_id:"id1",
The sort() Method : name:"Uber",description:”US”}, {_id:"id2",
To sort documents in MongoDB, you need to use sort() name:"Airbnb",description,”IND”}, {_id:"id4",
method. sort() method accepts a name:"Ola",description:”IND”}, ] ); showing all
document containing list of fields along with their sorting documents in startupnew db.startupnew.find() {_id:"id1",
order. To specify sorting order 1 name:"Uber",description:”US”}, {_id:"id2",
and -1 are used. 1 is used for ascending order while -1 is name:"Airbnb",description,”IND”}, {_id:"id4",
used for descending order. name:"Ola",description:”IND”},
Syntax: >db.startupnew.ensureIndex({"name":1})
Basic syntax of sort() method is as follows Or db.startupnew.createIndex( {name: 1},
>db.COLLECTION_NAME.find().sort({KEY:1}) {name: "cab index"} )
Example : In ensureIndex() method you can pass multiple fields, to
Consider the collection startupnew has the following data create index on multiple fields. >db.
{ _id: 'id1', name: 'Uber' } startupnew.ensureIndex({"name":1,"description":-1})
{ _id: 'id2', name: 'Airbnb' } > ensureIndex() method also accepts list of options (which
{ _id: 'id4', name: 'Ola' } are optional), whose list is
Following example will display the documents sorted by given below:
name in descending order. b) Finding indexes
>db.startupnew.find({},{"name":1,_id:0}).sort({"name":- You can find all the available indexes in a MongoDB
1}) collection by using the getIndexes
Output: method. This will return all the indexes in a specific
{ _id: 'id1', name: 'Uber' } collection.
{ _id: 'id4', name: 'Ola' } db.startupnew.getIndexes()
{ _id: 'id2', name: 'Airbnb' } c) Dropping indexes
Please note if you don't specify the sorting preference, then To delete an index from a collection, use the dropIndex
sort() method will display method while specifying the index
documents in ascending order. name to be dropped.
11. MongoDB indexing db.startupnew.dropIndex("cab index")
a. Create index in MongoDB d) Dropping all indexes
b. Finding the indexes in a collection The dropIndexes command can also drop all the indexes
c. Drop indexes in a collection excluding the default _id index.
d. Drop all the indexes db.startupnew.dropIndexes()
a. Create index in MongoDB
Indexes support the efficient resolution of queries. Without
indexes, MongoDB must scan
every document of a collection to select those documents
that match the query statement.
This scan is highly inefficient and require the mongod to
process a large volume of data.
The ensureIndex() Method:
To create an index you need to use ensureIndex() method of
mongodb.
Syntax:
Basic syntax of ensureIndex() method is as follows()