NodeJS Practice Questions
NodeJS Practice Questions
Problems
You run a movie theater, and you want to offer discounts based on a person's age. Write a
JavaScript program that asks the user for their age and then displays a message:
- If the age is less than 18, display "You get a 20% discount!"
- If the age is between 18 and 65 (inclusive), display "Normal ticket price applies."
- If the age is 65 or older, display "You get a 30% senior discount!"
Create a JavaScript program to calculate the area of a rectangle. Ask the user for the length
and width of the rectangle and store them in variables. Calculate and display the area using
the formula: `area = length * width`.
You're creating an online store. Define a JavaScript object named "product" with the following
properties:
- name (string)
- price (number)
- inStock (boolean)
Create at least three products using your object template and display their details using
console.log.
Problem 4: Arrays
You're organizing a party and want to keep track of the guest list. Create an array called
"guestList" and add the names of at least five guests. Then, write a program that checks if a
given name is on the guest list. If the name is found, display "Welcome to the party, [name]!";
otherwise, display "Sorry, you're not on the guest list."
Problem 5: JSON (JavaScript Object Notation)
You're working on a weather app. Create a JSON object representing the weather forecast for
a specific day. Include properties like "date," "temperature," "conditions," and "humidity."
Display the information using console.log.
Remember to encourage your students to experiment and think creatively while solving these
problems. They can use the concepts you've taught them to come up with their own solutions.
This will not only help solidify their understanding but also foster their problem-solving skills in
JavaScript.
Solution
const product1 = {
name: "Smartphone",
price: 399.99,
inStock: true
};
const product2 = {
name: "Laptop",
price: 999.99,
inStock: false
};
const product3 = {
name: "Headphones",
price: 49.99,
inStock: true
};
console.log(product1);
console.log(product2);
console.log(product3);
Problem 4: Arrays
const weatherForecast = {
date: "2023-08-06",
temperature: 28,
conditions: "Sunny",
humidity: 60
};
DAY - 02
Problems
You're starting a new project and want to manage your project's dependencies using NPM.
Explain the purpose of NPM and how it helps in managing packages. Create a simple
package.json file for your project, specifying the name, version, and a few dependencies of
your choice.
Write a JavaScript function named calculateCircleArea that takes the radius of a circle
as a parameter and returns the area of the circle. You can use the formula area = π *
radius^2. Test the function with a few different radii.
Write a Node.js program that uses the fs module to read the contents of a text file named
"notes.txt" and display them in the console.
Create a Node.js program that uses the os module to display the following system
information:
Use the lodash library to solve the following problem: Given an array of numbers, write a
function that returns the sum of all even numbers in the array. Use the _.sumBy function from
lodash to achieve this.
Solution
Problem 1: NPM and Package.json
NPM (Node Package Manager) is a tool that helps you manage libraries and packages in your Node.js
projects. It allows you to easily install, update, and remove packages that you need for your project.
To create a package.json file for your project, you can use the following example:
{
"name": "my-project",
"version": "1.0.0",
"dependencies": {
"lodash": "^4.17.21"
}
}
function calculateCircleArea(radius) {
return Math.PI * radius ** 2;
}
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
function multiply(x, y) {
return x * y;
}
function divide(x, y) {
return x / y;
}
const fs = require('fs');
fs.readFile('notes.txt', 'utf8', (err, data) => {
if (err) {
console.error("Error reading file:", err);
return;
}
console.log(data);
});
const os = require('os');
const _ = require('lodash');
function sumOfEvenNumbers(numbers) {
const evenNumbers = _.filter(numbers, num => num % 2 === 0);
return _.sumBy(evenNumbers);
}
DAY - 03
Problems
Problem 1: Understanding Servers and Express.js
Explain in your own words what a server is in the context of Node.js. Then, write step-by-step instructions on
how to create a basic server using Express.js.
b) Given a JSON data string: {"name": "Alice", "age": 25, "hobbies": ["reading",
"painting"]}, explain how you would extract the value of the "age" key.
c) How would you convert the following object into a JSON data string? {"title": "Book", "pages":
200}
a) Explain what the HTTP GET method is used for in the context of web development.
b) Write the code to create a simple Express.js route that responds with "Hello, World!" when a user visits the
root URL ("/").
a) Given a JSON data string: {"product": "Laptop", "price": 999.99}, explain how you would
parse it into a JavaScript object.
b) You have an object: { "name": "Bob", "age": 30 }. How would you convert it into a JSON data
string?
Imagine you're building an API for a weather app. Your API needs an endpoint to retrieve the current weather.
Create an Express.js route that responds with a JSON object containing the current temperature, conditions,
and city.
Solution
● A server in Node.js is a computer program that receives and responds to requests from clients (like
web browsers or mobile apps) over a network. It processes requests and sends back appropriate
responses.
● To create a basic server using Express.js:
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
a) JSON (JavaScript Object Notation) is a lightweight data interchange format used to exchange data between
a server and a client. It's easy for humans to read and write, and it's easy for machines to parse and generate.
b) To extract the value of the "age" key from the JSON data:
a) An API (Application Programming Interface) is a set of rules and protocols that allows different software
components to communicate and interact with each other. It defines how requests and responses should be
structured.
b) An endpoint is a specific URL (Uniform Resource Locator) that represents a particular function or service
provided by an API. It's the specific location where clients can make requests to access certain data or perform
actions.
c) Example of an endpoint in a social media app: /users/{username} to retrieve user information based on
their username.
a) The HTTP GET method is used to request data from a server. It's often used to retrieve information or
resources from a specified URL.
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
DAY - 04
Problems
Question 1: Difference Between MongoDB Server & Node.js Server
Explain the difference between a MongoDB server and a Node.js server in terms of their roles and
functionalities. Provide examples of situations where you would use each server type.
a) Write a MongoDB query to create a new document in a collection named "students" with fields "name,"
"age," and "grade."
b) Write a MongoDB query to update the "age" field of a document in the "employees" collection with the name
"John" to 30.
c) Write a MongoDB query to delete a document from the "products" collection with the name "Product A."
d) Write a MongoDB query to retrieve all documents from the "orders" collection where the total amount is
greater than $100.
Explain the main differences between SQL databases and MongoDB in terms of data structure, querying
language, and use cases. Provide examples of scenarios where you might choose one over the other.
Question 4: Query Comparison
Compare and contrast the following MongoDB and SQL queries for retrieving data:
Solution
Answer: The MongoDB server is responsible for storing and managing data in the MongoDB database. It
handles data storage, retrieval, and manipulation operations. On the other hand, a Node.js server is a runtime
environment that executes JavaScript code. It handles incoming requests from clients, processes them, and
can interact with databases like MongoDB to retrieve or update data. You would use a MongoDB server to
store and manage data, while a Node.js server is used to handle application logic and serve client requests.
a) Answer:
b) Answer:
c) Answer:
d) Answer:
db.orders.find({ totalAmount: { $gt: 100 } });
Answer: SQL databases use structured tables with rows and columns to store data, while MongoDB uses
flexible and dynamic documents in collections. SQL databases use SQL as a querying language, while
MongoDB uses a JavaScript-like syntax for queries. SQL databases are suitable for applications with well-
defined and structured data, such as financial systems. MongoDB is better for projects with changing or
unstructured data, like content management systems or real-time analytics.
c) Answer: Both queries calculate the total amount of orders grouped by status.
DAY - 05
Problems
Create a POST method API to store data or menu items as per the schema we discussed ( /menu )
Create a GET method API to List down the All Menu Items as per the schema we discussed ( /menu )
You're building a simple task management application. Your task is to create a POST API endpoint for adding
new tasks to the database. Assume you've already set up an Express application and connected it to your
MongoDB using Mongoose.
a) Design the Mongoose schema for a "Task" with fields for "title," "description," "priority," and "dueDate."
b) Create a POST API endpoint /api/tasks that allow clients to submit new tasks to the database. Ensure it
handles request validation and responds with the newly created task.
Continuing with the task management application, you need to create a GET API endpoint for retrieving a list of
tasks from the database.
Create a GET API endpoint /api/tasks that retrieve a list of all tasks from the database. Ensure it handles
errors and responds with the list of tasks in JSON format.
Solution
Answer 1: POST method API to store data or menu items as per the schema we discussed on /menu
a) Design the Mongoose schema for a "Task" with fields for "title," "description," "priority," and "dueDate."
module.exports = Task;
b) Create a POST API endpoint /api/tasks that allow clients to submit new tasks to the database. Ensure it
handles request validation and responds to the newly created task.
a) Create a GET API endpoint /api/tasks that retrieve a list of all tasks from the database
Problems
Question 1: Create a parameterized GET Method API for the Menu Item on the Basis of
taste Type via using Express Router
( /menu/:taste )
Question 2: Create a PUT Method API to update the MenuItem Records ( menu/:id )
Question 3: Create a DELETE Method API to delete the MenuItem Records ( menu/:id )
Solution
if (!response) {
return res.status(404).json({ error: 'Menu Item not found' });
}
console.log('data updated');
res.status(200).json(response);
}catch(err){
console.log(err);
res.status(500).json({error: 'Internal Server Error'});
}
})