Assignment 1 1(a) PATH MODULE File name usingPath.js What examiner checks Use of path module Understanding of path utilities CODE (Copy–Paste Exactly) // usingPath.js const path = require("path"); console.log("===== CURRENT DIRECTORY AND FILE ====="); console.log("__dirname:", __dirname); console.log("__filename:", __filename); console.log("\n===== FILENAME FROM PATH ====="); const filePath = "C:\Users\demo\Desktop\SIES\WEB\Assignments\WT\file.html"; console.log("Basename:", path.basename(filePath)); console.log("\n===== FILE EXTENSION ====="); console.log("Extension:", path.extname(filePath)); console.log("\n===== DIRECTORY NAME ====="); console.log("Directory:", path.dirname(filePath)); console.log("\n===== IS PATH ABSOLUTE ====="); console.log("Is Absolute:", path.isAbsolute(filePath)); console.log("\n===== JOINING PATH SEGMENTS ====="); console.log("Joined Path:", path.join("/ext", "text", "test", "rest")); console.log("\n===== PATH COMPONENTS ====="); console.log(path.parse(filePath)); console.log("\n===== RELATIVE PATH ====="); console.log( path.relative( "C:\Users\demo\Desktop\SIES\WEB\Assignments\WT\file.html", "C:\Users\demo\Desktop\SIES\WEB\Assignments\WT\usingHello.js" ) ); console.log("\n===== SPLIT USING PATH SEPARATOR ====="); console.log("foo\bar\baz".split(path.sep)); 1(b) CUSTOM MODULE — CURRENCY CONVERSION File 1 conversion.js // conversion.js const dollarToInr = (amount) => amount * 88.76; const inrToPounds = (amount) => amount * 0.0084; const rubleToDollar = (amount) => amount * 0.012; module.exports = { dollarToInr, inrToPounds, rubleToDollar, }; File 2 usingConversion.js // usingConversion.js const { dollarToInr, inrToPounds, rubleToDollar } = require("./conversion"); const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question("Enter dollar amount: ", (dollar) => {
rl.question("Enter INR amount: ", (inr) => {
rl.question("Enter ruble amount: ", (ruble) => {
console.log( contactModule.js // contactModule.js let callBook = [ ["Bob", 12], ["David", 13], ]; const getContact = () => callBook; const addContact = (name, number) => { callBook.push([name, number]); return callBook; }; const deleteContact = (name) => { const index = callBook.findIndex((c) => c[0] === name); if (index !== -1) callBook.splice(index, 1); return callBook; }; const findNumber = (name) => { const contact = callBook.find((c) => c[0] === name); return contact ? contact[1] : "Not Found"; }; const findName = (number) => { const contact = callBook.find((c) => c[1] === number); return contact ? contact[0] : "Not Found"; }; module.exports = { getContact, addContact, deleteContact, findNumber, findName, }; 📁 usingContacts.js const { getContact, addContact, deleteContact, findNumber, findName, } = require("./contactModule"); console.log("Contacts:", getContact()); addContact("Karna", 99999); console.log("After Add:", getContact()); console.log("Find Number:", findNumber("Karna")); console.log("Find Name:", findName(12)); deleteContact("David"); console.log("After Delete:", getContact()); FS MODULE — FILE OPERATIONS 📁 fileOps.js const fs = require("fs"); if (!fs.existsSync("source.txt")) { fs.writeFileSync("source.txt", "Hello Web Tech"); } console.log("Reading File:"); console.log(fs.readFileSync("source.txt", "utf-8")); fs.writeFile("output.txt", "New File", () => { fs.appendFile("output.txt", "\nAppended Text", () => { fs.rename("output.txt", "renamed.txt", () => { fs.unlink("renamed.txt", () => { console.log("File deleted"); }); }); }); }); ▶️ node fileOps.js STREAMS — FILE COPY PROGRESS 📁 streamCopy.js const fs = require("fs"); let bytes = 0; const read = fs.createReadStream("source.txt"); const write = fs.createWriteStream("dest.txt"); read.on("data", (chunk) => { bytes += chunk.length; console.log("Copied", bytes, "bytes"); }); read.pipe(write); server.js const http = require("http"); const fs = require("fs"); http .createServer((req, res) => { if (req.url === "/") { res.end("Server Running"); } }) .listen(4000, () => console.log("Server at http://localhost:4000")); Assignment 2 // multipleOfFive.js const EventEmitter = require("events"); const myEmitter = new EventEmitter(); // Event listener
myEmitter.on("multipleOfFive", (num) => {
console.log( // Function to scan array function findMultiples(arr) { for (let num of arr) { if (num % 5 === 0) { myEmitter.emit("multipleOfFive", num); } } } // Test array const numbers = [2, 10, 7, 15, 3, 25, 8, 20]; console.log("Array:", numbers); console.log("Processing array..."); findMultiples(numbers); console.log("Done."); // trafficLight.js const EventEmitter = require("events"); const traffic = new EventEmitter(); const TIMING = { red: 5000, green: 5000, yellow: 2000, }; let current = "red"; // Listener traffic.on("change", (state) => { console.clear(); console.log("🚦 TRAFFIC LIGHT 🚦"); console.log("Current Light:", state.toUpperCase()); if (state === "red") console.log("Cars: STOP | Pedestrian: GO"); if (state === "green") console.log("Cars: GO | Pedestrian: WAIT"); if (state === "yellow") console.log("Cars: READY | Pedestrian: STOP"); }); // Change logic function changeLight() { if (current === "red") current = "green"; else if (current === "green") current = "yellow"; else current = "red"; traffic.emit("change", current); setTimeout(changeLight, TIMING[current]); } console.log("Starting Traffic Simulation..."); setTimeout(changeLight, 1000); // resendOTP.js let timer = 10; setInterval(() => { if (timer === 0) { console.log("OTP reset. You can resend OTP now."); timer = 10; } else { console.log("Resend OTP in:", timer); timer--; } }, 1000); // uploadProgress.js const EventEmitter = require("events"); const emitter = new EventEmitter(); function uploadFile(filename, size) { let uploaded = 0; const chunk = size / 10; const timer = setInterval(() => { uploaded += chunk;
}, 500); } emitter.on("progress", (data) => {
console.log( emitter.on("done", (file) => {
console.log( uploadFile("example.txt", 1000); // requestCounter.js const http = require("http"); const EventEmitter = require("events"); const emitter = new EventEmitter(); let count = 0; emitter.on("request", () => { count++; console.log("Request received:", count); }); http .createServer((req, res) => { emitter.emit("request");
}) .listen(3000, () => { console.log("Server running at http://localhost:3000"); }); Assignment 3 🗄️ DATABASE SETUP (DO THIS FIRST) Open phpMyAdmin / MySQL Workbench and run: CREATE DATABASE MyDB; USE MyDB; CREATE TABLE employee ( emp_id INT PRIMARY KEY, emp_name VARCHAR(50), emp_salary INT ); INSERT INTO employee VALUES (101, 'Aj', 900000), (102, 'Tom', 600000), (103, 'Jerry', 700000); ✔️ Database ready // fetchEmployee.js const mysql = require("mysql2"); // Create connection const connection = mysql.createConnection({ host: "localhost", user: "root", password: "", // keep blank if using XAMPP default database: "MyDB", }); // Connect to DB connection.connect((err) => { if (err) { console.error("❌ Error connecting:", err.message); return; }
}); DATABASE SETUP Run in MySQL: CREATE DATABASE books; USE books; CREATE TABLE BOOKS ( book_id INT PRIMARY KEY, book_name VARCHAR(100), book_author VARCHAR(100), book_price INT ); // db.js const mysql = require("mysql2"); const connection = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "books", }); connection.connect((err) => { if (err) console.error("❌ DB Connection Failed:", err.message); else console.log("✅ Connected to BOOKS Database"); }); module.exports = connection; // books.js const db = require("./db"); // INSERT const insertSql = "INSERT INTO BOOKS (book_id, book_name, book_author, book_price) VALUES ?"; const books = [ [101, "The Alchemist", "Paulo Coelho", 250], [102, "Clean Code", "Robert C. Martin", 1200], [103, "Harry Potter", "J.K. Rowling", 500], [104, "Atomic Habits", "James Clear", 800], ]; db.query(insertSql, [books], (err) => { if (err) throw err; console.log("📘 Books Inserted"); // DISPLAY db.query("SELECT * FROM BOOKS", (err, rows) => { console.log("📋 After INSERT"); console.table(rows);
}); });Assignment 4 Functional Component & Export 📁 src/Greetings.js import React from "react"; function Greetings() { return Hello! This is my first React Project; }export default Greetings; 📁 src/App.js import Greetings from "./Greetings"; function App() { return ( export default App; PROGRAM 4.2 Personalized Greeting using Props 📁 src/Greetings.js import React from "react"; function Greetings(props) { return Hello {props.name} 🙂; }export default Greetings; 📁 src/App.js import Greetings from "./Greetings"; function App() { return ( export default App; Profile Picture Component 📁 src/ProfilePic.js import React from "react"; function ProfilePic(props) { return ( export default ProfilePic; 📁 src/App.js import ProfilePic from "./ProfilePic"; function App() { return ( Hello Karnaexport default App; Product Card Component (Reusable) 📁 src/ProductCard.js function ProductCard({ name, price, description, imageUrl }) { return ( {name}₹{price} {description} const styles = { card: { border: "1px solid #ccc", padding: "15px", width: "250px", borderRadius: "10px", }, image: { width: "100%", height: "150px", objectFit: "cover", }, }; export default ProductCard; 📁 src/App.js import ProductCard from "./ProductCard"; function App() { return ( <div style={{ display: "flex", gap: "20px" }}> export default App; Counter — Class Component 📁 src/Counter.js import React from "react"; class Counter extends React.Component { constructor() { super(); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; decrement = () => { this.setState({ count: this.state.count - 1 }); }; reset = () => { this.setState({ count: 0 }); }; render() { return ( Counter{this.state.count}export default Counter; 📁 src/App.js import Counter from "./Counter"; function App() { return ; } export default App; PROGRAM 4.6 Character Counter (Class Component + Timer) 📁 src/CharCounter.js import React, { Component } from "react"; class CharCounter extends Component { constructor(props) { super(props); this.state = { text: "", remaining: props.maxLength || 100, }; } handleChange = (e) => { const text = e.target.value; this.setState({ text, remaining: this.props.maxLength - text.length, }); }; render() { return ( export default CharCounter; 📁 src/App.js import CharCounter from "./CharCounter"; function App() { return ; } export default App; PROGRAM 4.7 Like / Unlike Toggle Button 📁 src/Toggle.js import React, { Component } from "react"; class Toggle extends Component { constructor() { super(); this.state = { liked: false, count: 0 }; } toggleLike = () => { this.setState((prev) => ({ liked: !prev.liked, count: prev.liked ? prev.count - 1 : prev.count + 1, })); }; render() { return ( ); } } export default Toggle; 🔹 PROGRAM 4.8 Currency Switcher (Class Component) 📁 src/CurrencyClass.js import React from "react"; class CurrencyClass extends React.Component { state = { currency: "INR" }; rates = { INR: 1, USD: 0.012, EUR: 0.011, }; render() { const basePrice = 100000; const converted = basePrice * this.rates[this.state.currency];
} } export default CurrencyClass;Assignment 5 PROGRAM 5.1 Color Switcher using useState 📁 src/ColorSwitch.js import React, { useState } from "react"; const ColorSwitch = () => { const [color, setColor] = useState("red"); return ( Color Switcher
); }; export default ColorSwitch; 📁 src/App.js import ColorSwitch from "./ColorSwitch"; function App() { return ; } export default App; Character Counter (Limit = 20) 📁 src/CharCounter.js import React, { useState } from "react"; const CharCounter = () => { const [count, setCount] = useState(0); return (
<textarea
rows="4"
cols="30"
onChange={(e) => setCount(e.target.value.length)}
>
); }; export default CharCounter; Password Strength Checker 📁 src/PasswordCheck.js import React, { useState } from "react"; const PasswordCheck = () => { const [password, setPassword] = useState(""); return (
<input
type="password"
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter password"
/>
); }; export default PasswordCheck; Todo List (Add & Delete) 📁 src/Todo.js import React, { useState } from "react"; const Todo = () => { const [list, setList] = useState([]); const [item, setItem] = useState(""); const addTodo = () => { if (!item) return; setList([...list, item]); setItem(""); }; const deleteTodo = (i) => { setList(list.filter((_, index) => index !== i)); }; return (
<input value={item} onChange={(e) => setItem(e.target.value)} />
);
}
); }; export default Todo; PROGRAM 5.5 Search Filter 📁 src/SearchFilter.js import React, { useState } from "react"; const SearchFilter = () => { const [search, setSearch] = useState(""); const items = [ "Banana", "Apple", "Orange", "Mango", "Kiwi", "Watermelon", ]; return (
<input
placeholder="Search"
onChange={(e) => setSearch(e.target.value.toLowerCase())}
/>
);
}
); }; export default SearchFilter; 🔹 PROGRAM 5.6 useEffect — Change Title on Counter 📁 src/TitleCounter.js import React, { useState, useEffect } from "react"; const TitleCounter = () => { const [count, setCount] = useState(0); useEffect(() => { document.title = "Counter: " + count; }, [count]); return <button onClick={() => setCount(count + 1)}>Click; }; export default TitleCounter; 🔹 PROGRAM 5.7 Login / Logout Title Change 📁 src/Login.js import React, { useState, useEffect } from "react"; const Login = () => { const [logged, setLogged] = useState(false); useEffect(() => { document.title = logged ? "Hello User" : "Hello Guest"; }, [logged]); return (
<button onClick={() => setLogged(true)}>Login
<button onClick={() => setLogged(false)}>Logout
);
};
export default Login; 🔹 PROGRAM 5.8 Timer (Time Up) 📁 src/Timer.js import React, { useEffect, useState } from "react"; const Timer = () => { const [time, setTime] = useState(10); useEffect(() => { if (time > 0) { setTimeout(() => setTime(time - 1), 1000); } }, [time]); return {time === 0 ? "Time Up" : time}; };export default Timer;Assignment 6 npx create-react-app wt-assignment6 cd wt-assignment6 npm install react-router-dom npm start 📁 src/index.js import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import { BrowserRouter } from "react-router-dom"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( ); 📌 Viva Tip: BrowserRouter enables routing in React. 📁 src/App.js import { Routes, Route } from "react-router-dom"; import Navbar from "./Pages/Navbar"; import Dashboard from "./Pages/Dashboard"; import Profile from "./Pages/Profile"; import Products from "./Pages/Products"; import Contact from "./Pages/Contact"; function App() { return ( <> <Route path="/" element={} /> <Route path="/profile" element={} /> <Route path="/products" element={} /> <Route path="/contact" element={} /> </> ); } export default App; 📁 src/Pages/Navbar.js import { Link } from "react-router-dom"; function Navbar() { return ( <nav style={{ padding: "10px", background: "#222" }}> <Link to="/" style={{ color: "white", margin: "10px" }}>Dashboard <Link to="/profile" style={{ color: "white", margin: "10px" }}>Profile <Link to="/products" style={{ color: "white", margin: "10px" }}>Products <Link to="/contact" style={{ color: "white", margin: "10px" }}>Contact ); } export default Navbar; 📌 Why Link instead of ? 👉 Prevents page reload. 📁 src/Pages/Dashboard.js function Dashboard() { return Welcome to Dashboard; }export default Dashboard; 📁 src/Pages/Profile.js function Profile() { return ( User ProfileName: Karna Email: karna@gmail.com export default Profile; 📁 src/Pages/ProductCard.js function ProductCard({ name, price }) { return ( <div style={{ border: "1px solid gray", padding: "10px", width: "150px" }}> {name}₹{price} export default ProductCard; 📁 src/Pages/Products.js import ProductCard from "./ProductCard"; function Products() { return ( <div style={{ display: "flex", gap: "20px" }}> export default Products; 📁 src/Pages/Contact.js import { useState } from "react"; function Contact() { const [data, setData] = useState({ name: "", email: "", message: "", }); const handleChange = (e) => { setData({ ...data, [e.target.name]: e.target.value }); }; const handleSubmit = (e) => { e.preventDefault(); alert("Message Sent!"); setData({ name: "", email: "", message: "" }); }; return ( ); }export default Contact; 🔹 PART 6(B) Review Submission Form 📁 ReviewForm.js import { useState } from "react"; function ReviewForm() { const [name, setName] = useState(""); const [review, setReview] = useState(""); const [submitted, setSubmitted] = useState(false); const handleSubmit = (e) => { e.preventDefault(); setSubmitted(true); }; return submitted ? ( Thank you! Review Submitted.) : ( ); }export default ReviewForm; 🔹 PART 6(C) Registration Form (Controlled) 📁 RegistrationForm.js import { useState } from "react"; function RegistrationForm() { const [data, setData] = useState({ name: "", email: "", password: "", agree: false, }); const handleChange = (e) => { const { name, value, type, checked } = e.target; setData({ ...data, [name]: type === "checkbox" ? checked : value }); }; const handleSubmit = (e) => { e.preventDefault(); alert("Registered Successfully"); }; return ( ); }export default RegistrationForm; 🔹 PART 6(D) Newsletter Form (Uncontrolled – useRef) 📁 Newsletter.js import { useRef, useState } from "react"; function Newsletter() { const emailRef = useRef(); const checkRef = useRef(); const [summary, setSummary] = useState(null); const submit = (e) => { e.preventDefault(); setSummary({ email: emailRef.current.value, consent: checkRef.current.checked, }); }; return ( <>
); } export default Newsletter; 🔹 PART 6(E) Contact Form with Validation 📁 ContactForm.js import { useState } from "react"; function ContactForm() { const [data, setData] = useState({ name: "", email: "", phone: "", age: "", message: "", }); const submit = (e) => { e.preventDefault();
}; return ( ); }export default ContactForm; |