0% found this document useful (0 votes)
7 views21 pages

MERN Full Stack File

The document outlines a series of programming tasks and examples primarily focused on JavaScript, Node.js, and Express.js. It includes functions for basic operations, DOM manipulation, error handling, API interactions, and CRUD operations with MongoDB. Each task is accompanied by code snippets and expected outputs, showcasing practical implementations of various programming concepts.

Uploaded by

yadava05062
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)
7 views21 pages

MERN Full Stack File

The document outlines a series of programming tasks and examples primarily focused on JavaScript, Node.js, and Express.js. It includes functions for basic operations, DOM manipulation, error handling, API interactions, and CRUD operations with MongoDB. Each task is accompanied by code snippets and expected outputs, showcasing practical implementations of various programming concepts.

Uploaded by

yadava05062
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/ 21

INDEX

Sr. No. Program Date Signature

1 Write a function that takes two numbers and returns their sum.

2 Implement a program that checks whether a given number is


even or odd using conditional statements.
3 Create a function using arrow notation that calculates the
square of a number.
4 Use the map() function to double the values in an array.

5 Create an object representing a car with properties like make,


model, and year. Print the car’s details using object
destructuring.
6 Write a function that returns the sum of all elements in an array
using the reduce() method.
7 Create a simple webpage and manipulate its DOM using
JavaScript.
8 Handle an error scenario using try...catch in JavaScript.
9 Implement a program that fetches data from a public API using
fetch() and handles errors properly.
10 Write a Node.js module that exports a function to calculate the
factorial of a number.
11 Build a basic Node.js application that reads and writes files
using the fs module.
12 Create a simple Node.js script that prints "Hello, Node.js!" to
the console.
13 Set up an Express.js server and define a route that returns
“Welcome to Express.js!” when accessed.
14 Create a REST API in Express.js with routes for GET, POST,
PUT, and DELETE.
15 Use middleware like body-parser to process JSON requests in
an Express application.
16 Create a Mongoose schema and model for a basic user entity.

17 Query data from a MongoDB collection using the find()


method.
18 Implement basic authentication in an Express.js application
using middleware.
19 Write a MongoDB script to insert multiple documents into a
collection.
20 Implement a CRUD (Create, Read, Update, Delete) application
using MongoDB and Mongoose
Q1: Write a function that takes two numbers and returns their
sum.
function sum(a, b) {
return a + b;
}

Output: 15
Q2: Implement a program that checks whether a given
number is even or odd using conditional statements.
const num = 10;
if (num % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}

Output: Even
Q3: Create a function using arrow notation that calculates the
square of a number.
const square = num => num * num;
console.log(square(5));

Output: 25
Q4: Use the map() function to double the values in an array.
const arr = [1, 2, 3, 4];
const doubled = arr.map(num => num * 2);
console.log(doubled);

Output: [2, 4, 6, 8]
Q5: Create an object representing a car with properties like
make, model, and year. Print the car’s details using object
destructuring.
const car = { make: "Toyota", model: "Corolla", year: 2020 };
const { make, model, year } = car;
console.log(`Make: ${make}, Model: ${model}, Year: ${year}`);

Output: Make: Toyota, Model: Corolla, Year: 2020


Q6: Write a function that returns the sum of all elements in an
array using the reduce() method.
const arr = [1, 2, 3, 4];
const sum = arr.reduce((acc, val) => acc + val, 0);
console.log(sum);

Output: 10
Q7: Create a simple webpage and manipulate its DOM using
JavaScript.
<!-- HTML -->
<p id="demo">Hello</p>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("demo").innerHTML = "Text changed!";
}
</script>

Output: Button changes text to 'Text changed!'


Q8: Handle an error scenario using try...catch in JavaScript.
try {
let x = y + 1; // y is not defined
} catch (error) {
console.error("Error occurred:", error.message);
}

Output: Error occurred: y is not defined


Q9: Implement a program that fetches data from a public API
using fetch() and handles errors properly.
fetch('https://api.publicapis.org/entries')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));

Output: Displays JSON data from API or error


Q10: Write a Node.js module that exports a function to
calculate the factorial of a number.
// factorial.js
function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}
module.exports = factorial;

Output: Function exported to calculate factorial


Q11: Build a basic Node.js application that reads and writes
files using the fs module.
const fs = require('fs');
fs.writeFileSync('output.txt', 'Hello, file system!');
const content = fs.readFileSync('output.txt', 'utf-8');
console.log(content);

Output: File written and read: Hello, file system!


Q12: Create a simple Node.js script that prints "Hello,
Node.js!" to the console.
console.log("Hello, Node.js!");

Output: Hello, Node.js!


Q13: Set up an Express.js server and define a route that
returns “Welcome to Express.js!” when accessed.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Express.js!');
});
app.listen(3000, () => console.log('Server running on port 3000'));

Output: Server returns 'Welcome to Express.js!'


Q14: Create a REST API in Express.js with routes for GET,
POST, PUT, and DELETE.
const express = require('express');
const app = express();
app.use(express.json());

let items = [];

app.get('/items', (req, res) => res.json(items));


app.post('/items', (req, res) => {
items.push(req.body);
res.status(201).send('Item added');
});
app.put('/items/:index', (req, res) => {
items[req.params.index] = req.body;
res.send('Item updated');
});
app.delete('/items/:index', (req, res) => {
items.splice(req.params.index, 1);
res.send('Item deleted');
});

app.listen(3000);

Output: REST API handling GET, POST, PUT, DELETE


Q15: Use middleware like body-parser to process JSON
requests in an Express application.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());

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


res.send(`Received: ${JSON.stringify(req.body)}`);
});

app.listen(3000);

Output: JSON body processed by body-parser


Q16: Create a Mongoose schema and model for a basic user
entity.
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({


name: String,
email: String,
password: String
});

const User = mongoose.model('User', userSchema);

Output: Mongoose model created for user


Q17: Query data from a MongoDB collection using the find()
method.
User.find({}, (err, users) => {
if (err) console.error(err);
else console.log(users);
});

Output: Displays all user documents


Q18: Implement basic authentication in an Express.js
application using middleware.
const express = require('express');
const app = express();

const auth = (req, res, next) => {


const token = req.headers['authorization'];
if (token === 'secret-token') next();
else res.status(403).send('Forbidden');
};

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


res.send('Authenticated');
});

app.listen(3000);

Output: Route protected with basic auth


Q19: Write a MongoDB script to insert multiple documents
into a collection.
db.users.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
]);

Output: 3 users inserted into MongoDB

Q20: Implement a CRUD (Create, Read, Update, Delete) application


using MongoDB and Mongoose
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/testDB');

const userSchema = new mongoose.Schema({


name: String,
email: String
});
const User = mongoose.model('User', userSchema);

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


const user = new User(req.body);
await user.save();
res.send(user);
});

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


const users = await User.find();
res.send(users);
});

app.put('/users/:id', async (req, res) => {


const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(user);
});
app.delete('/users/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.send('User deleted');
});
app.listen(3000);

Output: CRUD operations handled via Express and Mongoose

You might also like