KEMBAR78
FSD Lab Manual (Final) | PDF | Angular Js | Software Engineering
0% found this document useful (0 votes)
5 views15 pages

FSD Lab Manual (Final)

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

FSD Lab Manual (Final)

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

Sure! Below is a breakdown of the solutions for each of the given tasks.

These will be basic


implementations in Node.js, AngularJS, MongoDB, and ReactJS. I'll provide the code along
with brief explanations and expected outputs.

---

### 1. **Create an application to set up Node.js environment and display “Hello World”**

```javascript
// helloWorld.js
const http = require('http');

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


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

server.listen(3000, '127.0.0.1', () => {


console.log('Server running at http://127.0.0.1:3000/');
});
```

**Output:**
```bash
Server running at http://127.0.0.1:3000/
```

When you open `http://127.0.0.1:3000/` in a browser, you should see `Hello World`.

---

### 2. **Create a Node.js application for user login system**

```javascript
// login.js
const http = require('http');
const url = require('url');

const users = [
{ username: 'admin', password: '12345' },
{ username: 'user', password: 'password' }
];

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


const query = url.parse(req.url, true).query;

const user = users.find(u => u.username === query.username && u.password ===
query.password);

res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');

if (user) {
res.end('Login successful');
} else {
res.end('Invalid credentials');
}
});

server.listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
```

**Output:**
Accessing `http://127.0.0.1:3000/?username=admin&password=12345` will return `Login
successful`. Otherwise, it will return `Invalid credentials`.

---

### 3. **Write a Node.js program to perform read, write, and other operations on a file**

```javascript
// fileOperations.js
const fs = require('fs');

// Write to file
fs.writeFileSync('example.txt', 'Hello Node.js');

// Read from file


const data = fs.readFileSync('example.txt', 'utf8');
console.log(data); // Output: Hello Node.js

// Append to file
fs.appendFileSync('example.txt', '\nThis is appended text');

// Read updated file


const updatedData = fs.readFileSync('example.txt', 'utf8');
console.log(updatedData);
```

**Output:**
```bash
Hello Node.js
Hello Node.js
This is appended text
```

---
### 4. **Write a Node.js program to read form data from query string and generate a
response using Node.js**

```javascript
// queryString.js
const http = require('http');
const url = require('url');

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


const query = url.parse(req.url, true).query;
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(`Hello, ${query.name}`);
});

server.listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
```

**Output:**
Accessing `http://127.0.0.1:3000/?name=John` will return `Hello, John`.

---

### 5. **Create a food delivery website where users can order food from a particular
restaurant listed in the website for handling HTTP requests and responses using Node.js**

```javascript
// foodDelivery.js
const http = require('http');

const menu = [
{ id: 1, name: 'Pizza', price: 12 },
{ id: 2, name: 'Burger', price: 5 }
];

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


if (req.url === '/menu' && req.method === 'GET') {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(menu));
} else {
res.statusCode = 404;
res.end('Page not found');
}
});

server.listen(3000, () => {
console.log('Server running at http://127.0.0.1:3000/');
});
```

**Output:**
Accessing `http://127.0.0.1:3000/menu` will return the food menu in JSON format.

---

### 6. **Implement a program with basic commands on databases and collections using
MongoDB**

```javascript
// mongodbExample.js
const { MongoClient } = require('mongodb');

async function run() {


const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('testdb');
const collection = db.collection('users');

// Insert a document
await collection.insertOne({ name: 'Alice', age: 25 });

// Find a document
const user = await collection.findOne({ name: 'Alice' });
console.log(user); // Output: { _id: ..., name: 'Alice', age: 25 }

await client.close();
}

run().catch(console.error);
```

**Output:**
```bash
{ _id: ..., name: 'Alice', age: 25 }
```

---

### 7. **Implement CRUD operations on the given dataset using MongoDB**

