Assignment Mfd
Assignment Mfd
Q:-1
1. Purpose of the HTTP module in Node.js: The HTTP module in Node.js allows
developers to create and manage web servers and handle HTTP requests and
responses. It is used to build web applications and APIs by enabling communication
between clients and servers.
2. What is React and why it is used in web development? React is a JavaScript library
developed by Facebook for building user interfaces, particularly for single-page
applications. It is used in web development for creating interactive, reusable UI
components, and efficiently updating the view with changes in the data using a virtual
DOM.
3. What is the use of Node.js? Node.js is a JavaScript runtime built on Chrome’s V8
JavaScript engine that allows developers to run JavaScript code on the server-side. It
is used for building fast, scalable, and real-time network applications, especially for
handling I/O operations like web servers and APIs.
4. Different data types in Node.js: Node.js supports various data types similar to
JavaScript. The common data types are:
o String: Represents textual data.
o Number: Represents numeric values (integers or floating-point numbers).
o Boolean: Represents true or false values.
o Object: Represents a collection of key-value pairs.
o Array: Represents an ordered list of values.
o Null: Represents an empty or non-existent value.
o Undefined: Represents a variable that has been declared but not assigned a
value.
o Buffer: Represents binary data in Node.js (mainly used for I/O operations).
Q:2
1. Create a simple Node.js web server that responds with "Hello, World!"
Code:
javascript
Copy code
// Load the http module to create an HTTP server
const http = require('http');
// The server listens on port 3000, and when it's ready, logs a message
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Explanation:
• require('http'): Loads the HTTP module that allows us to create an HTTP server.
• http.createServer(): Creates a server that listens for requests and sends a
response. The callback function takes two arguments: req (request) and res
(response).
• res.writeHead(200, { 'Content-Type': 'text/plain' }): Sends an HTTP
response with status code 200 (OK) and specifies that the response content type is
plain text.
• res.end('Hello, World!\n'): Ends the response and sends the message "Hello,
World!" to the client.
• server.listen(3000): Makes the server listen for incoming requests on port 3000.
Middleware in Node.js, especially in frameworks like Express, refers to functions that have
access to the request (req), response (res), and the next middleware function in the request-
response cycle. Middleware functions can modify the request, the response, or end the
request-response cycle.
javascript
Copy code
const express = require('express');
const app = express();
NPM (Node Package Manager) is a package manager for JavaScript and is the default
package manager for Node.js. It simplifies the management of project dependencies, allows
developers to easily share and reuse code, and makes it easy to install libraries and tools for
Node.js projects.
• Package Management: NPM allows developers to easily install, update, and manage
third-party libraries (called packages) that are used in their Node.js applications. This
is done using the npm install command.
• Dependency Management: NPM automatically resolves and installs dependencies
required by a package. It ensures that the correct versions of libraries are installed for
compatibility.
• Publishing and Sharing Packages: Developers can publish their own packages to
the NPM registry, making it easy for others to install and use them in their projects.
To publish a package, developers use npm publish.
• NPM Scripts: NPM allows defining custom scripts in a package.json file, such as
build, test, or start scripts, making it easy to automate tasks.
• NPM Registry: The NPM registry is a large collection of open-source packages
available for use. It is the largest ecosystem of open-source libraries in the world.
Basic commands in NPM:
Overall, NPM plays a crucial role in the Node.js ecosystem by simplifying the process of
managing and using packages.
Q-3
Here’s a Node.js application that serves an HTML file and logs request headers.
Code:
Explanation:
You will need an index.html file in the same directory as this Node.js script for the server to
serve it.
To create an HTTPS server, you need an SSL/TLS certificate. In the case of a self-signed
certificate, you can generate one using tools like OpenSSL. Here's how to create an HTTPS
server with self-signed certificates.
You can generate a self-signed certificate with OpenSSL using the following commands:
Explanation:
• https.createServer(): Creates an HTTPS server using the provided options (key and
cert).
• fs.readFileSync(): Reads the self-signed certificate and private key from files
(server.crt and private.key).
• res.writeHead(): Sets the response status code and headers.
• server.listen(): Starts the server on port 3000, which can now handle HTTPS requests
securely.
When you visit https://localhost:3000/, your browser may show a warning about the
self-signed certificate, but you can proceed with the connection.
Here’s the simplest way to create a server in Node.js using the built-in HTTP module:
Code:
Explanation:
Code:
Explanation:
When the server is running, visiting http://localhost:3000/ will display "Hello World"
in the browser.
Assignment : 4
Express.js is a fast, minimalist, and flexible web application framework for Node.js. It
simplifies the process of building web applications and APIs by providing a set of features
and tools, such as routing, middleware support, and easy handling of HTTP requests. It is
commonly used in Node.js applications because it simplifies the creation of robust, scalable
web servers and allows developers to focus more on building features rather than dealing
with low-level HTTP requests and responses.
• Serving static pages: In Express, static files such as images, CSS, and JavaScript
files can be served using the built-in express.static() middleware. This
middleware allows the app to serve files from a specified directory.
Example:
app.use(express.static('public'));
• Listing directory contents: Express does not natively list directory contents, but you
can implement this functionality using the fs module from Node.js to read and return
the contents of a directory.
• Handling cookies: Express allows handling cookies with the help of the cookie-
parser middleware. This middleware parses cookies attached to the incoming
requests and makes them available in req.cookies.
Example:
app.use(cookieParser());
Example:
Example:
app.use(compression());
Example:
app.use(timeout('5s'));
• Express response object: The response object (res) in Express is used to send back
the HTTP response to the client. It provides methods like res.send(), res.json(),
res.status(), and res.redirect() to handle the response.
1. Write a simple Express application that serves a static HTML page from a directory called "public".
Include the code and explain how static files are served.
Code:
Explanation:
• express.static() middleware is used to serve static files like HTML, CSS, and JavaScript
from the public directory.
• path.join(__dirname, 'public') generates the absolute path to the public
directory, ensuring platform compatibility (e.g., Windows vs Linux file paths).
• The server will respond to requests with files from the public directory (e.g.,
index.html).
2. Explain how to use middleware to handle cookies in an Express application. Provide an example of
setting and reading cookies.
Code Example:
Explanation:
1. Create an Express application that accepts JSON requests and HTML form inputs, handling both
types of data. Include the code and explain how to parse these inputs.
Code:
Explanation:
2. Discuss the concept of REST in the context of Express.js and create a simple RESTful API with routes
for GET and POST methods.
Code:
app.use(express.json());
Explanation:
• GET /users: Retrieves a list of users from the in-memory data store and sends it as JSON.
• POST /users: Accepts a new user (in JSON format) via a POST request and adds it to the
users array. The new user is then returned with a status code of 201 (Created).
• REST (Representational State Transfer) is a software architectural style that is based on a set
of principles and constraints, which guide the design of stateless client-server
communication over HTTP.
• Resources: Each resource (e.g., user, product) is identified by a unique URL.
• HTTP Methods: Standard HTTP methods (GET, POST, PUT, DELETE) are used to perform
CRUD (Create, Read, Update, Delete) operations on resources.
• Stateless Communication: Each request from the client to the server must contain all the
information needed to understand and process the request. The server does not store any
state between requests.
• JSON: Data is typically exchanged in the form of JSON, making it easy to parse and work
with.
Node.js, with frameworks like Express, makes it easy to build RESTful APIs by defining
routes for HTTP methods and performing actions on resources. The RESTful API can be
extended by adding additional routes, using middleware, and interacting with databases to
persist data.
Assignment:5
SQL Databases (Relational Databases) are based on a structured schema that defines tables
with predefined columns. They use the SQL (Structured Query Language) for managing and
manipulating data. Data is stored in rows, and relationships between different tables are
established using foreign keys. Examples of SQL databases include MySQL, PostgreSQL,
and SQLite.
NoSQL Databases, on the other hand, are non-relational databases that do not require a fixed
schema. They store data in various formats such as key-value pairs, documents, wide-column
stores, or graphs. NoSQL databases are more flexible in terms of schema and are highly
scalable. Examples include MongoDB, Cassandra, and CouchDB.
Key Differences:
• Structure: SQL uses a fixed schema with tables, whereas NoSQL uses flexible schema types
like documents or key-value pairs.
• Scalability: NoSQL is typically horizontally scalable (distributed), while SQL is vertically
scalable.
• Transactions: SQL databases follow ACID properties, ensuring strong consistency, while
NoSQL databases may use eventual consistency for scalability and performance.
3. Explain the basic concepts of MongoDB. Include definitions for Document, Collection, and Database.
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "Alice",
"age": 25,
"email": "[email protected]"
}
Example: A usersDB database might contain collections like users, orders, and
products.
A MongoDB document is a set of key-value pairs stored in BSON (Binary JSON) format. It
represents a single data record and can contain nested data structures such as arrays or other
documents. Unlike rows in SQL, MongoDB documents are schema-less, meaning each
document can have different fields and data types.
Example Document:
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "John",
"email": "[email protected]",
"age": 30,
"addresses": [
{ "type": "home", "address": "123 Street Name" },
{ "type": "work", "address": "456 Business Rd." }
]
}
In MongoDB, the _id field is a unique identifier for each document in a collection. If you
don't explicitly provide an _id when inserting a document, MongoDB will automatically
generate a unique ObjectId for it. The _id field is used to ensure the uniqueness of each
document in a collection and is indexed by default for fast retrieval.
Example:
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "Alice"
}
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides
a higher-level abstraction over the native MongoDB driver by offering a schema-based
solution to model data, allowing developers to define how the data should be structured,
validated, and queried. Mongoose helps with data validation, casting, business logic, and
more, making it easier to interact with MongoDB in Node.js applications.
Benefits of Mongoose:
• Schema Flexibility: MongoDB is schema-less, which allows for dynamic and flexible data
storage. You don’t need to define the schema upfront, and documents in a collection can
have different structures.
• Scalability: MongoDB provides built-in horizontal scaling through sharding, making it
suitable for applications with large datasets or traffic.
• Performance: MongoDB stores data in memory-mapped files and can quickly index large
volumes of data. It is optimized for high throughput and real-time applications.
• High Availability: MongoDB supports replication (master-slave) for redundancy and fault
tolerance, ensuring high availability.
• Ease of Use: MongoDB is developer-friendly, with simple JSON-based queries and flexible
data types, unlike SQL databases that require complex joins and predefined schemas.
2. What is "callback hell" in JavaScript, and how does it relate to MongoDB operations? Provide an
example.
Callback hell refers to the situation where multiple nested callbacks are used in
asynchronous programming, leading to code that is difficult to read, maintain, and debug.
In MongoDB operations, callback hell occurs when performing multiple asynchronous
operations, such as querying, inserting, or updating documents, with each operation relying
on a callback function.
Example:
Solution: Using Promises or async/await can eliminate callback hell and make the code
more readable and maintainable.
3. Explain the CRUD operations in MongoDB and give an example of each operation using the
MongoDB shell.
4. Explain the concept of Promises in JavaScript. How do Promises improve the management of
asynchronous code in MongoDB? Provide a simple example.
Advantages of Promises:
Example:
1. Create a simple Node.js application that uses Mongoose to connect to a MongoDB database,
defines a schema, and performs CRUD operations (Create, Read, Update, Delete) on a collection.
Code Example:
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser:
true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Error connecting to MongoDB', err));
// Define a schema
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String
});
// Create a model
const User = mongoose.model('User', userSchema);
// CRUD Operations:
// Create
const createUser = async () => {
const user = new User({ name: 'Alice', age: 25, email:
'[email protected]' });
await user.save();
console.log('User created:', user);
};
// Read
const getUser = async () => {
const user = await User.findOne({ name: 'Alice' });
console.log('User found:', user);
};
// Update
const updateUser = async () => {
const user = await User.findOneAndUpdate({ name: 'Alice' }, { age: 26 });
console.log('User updated:', user);
};
// Delete
const deleteUser = async () => {
const result = await User.deleteOne({ name: 'Alice' });
console.log('User deleted:', result);
};
2. Explain in detail the process of setting up Mongoose in a Node.js application. Include the steps for
creating a schema, defining models, and performing CRUD operations. Provide an example where a
"User" schema is created and basic CRUD operations are performed.
1. Install Mongoose:
2. npm install mongoose
3. Connect to MongoDB: In the application, use mongoose.connect() to connect to
the MongoDB instance.
4. Define a Schema: A schema defines the structure of documents in a collection. Use
new mongoose.Schema() to define the schema.
5. Create a Model: A model is a wrapper for the schema. Use mongoose.model() to
define a model that you will interact with for CRUD operations.
6. CRUD Operations: Use model methods like create(), find(), update(), and
delete() to perform CRUD operations.
// Create
const createUser = async () => {
const user = new User({ name: 'John', age: 30, email: '[email protected]'
});
await user.save();
console.log('User Created:', user);
};
// Read
const getUser = async () => {
const user = await User.findOne({ name: 'John' });
console.log('User Found:', user
); };
// Delete const deleteUser = async () => { const result = await User.deleteOne({ name: 'John'
}); console.log('User Deleted:', result); };
---
**Creating an Index**:
```javascript
// Create an index on the "name" field
db.users.createIndex({ name: 1 });
The { name: 1 } indicates an ascending order index. For descending order, you can use {
name: -1 }.
Indexes improve query speed, but they come with a tradeoff in terms of memory usage and
write performance since indexes need to be updated whenever a document is inserted or
updated.