0% found this document useful (0 votes)
25 views26 pages

FSDDD

The document outlines the creation of various Node.js applications, including a simple 'Hello World' server, a student information management system using Express and AngularJS, a user login system, file operations, and a job registration form. It also describes a food delivery website that allows users to order from listed restaurants. Each application includes code snippets and expected outputs, demonstrating the functionality of Node.js and AngularJS in web development.

Uploaded by

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

FSDDD

The document outlines the creation of various Node.js applications, including a simple 'Hello World' server, a student information management system using Express and AngularJS, a user login system, file operations, and a job registration form. It also describes a food delivery website that allows users to order from listed restaurants. Each application includes code snippets and expected outputs, demonstrating the functionality of Node.js and AngularJS in web development.

Uploaded by

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

1) Create an application to setup node JS environment and display “Hello

World

const http = require('http');


const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});

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

OUTPUT:
Server running at http://localhost:3000/

12) Develop a web application to manage student information using Express


and Angular JS

Create a studentapp folder:


studentapp/

├── index.html ← AngularJS frontend
├── server.js ← Express backend
├── package.json

Server.js

const express = require('express');


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

const app = express();


const PORT = 3001;
app.use(cors());
app.use(bodyParser.json());

let students = [
{ id: 1, name: 'Alice', age: 20 },
{ id: 2, name: 'Bob', age: 21 }
];

// Get all students


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

// Add a new student


app.post('/api/students', (req, res) => {
const newStudent = {
id: students.length + 1,
name: req.body.name,
age: req.body.age
};
students.push(newStudent);
res.json(newStudent);
});

app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

Index .html

<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<meta charset="UTF-8">
<title>Student Manager</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
<style>
body { font-family: Arial; margin: 40px; }
input, button { margin: 5px; padding: 6px; }
table { margin-top: 20px; border-collapse: collapse; width: 50%; }
th, td { border: 1px solid black; padding: 8px; }
th { background-color: #f2f2f2; }
</style>
</head>
<body ng-controller="StudentController">

<h2>Student Information</h2>

<input type="text" ng-model="newStudent.name" placeholder="Name" />


<input type="number" ng-model="newStudent.age" placeholder="Age" />
<button ng-click="addStudent()">Add Student</button>

<table>
<thead>
<tr>
<th>ID</th><th>Name</th><th>Age</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="student in students">
<td>{{ student.id }}</td>
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
</tr>
</tbody>
</table>

<script>
const app = angular.module('studentApp', []);
app.controller('StudentController', function($scope, $http) {
$scope.students = [];
$scope.newStudent = {};

$http.get('http://localhost:3001/api/students').then(function(response) {
$scope.students = response.data;
});

$scope.addStudent = function() {
if (!$scope.newStudent.name || !$scope.newStudent.age) return;

$http.post('http://localhost:3001/api/students',
$scope.newStudent).then(function(response) {
$scope.students.push(response.data);
$scope.newStudent = {};
});
};
});
</script>
</body>
</html>

output

cd studentapp
>node server.js
Server running at http://localhost:3001

2.Create a Node JS application for user login system


const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');

const app = express();


app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true
}));

const users = { user1: 'pass1', admin: 'admin123' }; // In-memory users

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


res.send(`<h2>Login</h2>
<form method="POST">
<input name="username" placeholder="Username" required /><br>
<input name="password" type="password" placeholder="Password" required
/><br>
<button>Login</button>
</form>`);
});

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


const { username, password } = req.body;
if (users[username] && users[username] === password) {
req.session.user = username;
res.redirect('/dashboard');
} else {
res.send('Invalid credentials');
}
});

app.get('/dashboard', (req, res) => {


if (req.session.user) {
// ✅ Fix: wrap string in backticks for template literal
res.send(`Welcome ${req.session.user}! <a href="/logout">Logout</a>`);
} else {
res.redirect('/');
}
});

app.get('/logout', (req, res) => {


req.session.destroy(err => {
if (err) console.error(err);
res.redirect('/');
});
});