```javascript
// mongodbCrud.js
const { MongoClient } = require('mongodb');

async function run() {


const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('testdb');
const collection = db.collection('users');
// Create
await collection.insertOne({ name: 'Bob', age: 30 });

// Read
const user = await collection.findOne({ name: 'Bob' });
console.log(user);

// Update
await collection.updateOne({ name: 'Bob' }, { $set: { age: 31 } });

// Delete
await collection.deleteOne({ name: 'Bob' });

await client.close();
}

run().catch(console.error);
```

**Output:**
```bash
{ _id: ..., name: 'Bob', age: 30 }
```

---

### 8. **Perform Count, Limit, Sort, and Skip operations on the given collections using
MongoDB**

```javascript
// mongodbOps.js
const { MongoClient } = require('mongodb');

async function run() {


const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('testdb');
const collection = db.collection('users');

// Count documents
const count = await collection.countDocuments();
console.log('Count:', count);

// Limit results
const usersLimit = await collection.find().limit(2).toArray();
console.log('Limited users:', usersLimit);

// Sort results
const usersSorted = await collection.find().sort({ age: 1 }).toArray();
console.log('Sorted users by age:', usersSorted);
// Skip results
const usersSkipped = await collection.find().skip(1).toArray();
console.log('Skipped users:', usersSkipped);

await client.close();
}

run().catch(console.error);
```

**Output:**
```bash
Count: 2
Limited users: [ ... ]
Sorted users by age: [ ... ]
Skipped users: [ ... ]
```

---

### 9. **Develop an AngularJS form to apply CSS and Events**

```html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1>{{message}}</h1>
<form ng-submit="submitForm()">
<input type="text" ng-model="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
</body>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.message = "Hello, AngularJS!";
$scope.submitForm = function () {
alert("Hello " + $scope.name);
};
});
</script>
</html>
```
**Output:**
When you enter a name and submit the form, it will alert: `Hello [name]`.

---

### 10. **Develop a Job Registration form and validate it using AngularJS**

```html
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="jobApp" ng-controller="jobCtrl">
<form name="jobForm" ng-submit="submitForm()">
<label>Name:</label>
<input type="text" ng-model="job.name" required>
<br>
<label>Email:</label>
<input type="email" ng-model="job.email" required>
<br>
<button type="submit" ng-disabled="jobForm.$invalid">Submit</button>
</form>
<p ng-show="formSubmitted">Form submitted successfully!</p>
</body>

<script>
var app = angular.module('jobApp', []);
app.controller('jobCtrl', function ($scope) {
$scope.formSubmitted = false;
$scope.submitForm = function () {
if ($scope.jobForm.$valid) {
$scope.formSubmitted = true;
}
};
});
</script>
</html>
```

**Output:**
If valid data is entered, on submit it will show `Form submitted successfully!`.

---

Sure! Let's continue with the rest of the tasks:

11. Write an AngularJS application to access JSON file data of an employee from a server
using $http service
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="employeeApp" ng-controller="employeeCtrl">
<h1>Employee Details</h1>
<div ng-repeat="employee in employees">
<p>Name: {{employee.name}}</p>
<p>Position: {{employee.position}}</p>
</div>

<script>
var app = angular.module('employeeApp', []);
app.controller('employeeCtrl', function ($scope, $http) {
$http.get('employees.json').then(function(response) {
$scope.employees = response.data;
});
});
</script>
</body>
</html>
Assume employees.json contains:
[
{ "name": "John Doe", "position": "Developer" },
{ "name": "Jane Smith", "position": "Manager" }
]
Output: This will display employee details (name and position) in the HTML using data
fetched from the employees.json file.

12. Develop a web application to manage student information using Express and AngularJS
// server.js (Node.js with Express)
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

let students = [
{ id: 1, name: 'John Doe', age: 20 },
{ id: 2, name: 'Jane Smith', age: 22 }
];

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

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


const newStudent = req.body;
students.push(newStudent);
res.status(201).json(newStudent);
});
app.listen(3000, () => {
console.log('Server running on http://127.0.0.1:3000/');
});
<!-- studentApp.html (AngularJS frontend) -->
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="studentApp" ng-controller="studentCtrl">
<h1>Student Information</h1>
<ul>
<li ng-repeat="student in students">
{{student.name}} (Age: {{student.age}})
</li>
</ul>

