Node.
js
Definition: Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaSc
Key Features:
- Asynchronous and event-driven.
- Single-threaded but highly scalable due to its non-blocking I/O model.
- Uses the V8 engine, which compiles JavaScript into machine code.
- Package management with npm (Node Package Manager).
Common Use Cases:
- Building RESTful APIs.
- Real-time applications like chat applications.
- Streaming applications.
Express.js
Definition: Express.js is a fast, minimal, and flexible Node.js web application framework.
Key Features:
- Simplifies the process of routing, middleware integration, and server setup.
- Offers a robust set of HTTP utilities and middleware.
- Supports template engines like Pug, EJS, and Handlebars.
Common Use Cases:
- Creating web servers.
- Handling API requests and responses.
- Managing middleware for handling different tasks like authentication and error handling.
Creating a Server in Express.js
Steps to Create a Server:
1. Install Express:
npm install express
2. Create a Basic Server:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
3. Add Middleware (e.g., express.json() for parsing JSON requests).
4. Define Routes: Create endpoints to handle different HTTP requests.
5. Error Handling: Add error-handling middleware for robust server behavior.
Advantages of Using Express for Servers:
- Simplified setup and configuration.
- Extensive middleware ecosystem.
- Easy integration with databases and templating engines.
MVC (Model-View-Controller) Architecture
Definition: A design pattern that separates an application into three interconnected components:
1. Model: Manages the data, logic, and rules of the application.
2. View: Displays data to the user and handles user interactions.
3. Controller: Acts as an intermediary between the Model and View.
Advantages:
- Separation of concerns.
- Easier to maintain and scale.
- Encourages code reusability.
Implementation in Node.js:
- Model: Defines schema and interacts with the database.
- View: Renders UI (e.g., HTML templates).
- Controller: Contains the application logic and handles user requests.
Middlewares in Node.js
Definition: Functions that execute during the lifecycle of a request to a server.
Types:
1. Application-level middleware: Bound to the app object and executes for all or specific routes.
2. Router-level middleware: Attached to a specific router instance.
3. Error-handling middleware: Handles errors in the application.
4. Built-in middleware: Provided by Express (e.g., express.json() and express.static()).
5. Third-party middleware: Installed via npm (e.g., morgan, body-parser).
Example:
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
File Handling in Node.js
Core Module: fs (File System)
Operations:
1. Reading Files:
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
2. Writing Files:
fs.writeFile('example.txt', 'Hello, World!', (err) => {
if (err) throw err;
console.log('File written successfully');
});
3. Appending Data:
fs.appendFile('example.txt', ' Additional data.', (err) => {
if (err) throw err;
console.log('Data appended successfully');
});
4. Deleting Files:
fs.unlink('example.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully');
});
Schema Creation
Definition: A schema defines the structure of a document in a database.
In MongoDB:
- Use libraries like Mongoose to define schemas.
- Example:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, default: 18 },
});
const User = mongoose.model('User', userSchema);
Database Creation
In MongoDB:
1. Connecting to MongoDB:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Database connected'))
.catch(err => console.error('Connection error', err));
2. Creating Collections: Collections are automatically created when a model is used to insert data into the d
MongoDB CRUD Operations
1. Create:
const newUser = new User({ name: 'John', email: '[email protected]', age: 25 });
newUser.save()
.then(user => console.log('User created:', user))
.catch(err => console.error(err));
2. Read:
Find all documents:
User.find()
.then(users => console.log(users))
.catch(err => console.error(err));
Find by condition:
.then(user => console.log(user))
.catch(err => console.error(err));
3. Update:
Update one document:
User.updateOne({ email: '[email protected]' }, { $set: { age: 30 } })
.then(result => console.log('Update result:', result))
.catch(err => console.error(err));
4. Delete:
Delete one document:
.then(result => console.log('Delete result:', result))
.catch(err => console.error(err));