app.listen(3000, () => console.log('Running at http://localhost:3000'));


3) Write a Node JS program to perform read, write and other operations on a
file.
const fs = require('fs');
const fsp = require('node:fs/promises');
const file = 'example.txt';

// ➖ 1. Write (async) – create or replace


fs.writeFile(file, 'Hello, Node!\n', 'utf8', err => {
if (err) return console.error('writeFile failed:', err);
console.log('File written (async).');

// ➕ 2. Append (async)
fs.appendFile(file, 'Appended line.\n', err => {
if (err) return console.error('appendFile failed:', err);
console.log('Appended (async).');

// 📚 3. Read (async)
fs.readFile(file, 'utf8', (err, data) => {
if (err) return console.error('readFile failed:', err);
console.log('Async Read:\n', data);

// ℹ️4. File stats (async)


fs.stat(file, (err, stats) => {
if (err) return console.error('stat failed:', err);
console.log('Stats:', {
size: stats.size,
modified: stats.mtime
});

// 🔁 5. Rename (async)
const newFile = 'renamed_example.txt';
fs.rename(file, newFile, err => {
if (err) return console.error('rename failed:', err);
console.log(`Renamed to ${newFile}`);

// ❌ 6. Delete (async)
fs.unlink(newFile, err => {
if (err) return console.error('unlink failed:', err);
console.log(`Deleted ${newFile}`);
});
});
});
});
});
});
// 🧰 7. Synchronous examples
try {
fs.writeFileSync('sync.txt', 'Synchronous write\n');
fs.appendFileSync('sync.txt', 'Sync append\n');
const content = fs.readFileSync('sync.txt', 'utf8');
console.log('Sync Read:\n', content);
} catch (err) {
console.error('Sync operation failed:', err);
}

// 💡 8. Promise-based example (modern async/await)


(async () => {
try {
await fsp.writeFile('promise.txt', 'Promise write\n');
await fsp.appendFile('promise.txt', 'Promise append\n');
const data = await fsp.readFile('promise.txt', 'utf8');
console.log('Promise Read:\n', data);
} catch (err) {
console.error('Promise FS operation error:', err);
}
})();
Output:
Sync Read:
Synchronous write
Sync append

File written (async).


Appended (async).
Async Read:
Hello, Node!
Appended line.

Stats: { size: 28, modified: 2025-06-09T12:51:40.711Z }


Promise Read:
Promise write
Promise append

Renamed to renamed_example.txt
Deleted renamed_example.txt
11) Write an angular JS application to access JSON file data of an employee
from a server using $http service
Create folder
Index.html and employee.json
<!DOCTYPE html>
<html ng-app="employeeApp">
<head>
<meta charset="UTF-8">
<title>Employee Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
</head>
<body ng-controller="EmployeeController">

<h2>Employee List</h2>
<table border="1" cellpadding="8">
<tr>
<th>ID</th>
<th>Name</th>
<th>Designation</th>
<th>Salary</th>
</tr>
<tr ng-repeat="emp in employees">
<td>{{ emp.id }}</td>
<td>{{ emp.name }}</td>
<td>{{ emp.designation }}</td>
<td>{{ emp.salary }}</td>
</tr>
</table>

<script>
var app = angular.module('employeeApp', []);
app.controller('EmployeeController', function($scope, $http) {
$http.get('employee.json')
.then(function(response) {
$scope.employees = response.data;
}, function(error) {
console.error('Error:', error);
});
});
</script>

</body>
</html>
Employee.json
[
{ "id": 1, "name": "Alice", "designation": "Developer", "salary": 50000 },
{ "id": 2, "name": "Bob", "designation": "Designer", "salary": 45000 },
{ "id": 3, "name": "Charlie", "designation": "Manager", "salary": 60000 }
]

Output:
npm install -g http-server
cd employee-app
http-server
Starting up http-server, serving ./
http-server version: 14.1.
http-server settings:
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
http://192.168.1.186:8080
http://127.0.0.1:8080