<form ng-submit="addStudent()">
<input type="text" ng-model="newStudent.name" placeholder="Name" required />
<input type="number" ng-model="newStudent.age" placeholder="Age" required />
<button type="submit">Add Student</button>
</form>

<script>
var app = angular.module('studentApp', []);
app.controller('studentCtrl', function ($scope, $http) {
// Load students
$http.get('http://127.0.0.1:3000/students').then(function(response) {
$scope.students = response.data;
});

// Add a new student


$scope.addStudent = function() {
$http.post('http://127.0.0.1:3000/students',
$scope.newStudent).then(function(response) {
$scope.students.push(response.data);
$scope.newStudent = {};
});
};
});
</script>
</body>
</html>
Output:
• The AngularJS frontend will show a list of students.
• You can add a new student via the form, and the student list will update
dynamically.

13. Write a program to create a simple calculator application using ReactJS


// App.js (ReactJS)
import React, { useState } from 'react';

const App = () => {


const [result, setResult] = useState('');

const handleClick = (value) => {


setResult(result + value);
};

const handleClear = () => {


setResult('');
};

const handleCalculate = () => {


try {
setResult(eval(result));
} catch (error) {
setResult('Error');
}
};

return (
<div>
<h1>Simple Calculator</h1>
<div>
<input type="text" value={result} readOnly />
</div>
<div>
<button onClick={() => handleClick('1')}>1</button>
<button onClick={() => handleClick('2')}>2</button>
<button onClick={() => handleClick('3')}>3</button>
<button onClick={() => handleClick('+')}>+</button>
</div>
<div>
<button onClick={() => handleClick('4')}>4</button>
<button onClick={() => handleClick('5')}>5</button>
<button onClick={() => handleClick('6')}>6</button>
<button onClick={() => handleClick('-')}>-</button>
</div>
<div>
<button onClick={() => handleClick('7')}>7</button>
<button onClick={() => handleClick('8')}>8</button>
<button onClick={() => handleClick('9')}>9</button>
<button onClick={() => handleClick('*')}>*</button>
</div>
<div>
<button onClick={() => handleClick('0')}>0</button>
<button onClick={handleClear}>C</button>
<button onClick={handleCalculate}>=</button>
<button onClick={() => handleClick('/')}>/</button>
</div>
</div>
);
};

export default App;


Output: A simple calculator that performs basic arithmetic operations.

14. Write a program to create a voting application using ReactJS


// App.js (ReactJS)
import React, { useState } from 'react';

const App = () => {


const [votes, setVotes] = useState({
candidate1: 0,
candidate2: 0,
candidate3: 0,
});

const handleVote = (candidate) => {


setVotes((prevVotes) => ({
...prevVotes,
[candidate]: prevVotes[candidate] + 1,
}));
};

return (
<div>
<h1>Voting Application</h1>
<p>Candidate 1: {votes.candidate1} votes</p>
<p>Candidate 2: {votes.candidate2} votes</p>
<p>Candidate 3: {votes.candidate3} votes</p>
<button onClick={() => handleVote('candidate1')}>Vote for Candidate 1</button>
<button onClick={() => handleVote('candidate2')}>Vote for Candidate 2</button>
<button onClick={() => handleVote('candidate3')}>Vote for Candidate 3</button>
</div>
);
};

export default App;


Output: The user can vote for a candidate, and the vote count will be updated dynamically.

15. Develop a leave management system for an organization where users can apply
different types of leaves such as casual leave and medical leave using React
// LeaveApp.js (ReactJS)
import React, { useState } from 'react';

