Skip to content
| Marketplace
Sign in
Visual Studio Code>Education>FinTech VaultNew to Visual Studio Code? Get it now.
FinTech Vault

FinTech Vault

FinTech Vault

|
2 installs
| (0) | Free
Complete FinTech notes, SQL, and reference vault
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

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(${dollar} Dollar = ${dollarToInr(parseFloat(dollar))} INR); console.log(${inr} INR = ${inrToPounds(parseFloat(inr))} Pounds); console.log(${ruble} Ruble = ${rubleToDollar(parseFloat(ruble))} Dollar); rl.close(); }); }); });

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(Event emitted: Found multiple of 5 → ${num}); });

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

if (uploaded < size) {
  emitter.emit("progress", {
    file: filename,
    percent: Math.round((uploaded / size) * 100),
  });
} else {
  clearInterval(timer);
  emitter.emit("done", filename);
}

}, 500); }

emitter.on("progress", (data) => { console.log(Uploading ${data.file}: ${data.percent}%); });

emitter.on("done", (file) => { console.log(Upload complete: ${file}); });

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");

if (req.url === "/stats") {
  res.end(`Total Requests: ${count}`);
} else {
  res.end("Welcome! Refresh to increase count.");
}

}) .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; }

console.log("✅ Connected to MySQL Database");

const query = "SELECT * FROM employee";

connection.query(query, (err, results) => {
  if (err) {
    console.error("❌ Query error:", err.message);
    return;
  }

  console.log("📋 Employee Table Data:");
  console.table(results);
});

// Close connection
connection.end((err) => {
  if (err) console.error("❌ Error closing connection:", err.message);
  else console.log("🔒 Connection closed");
});

});

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);

// UPDATE
const updateSql = "UPDATE BOOKS SET book_price=? WHERE book_id=?";
db.query(updateSql, [1300, 102], () => {
  console.log("✏️ Book Updated");

  db.query("SELECT * FROM BOOKS", (err, rows) => {
    console.log("📋 After UPDATE");
    console.table(rows);

    // DELETE
    db.query("DELETE FROM BOOKS WHERE book_id=?", [104], () => {
      console.log("🗑️ Book Deleted");

      db.query("SELECT * FROM BOOKS", (err, rows) => {
        console.log("📋 After DELETE");
        console.table(rows);

        db.end();
      });
    });
  });
});

}); });

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 Karna

); }

export 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 (

  <p
    style={{
      backgroundColor: count > 20 ? "red" : "transparent",
      color: count > 20 ? "white" : "black",
    }}
  >
    Characters: {count}/20
  </p>
</div>

); };

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

  {password.length > 0 && (
    <p
      style={{
        color: "white",
        backgroundColor: password.length > 8 ? "green" : "red",
      }}
    >
      {password.length > 8 ? "Strong Password" : "Weak Password"}
    </p>
  )}
</div>

); };

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)} />

  <ul>
    {list.map((todo, i) => (
      <li key={i}>
        {todo}
        <button onClick={() => deleteTodo(i)}>❌</button>
      </li>
    ))}
  </ul>
</div>

); };

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())} />

  <ul>
    {items
      .filter((item) => item.toLowerCase().includes(search))
      .map((item, i) => (
        <li key={i}>{item}</li>
      ))}
  </ul>
</div>

); };

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 Profile

Name: 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 (