4) Write a Node JS program to read form data from query string and
generate response using NodeJS
const http = require('http');
const url = require('url');
// Create HTTP server
http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true); // true to get query as object
const pathname = parsedUrl.pathname;
if (pathname === '/') {
// Serve form HTML
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(`
<h2>Enter Your Info</h2>
<form action="/submit" method="get">
Name: <input type="text" name="name" /><br><br>
Age: <input type="number" name="age" /><br><br>
<input type="submit" value="Submit" />
</form>
`);
res.end();
} else if (pathname === '/submit') {
// Handle query string data
const name = parsedUrl.query.name;
const age = parsedUrl.query.age;
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(`<h3>Hello, ${name}!</h3>`);
res.write(`<p>Your age is ${age}.</p>`);
res.end();
} else {
// 404 Not Found
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
}).listen(3002);
console.log('🌐 Server running at http://localhost:3002');
OUTPUT:
node response.js
🌐 Server running at http://localhost:3002

10) Develop a Job Registration form and validate it using angular JS.
<!DOCTYPE html>
<html ng-app="jobApp">
<head>
<meta charset="UTF-8">
<title>Job Registration</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
<style>
input.ng-invalid.ng-touched { border: 1px solid red; }
input.ng-valid.ng-touched { border: 1px solid green; }
.error { color: red; font-size: 0.9em; }
form { max-width: 300px; margin: 20px auto; }
pre {
background: #f8f8f8;
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
text-align: left;
}
</style>
</head>
<body ng-controller="JobCtrl as vm">

<form name="regForm" novalidate ng-submit="vm.submit(regForm.$valid)">


<label>Name:</label><br>
<input type="text" name="name" ng-model="vm.user.name" required>
<div class="error" ng-show="regForm.name.$touched && regForm.name.
$error.required">Required</div><br>

<label>Email:</label><br>
<input type="email" name="email" ng-model="vm.user.email" required>
<div class="error" ng-show="regForm.email.$touched">
<span ng-show="regForm.email.$error.required">Required</span>
<span ng-show="regForm.email.$error.email">Invalid email</span>
</div><br>

<label>Phone:</label><br>
<input type="text" name="phone" ng-model="vm.user.phone" required ng-
pattern="/^\d{10}$/">
<div class="error" ng-show="regForm.phone.$touched">
<span ng-show="regForm.phone.$error.required">Required</span>
<span ng-show="regForm.phone.$error.pattern">Must be 10 digits</span>
</div><br>

<label>Position:</label><br>
<input type="text" name="position" ng-model="vm.user.position" required>
<div class="error" ng-show="regForm.position.$touched && regForm.position.
$error.required">Required</div><br>

<button type="submit" ng-disabled="regForm.$invalid">Register</button>


</form>

<div ng-if="vm.users.length > 0" style="max-width: 400px; margin: 30px auto;">


<h3 style="text-align: center;">Registered Users</h3>
<div ng-repeat="u in vm.users track by $index" style="margin-bottom: 15px;">
<pre>{{ u | json }}</pre>
</div>
</div>
<script>
angular.module('jobApp', [])
.controller('JobCtrl', function () {
this.user = {};
this.users = [];

this.submit = (isValid) => {


if (isValid) {
this.users.push(angular.copy(this.user));
this.user = {};
// Optionally reset form state
regForm.$setPristine();
regForm.$setUntouched();
}
};
});
</script>
</body>
</html>

Output:

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
NodeJS.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));

// Updated data: menu items include prices


const restaurants = {
'Pizza Palace': [
{ name: 'Margherita', price: 250 },
{ name: 'Pepperoni', price: 300 },
{ name: 'Cheese Burst', price: 350 }
],
'Burger Bistro': [
{ name: 'Veg Burger', price: 120 },
{ name: 'Chicken Burger', price: 180 },
{ name: 'Cheese Burger', price: 160 }
],
'Sushi World': [
{ name: 'Salmon Roll', price: 400 },
{ name: 'Tuna Nigiri', price: 450 },
{ name: 'Veg Maki', price: 300 }
]
};

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


