Node.js, React, Express.js, MongoDB: Key Concepts
Node.js, React, Express.js, and MongoDB: Key Concepts
Node.js Fundamentals
1) Write any four built-in modules in Node.js.
fs, http, path, os.
2) What is the File System module in Node.js?
The fs module in Node.js handles file operations like reading, writing, and deleting files.
3) What is Nodemon?
Nodemon is a tool that automatically restarts Node.js applications when file changes are detected.
4) What is the full form of REST API?
REST API stands for Representational State Transfer Application Programming Interface.
React Fundamentals
5) What is Props in React?
Props (short for “properties”) are used to pass data from one component to another in React.
6) What is JSX?
JSX (JavaScript XML) is a syntax extension in React that allows writing HTML-like code within JavaScript.
7) What is useState in React Hooks?
useState is a React Hook that allows adding state to functional components.
Node.js Modules Explained
1) What are Modules in Node.js? Explain core module in Node.js with example.
In Node.js, modules are reusable blocks of code that encapsulate related functionality. They help organize code into smaller, manageable pieces. There are three types of modules in Node.js: Core Modules, Local Modules, and Third-Party Modules.
Core Modules are built into Node.js and don’t require installation. They can be directly imported using the require()
function.
Example:
const fs = require('fs'); // Importing the File System (fs) core module
// Using the fs module to read a file
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
In this example, the fs
module is used to handle file operations like reading files.
Express.js Routing
1) Explain Routing in Express.js with example.
Routing in Express.js is the process of defining the endpoints (URIs) and the HTTP methods (GET, POST, PUT, DELETE) that the server will respond to.
Example:
const express = require('express');
const app = express();
const port = 3000;
// Define routes
app.get('/', (req, res) => {
res.send('Welcome to the Home Page!');
});
app.get('/about', (req, res) => {
res.send('About Us');
});
// Start the server
app.listen(port, () => {
console.log(`Server running at <a href="http://localhost">http://localhost:${port}</a>`);
});
In this example:
app.get()
defines a route for handling GET requests at the specified path.
When you visit http://localhost:3000/, “Welcome to the Home Page!” will be displayed.
Visiting http://localhost:3000/about will display “About Us”.
Body Parser Module in Express.js
2) What is Body Parser Module? Explain in detail with example.
Body-parser is a middleware in Express.js used to parse incoming request bodies before handling them. It extracts the body data from HTTP requests and makes it accessible through req.body
.
Before Express 4.16.0, body-parser was a separate package. Now it’s built into Express but can still be imported separately if needed.
Example:
Install body-parser:
npm install body-parser
Code:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
// Middleware to parse JSON data
app.use(bodyParser.json());
// POST route to handle incoming JSON data
app.post('/user', (req, res) => {
const { name, age } = req.body;
res.send(`User: ${name}, Age: ${age}`);
});
// Start the server
app.listen(port, () => {
console.log(`Server running at <a href="http://localhost">http://localhost:${port}</a>`);
});
Explanation:
bodyParser.json()
parses JSON-formatted request bodies and makes the data available through req.body
.
If a POST request is sent to http://localhost:3000/user with a JSON payload:
{
"name": "Alice",
"age": 25
}
The server responds with:
User: Alice, Age: 25
REST API Explained
1) What is REST API? Explain the HTTP methods used in REST-based architecture.
REST (Representational State Transfer) API is a set of rules and conventions for building web services. It allows communication between a client and a server using standard HTTP methods. RESTful APIs are stateless, meaning each request from the client to the server must contain all the information needed to understand and process the request.
Key Principles of REST:
- Statelessness: No session is stored on the server.
- Client-Server Architecture: Separation between the frontend (client) and backend (server).
- Uniform Interface: Standardized way to access resources using URIs (Uniform Resource Identifiers).
- CRUD Operations: Each HTTP method corresponds to a CRUD (Create, Read, Update, Delete) operation.
HTTP Methods in RESTful Architecture:
GET: Retrieves data from the server.
- Example: Fetching all users.
- Endpoint:
GET /users
POST: Sends data to the server to create a new resource.
- Example: Creating a new user.
- Endpoint:
POST /users
-
Payload:
{ "name": "Alice", "age": 25 }
PUT: Updates an existing resource.
- Example: Updating user details.
- Endpoint:
PUT /users/1
-
Payload:
{ "name": "Alice", "age": 26 }
PATCH: Partially updates an existing resource.
- Example: Updating only the user’s age.
- Endpoint:
PATCH /users/1
-
Payload:
{ "age": 27 }
DELETE: Removes a resource from the server.
- Example: Deleting a user.
- Endpoint:
DELETE /users/1
Example in Express.js:
const express = require('express');
const app = express();
app.use(express.json());
app.get('/users', (req, res) => res.send('Get all users'));
app.post('/users', (req, res) => res.send('Create a user'));
app.put('/users/:id', (req, res) => res.send('Update user with ID ' + req.params.id));
app.delete('/users/:id', (req, res) => res.send('Delete user with ID ' + req.params.id));
app.listen(3000, () => console.log('Server running on port 3000'));
JSON and JSON Parsing
1) What is JSON? What is JSON Parsing? Explain in detail with example.
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and easy to parse for machines. It is commonly used to transmit data between a server and a web application.
Example of JSON:
{
"name": "Alice",
"age": 25,
"skills": ["JavaScript", "React", "Node.js"]
}
JSON Parsing:
Parsing JSON means converting a JSON string into a JavaScript object (or vice versa).
In JavaScript:
// JSON String
const jsonString = '{"name": "Alice", "age": 25}';
// Parsing JSON String to Object
const user = JSON.parse(jsonString);
console.log(user.name); // Output: Alice
// Converting Object to JSON String
const jsonStr = JSON.stringify(user);
console.log(jsonStr); // Output: {"name":"Alice","age":25}
MongoDB Concepts
2) What is MongoDB? Explain Database, Document, and Collection in detail.
MongoDB is a NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON). It is highly scalable and suitable for handling large volumes of data.
Key Concepts:
Database:
- A container for collections.
- Example: A library database can contain collections for books, members, and transactions.
Collection:
- A group of MongoDB documents, similar to tables in relational databases.
- Example: A “books” collection can store all book-related documents.
Document:
- A single record in a collection, represented as a JSON-like object.
-
Example:
{ "_id": ObjectId("60adfdf9c25e3c3bfcdf7892"), "title": "Node.js Guide", "author": "John Doe", "year": 2021 }
MongoDB Shell Commands
3) Mongo Shell Commands:
a) To create a new database:
use myLibrary
This switches to the “myLibrary” database. If it doesn’t exist, MongoDB creates it when data is added.
b) To create a new collection for your database:
db.createCollection("books")
Alternatively, insert a document, and the collection will be created automatically:
db.books.insertOne({ title: "Node.js Guide", author: "John Doe" })
c) To find the document in your database:
db.books.find()
This returns all documents in the “books” collection. To find specific records:
db.books.find({ author: "John Doe" })
d) To delete the document from the collection:
db.books.deleteOne({ title: "Node.js Guide" })
To delete multiple documents:
db.books.deleteMany({ author: "John Doe" })
Would you like me to add more examples or dive deeper into any concept? Let me know!
React Components: Functional vs. Class
1) What is React Component? Explain functional and class components with examples.
In React, a component is a reusable, self-contained piece of code that defines how a portion of the user interface (UI) should appear and behave. Components can be nested, managed, and handled independently, allowing for a modular and maintainable code structure. There are two primary types of components in React: functional components and class components.
Functional Components:
Functional components are JavaScript functions that accept props (properties) as arguments and return React elements, which describe what should appear on the screen. They are stateless and do not have lifecycle methods. With the introduction of React Hooks, functional components can now manage state and side effects.
Example of a Functional Component:
import React from 'react';
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default Greeting;
In this example, the Greeting
component is a function that takes props
as an argument and returns an <h1>
element displaying a greeting message.
Class Components:
Class components are ES6 classes that extend from React.Component
. They can hold and manage their own state and have access to lifecycle methods, which allow for more control over the component’s behavior during its lifecycle.
Example of a Class Component:
import React, { Component } from 'react';
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
export default Greeting;
Here, the Greeting
component is a class that extends React.Component
and implements a render
method, which returns an <h1>
element displaying a greeting message.
Key Differences Between Functional and Class Components:
Syntax: Functional components are plain JavaScript functions, whereas class components are ES6 classes that extend from React.Component
.
State Management: Traditionally, class components could manage state using this.state
, while functional components were stateless. However, with the introduction of React Hooks (e.g., useState
), functional components can now manage state as well.
Lifecycle Methods: Class components have access to lifecycle methods (e.g., componentDidMount
, componentDidUpdate
), allowing for more control over the component’s lifecycle. Functional components do not have these methods but can achieve similar behavior using Hooks like useEffect
.
Performance: Functional components are generally easier to read and test, and they can lead to better performance, especially when using Hooks, as they eliminate the need for this
bindings and reduce boilerplate code.
It’s worth noting that as of React 16.8, functional components with Hooks have become the standard for writing React components, and class components are less commonly used in modern React development.
Form Handling in React
2) What is Form Handling in React? Explain Controlled and Uncontrolled Components of forms with examples.
Form handling in React involves managing user input through form elements like <input>
, <textarea>
, and <select>
. React provides two approaches for handling form data: controlled components and uncontrolled components.
Controlled Components:
In controlled components, form data is handled by the component’s state. The value of the form elements is controlled by React, and any changes to the input are managed through event handlers. This approach provides better control over the form data and makes it easier to implement features like validation and conditional rendering.
Example of a Controlled Component:
import React, { useState } from 'react';
function ControlledForm() {
const [name, setName] = useState('');
const handleChange = (event) => {
setName(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Submitted Name: ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name}
onChange={handleChange}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;
In this example, the ControlledForm
component manages the name
state using the useState
Hook. The input’s value
is set to the name
state, and any changes to the input update the state through the handleChange
function. Upon form submission, the handleSubmit
function is called, which prevents the default form submission behavior and displays an alert with the submitted name.
Uncontrolled Components:
Uncontrolled components rely on the DOM to manage form data. Instead of using state to control the form elements, refs are used to access the form values directly from the DOM. This approach is closer to traditional HTML form handling but provides less control over the form data within React.
Example of an Uncontrolled Component:
import React, { useRef } from 'react';
function UncontrolledForm() {
const nameInput = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
alert(`Submitted Name: ${nameInput.current.value}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={nameInput} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default UncontrolledForm;
In this example, the UncontrolledForm
component uses the useRef
Hook to create a reference to the input element. The input’s value is accessed directly from the DOM using nameInput.current.value
when the form is submitted.
Key Differences Between Controlled and Uncontrolled Components:
Data Management: Controlled components manage form data through React state, providing a single source of truth, while uncontrolled components rely on the DOM to handle form data.
Validation: Controlled components make it easier to implement form validation and conditional rendering based on user input
Redux State Immutability
1) Is the State Mutable or Immutable in Redux? Explain in detail with example.
In Redux, the state is immutable, meaning it cannot be changed directly. Instead of modifying the existing state, Redux requires the creation of a new state object to reflect changes. This immutability is fundamental to ensuring predictable state management and enabling features like time-travel debugging.
Why is Immutability Important in Redux?
Predictability: Immutability ensures that state changes are explicit and traceable, making the application’s behavior more predictable.
Change Detection: Immutable state allows for simple and efficient change detection through shallow comparisons, as any modification results in a new object reference.
Debugging and Testing: With immutable state, it’s easier to implement features like undo/redo and time-travel debugging, as previous states remain unchanged and accessible.
Example of Immutability in Redux Reducers:
Consider a Redux reducer managing a list of tasks:
const initialState = {
tasks: [],
};
function taskReducer(state = initialState, action) {
switch (action.type) {
case 'ADD_TASK':
// Return a new state object with the new task added
return {
...state,
tasks: [...state.tasks, action.payload],
};
case 'REMOVE_TASK':
// Return a new state object with the specified task removed
return {
...state,
tasks: state.tasks.filter(task => task.id !== action.payload.id),
};
default:
return state;
}
}
In this example, the taskReducer
handles two action types: ADD_TASK
and REMOVE_TASK
. For each action, a new state object is returned without mutating the existing state:
ADD_TASK
: A new task is added by spreading the existingtasks
array and appending the new task fromaction.payload
.REMOVE_TASK
: A task is removed by filtering out the task with the matchingid
fromaction.payload
.
By adhering to immutability, Redux ensures that state updates are predictable and maintainable.
Redux Thunk Explained
2) What is Redux Thunk? Explain in detail with example.
Redux Thunk is a middleware for Redux that allows action creators to return a function (a “thunk”) instead of an action object. This function can perform asynchronous operations and dispatch actions based on the outcome, enabling complex logic like API calls within Redux’s synchronous action flow.
Key Features of Redux Thunk:
Asynchronous Logic: Allows action creators to handle asynchronous operations, such as fetching data from an API.
Conditional Dispatching: Enables dispatching actions conditionally based on the current state or other logic.
Example of Redux Thunk in Action:
- Install Redux Thunk:
npm install redux-thunk
- Apply Middleware:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
- Create an Asynchronous Action Creator:
import axios from 'axios';
export const fetchData = () => {
return async (dispatch) => {
dispatch({ type: 'FETCH_DATA_REQUEST' });
try {
const response = await axios.get('/api/data');
dispatch({ type: 'FETCH_DATA_SUCCESS', payload: response.data });
} catch (error) {
dispatch({ type: 'FETCH_DATA_FAILURE', payload: error });
}
};
};
In this example, fetchData
is an action creator that returns a function. This function performs an asynchronous API call using axios
and dispatches different actions based on the request’s success or failure.
Redux Application Data Flow
3) Explain Redux Application Data Flow in detail with diagram.
Redux follows a unidirectional data flow, ensuring a predictable state management pattern. The typical data flow in a Redux application involves the following steps:
Action Creation: An action, a plain JavaScript object describing a change, is created.
Dispatching Action: The action is dispatched to the Redux store using the
dispatch
method.Reducer Processing: The store forwards the action to the reducer, a pure function that takes the current state and action as arguments and returns a new state.
State Update: The store updates its state with the new state returned by the reducer.
View Rendering: The view subscribes to the store and re-renders based on the updated state.
Diagram of Redux Data Flow:
+------------+ +-------------+ +----------+ +-----------+
| | | | | | | |
| Action +-------> Dispatch +-------> Reducer +-------> Store |
| | | | | | | |
+------------+ +-------------+ +----------+ +-----------+
|
|
v
+------+
| View |
+------+
Pure Functions Explained
4) Explain Pure Functions with example.
A pure function is a function that, given the same input, always returns the same output and has no side effects (does not alter any external state). Pure functions are deterministic and do not depend on or modify the state outside their scope.
Characteristics of Pure Functions:
Deterministic: Always produces the same output for the same input.
No Side Effects: Does not modify external state or rely on external state changes.
Example of a Pure Function:
function add(a, b) {
return a + b;
}