const LeaveApp = () => {


const [leaveType, setLeaveType] = useState('Casual Leave');
const [leaveDays, setLeaveDays] = useState(0);
const [remainingLeave, setRemainingLeave] = useState({
casual: 10,
medical: 12,
});

const applyLeave = () => {


if (leaveType === 'Casual Leave' && remainingLeave.casual >= leaveDays) {
setRemainingLeave({ ...remainingLeave, casual: remainingLeave.casual - leaveDays });
} else if (leaveType === 'Medical Leave' && remainingLeave.medical >= leaveDays) {
setRemainingLeave({ ...remainingLeave, medical: remainingLeave.medical - leaveDays });
} else {
alert('Insufficient leave days');
}
};

return (
<div>
<h1>Leave Management System</h1>
<p>Remaining Casual Leave: {remainingLeave.casual}</p>
<p>Remaining Medical Leave: {remainingLeave.medical}</p>
<form>
<label>Leave Type:</label>
<select value={leaveType} onChange={(e) => setLeaveType(e.target.value)}>
<option value="Casual Leave">Casual Leave</option>
<option value="Medical Leave">Medical Leave</option>
</select>
<br />
<label>Leave Days:</label>
<input
type="number"
value={leaveDays}
onChange={(e) => setLeaveDays(Number(e.target.value))}
/>
<br />
<button type="button" onClick={applyLeave}>
Apply Leave
</button>
</form>
</div>
);
};

export default LeaveApp;


Output: The user can apply for leave and the remaining leave balance will be updated after
applying.

16. Build a music store application using React components and provide routing among the
web pages
// App.js (ReactJS with React Router)
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
const Home = () => (
<div>
<h1>Welcome to the Music Store</h1>
<Link to="/products">Browse Products</Link>
</div>
);

const Products = () => (


<div>
<h1>Music Products</h1>
<ul>
<li>Album 1</li>
<li>Album 2</li>
<li>Album 3</li>
</ul>
<Link to="/">Go Home</Link>
</div>
);

const App = () => {


return (
<Router>
<div>
<h1>Music Store</h1>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/products" component={Products} />
</Switch>
</div>
</Router>
);
};

export default App;


Output:
• The home page displays a link to browse products.
• The products page lists music albums and provides navigation back to the home
page.

17. Create a react application for an online store which consists of registration, login, and
product information pages and implement routing to navigate through these pages
// App.js (ReactJS with React Router)
import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

const Registration = () => {


const [user, setUser] = useState({ username: '', password: '' });

const handleSubmit = (e) => {


e.preventDefault();
alert(`Registered as ${user.username}`);
};

return (
<form onSubmit={handleSubmit}>
<h1>Register</h1>
<input
type="text"
placeholder="Username"
value={user.username}
onChange={(e) => setUser({ ...user, username: e.target.value })}
/>
<input
type="password"
placeholder="Password"
value={user.password}
onChange={(e) => setUser({ ...user, password: e.target.value })}
/>
<button type="submit">Register</button>
</form>
);
};

const Login = () => {


const [user, setUser] = useState({ username: '', password: '' });

const handleSubmit = (e) => {


e.preventDefault();
alert(`Logged in as ${user.username}`);
};

return (
<form onSubmit={handleSubmit}>
<h1>Login</h1>
<input
type="text"
placeholder="Username"
value={user.username}
onChange={(e) => setUser({ ...user, username: e.target.value })}
/>
<input
type="password"
placeholder="Password"
value={user.password}
onChange={(e) => setUser({ ...user, password: e.target.value })}
/>
<button type="submit">Login</button>
</form>
);
};

const Products = () => (


<div>
<h1>Product List</h1>
<ul>
<li>Product 1</li>
<li>Product 2</li>
<li>Product 3</li>
</ul>
<Link to="/">Go Home</Link>
</div>
);

const App = () => (


<Router>
<div>
<h1>Online Store</h1>
<nav>
<Link to="/">Home</Link> | <Link to="/login">Login</Link> | <Link
to="/register">Register</Link> | <Link to="/products">Products</Link>
</nav>
<Switch>
<Route path="/" exact render={() => <h2>Welcome to our Store</h2>} />
<Route path="/login" component={Login} />
<Route path="/register" component={Registration} />
<Route path="/products" component={Products} />
</Switch>
</div>
</Router>
);

export default App;


Output:
• The app has pages for registration, login, and product listing.
• React Router handles navigation between these pages.

This concludes the solutions for the tasks! Let me know if you need further clarification or
help with any specific code.

You might also like