let html = `<h1>Available Restaurants</h1><ul>`;
for (let r in restaurants) {
html += `<li><a
href="/order?restaurant=${encodeURIComponent(r)}">${r}</a></li>`;
}
html += `</ul>`;
res.send(html);
});

app.get('/order', (req, res) => {


const name = req.query.restaurant;
const menu = restaurants[name];
if (!menu) return res.send('<h2>Restaurant not found</h2><a href="/">Back to
home</a>');

let form = `<h2>Order from <u>${name}</u></h2>


<form method="POST" action="/order">
<input type="hidden" name="restaurant" value="${name}">
<label>Select item:</label><br>
<select name="item">`;

menu.forEach(item => {
form += `<option value="${item.name}">${item.name} -
₹${item.price}</option>`;
});

form += `</select><br><br>
<label>Your Name:</label><br>
<input type="text" name="customer" required><br><br>
<button type="submit">Place Order</button>
</form>`;
res.send(form);
});

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


const { restaurant, item, customer } = req.body;
const selectedMenu = restaurants[restaurant] || [];
const foundItem = selectedMenu.find(i => i.name === item);

if (!foundItem) {
return res.send(`<h2>Item not found in ${restaurant}</h2><a
href="/">Back</a>`);
}

res.send(`<h2>Order Confirmed!</h2>
<p><strong>${customer}</strong>, you have ordered <strong>$
{foundItem.name}</strong> (₹${foundItem.price}) from
<strong>${restaurant}</strong>.</p>
<a href="/">Back to home</a>`);
});

const PORT = 3000;


app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

Output:
6) Implement a program with basic commands on databases and collections
using MongoDB.

const { MongoClient } = require('mongodb');

const url = 'mongodb://127.0.0.1:27017'; // Use MongoDB Atlas connection string


if needed
const client = new MongoClient(url);

async function main() {


try {
await client.connect();
console.log("✅ Connected to MongoDB");

const db = client.db('schoolDB'); // Creates or uses database


const collection = db.collection('students'); // Creates or uses collection

// Insert documents
await collection.insertMany([
{ name: 'Alice', age: 21, course: 'Math' },
{ name: 'Bob', age: 22, course: 'Physics' }
]);
console.log("✅ Documents inserted");

// Find documents
const allStudents = await collection.find().toArray();
console.log("📋 All Students:", allStudents);

// Update one document


await collection.updateOne({ name: 'Alice' }, { $set: { age: 23 } });
console.log("🔄 Updated Alice's age");
// Delete one document
await collection.deleteOne({ name: 'Bob' });
console.log(" Deleted Bob");

// Final check
const updatedList = await collection.find().toArray();
console.log("📋 Final List:", updatedList);

} catch (err) {
console.error("❌ Error:", err);
} finally {
await client.close();
console.log("🔌 MongoDB connection closed");
}
}

main();

Output:

7) Implement CRUD operations on the given dataset using MongoDB.


const { MongoClient } = require('mongodb');

const url = 'mongodb://127.0.0.1:27017'; // Use your Atlas URL if needed


const client = new MongoClient(url);

async function main() {


try {
await client.connect();
console.log("✅ Connected to MongoDB");
const db = client.db("collegeDB");
const collection = db.collection("students");

// 1. CREATE (Insert Documents)


await collection.insertMany([
{ name: "John", age: 22, course: "Math" },
{ name: "Jane", age: 21, course: "Science" },
{ name: "Mike", age: 23, course: "History" }
]);
console.log("🟢 Documents inserted");

// 2. READ (Find Documents)


const allStudents = await collection.find().toArray();
console.log("📋 All Students:", allStudents);

// 3. UPDATE (Update One Document)


await collection.updateOne({ name: "Jane" }, { $set: { age: 22 } });
console.log("🔄 Updated Jane's age");

// 4. DELETE (Delete One Document)


await collection.deleteOne({ name: "Mike" });
console.log(" Deleted Mike");

// Final Output
const finalList = await collection.find().toArray();
console.log("📋 Final List:", finalList);

} catch (err) {
console.error("❌ Error:", err);
} finally {
await client.close();
console.log("🔌 MongoDB connection closed");
}
}

main();
Output:

9. Develop an angular JS form to apply CSS and Events.


1. Server.js - Should be saved under program directory
const express = require('express');
const path = require('path');
const app = express();
const PORT = 3000;
// Serve static files from 'public' folder
app.use(express.static(path.join(__dirname, 'public')));
// Root route
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'FormNew.html'));
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

2. Index.html
• Create a directory with the name public inside your program directory
and save the below file in side public the directory with the name
Index.html
<!DOCTYPE html>
<html ng-app="formApp">
<head>
<meta charset="utf-8">
<title>AngularJS Form Example (No Validation)</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></s
cript>
<style>
.result-box {
margin-top: 10px;
padding: 10px;
border: 1px solid #ccc;
background-color: #eef;
}
</style>
</head>
<body ng-controller="FormController">
<h2>AngularJS Form (No Validation)</h2>
<form name="userForm">
<label>Name:</label>
<input type="text" ng-model="user.name" />
<br><br>
<label>Email:</label>
<input type="text" ng-model="user.email" />
<br><br>
<button type="button" ng-click="submitForm()">Submit</button>
</form>
<div class="result-box" ng-if="submitted">
<h3>Form Submitted!</h3>
<p><strong>Name:</strong> {{ user.name }}</p>
<p><strong>Email:</strong> {{ user.email }}</p>
</div>
<script>
angular.module('formApp', [])
.controller('FormController', function($scope) {
$scope.user = {
name: '',
email: ''
};
$scope.submitted = false;
$scope.submitForm = function() {
$scope.submitted = true;
};
});
</script>
</body>
</html>
Output:
Setup Instructions
1. Create your project: mkdir ex_ajs && cd ex_ajs
2. npm init -y
3. npm install express body-parser
4. File structure:
ex_ajs /
├── public/
│ └── index.html
└── server.js
5. Run the server: node server.js
6. Open in browser: Visit http://localhost:3000

8)Perform Count, Limit, Sort, and Skip operations on the given collections using
MongoDB.
import { MongoClient } from 'mongodb';

async function main() {


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

const db = client.db('myDB');
const col = db.collection('users');

// Insert sample data if collection is empty


const current = await col.countDocuments();
if (current === 0) {
await col.insertMany([
{ username: 'user1', role: 'user', active: true, createdAt: new Date() },
{ username: 'admin', role: 'admin', active: true, createdAt: new Date() },
{ username: 'user2', role: 'user', active: true, createdAt: new Date() },
{ username: 'user3', role: 'user', active: true, createdAt: new Date() },
{ username: 'admin2', role: 'admin', active: true, createdAt: new Date() },
// add more if desired
]);
console.log('Inserted sample data.');
}

const total = await col.countDocuments({});


const adminCount = await col.countDocuments({ role: 'admin' });

const page = 2;
const pageSize = 2;
const skip = (page - 1) * pageSize;

const docs = await col


.find({ active: true })
.sort({ createdAt: -1 })
.skip(skip)
.limit(pageSize)
.toArray();

console.log('Total documents:', total);


console.log('Admins count:', adminCount);
console.log(`Page ${page} results (${docs.length} items):`, docs);

await client.close();
}

main().catch(err => {
console.error(err);
process.exit(1);
});
Output:
Inserted sample data.
Total documents: 5
Admins count: 2
Page 2 results (2 items): [
{
_id: new ObjectId('68470067775b5e16dc1fe6a0'),
username: 'user1',
role: 'user',
active: true,
createdAt: 2025-06-09T15:40:23.703Z
},
{
_id: new ObjectId('68470067775b5e16dc1fe6a2'),
username: 'user2',
role: 'user',
active: true,
createdAt: 2025-06-09T15:40:23.703Z
}
]

You might also like