Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
22 views43 pages

Client-Server Architecture Is A Network Design Model Where Services Are

Question on js for practice
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)
22 views43 pages

Client-Server Architecture Is A Network Design Model Where Services Are

Question on js for practice
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/ 43

Client-Server Architecture

Client-Server Architecture is a network design model where services are


provided by servers and requested by clients. This model divides tasks
between providers (servers) and requesters (clients), leading to efficient
resource utilization and centralized management.

Key Components:

1. Client:
○ Definition: A client is any device or application that requests
services or resources from a server.
○ Examples: Web browsers, mobile apps, desktop applications.
○ Function: The client initiates a request and displays or
processes the data received from the server.
2. Server:
○ Definition: A server is a system or application that provides
services or resources to clients over a network.
○ Examples: Web servers, database servers, file servers.
○ Function: The server listens for requests from clients,
processes these requests, and returns the appropriate
response.

How Requests are Handled at the Server:

1. Request Reception:
○ Listening: Servers listen on specific ports for incoming client
requests. For example, a web server listens on port 80 for
HTTP requests.
○ Connection: Once a request arrives, the server establishes a
connection with the client to handle the communication.
2. Request Processing:
○ Parsing: The server parses the incoming request to understand
what the client needs. This includes examining the request
method (GET, POST, etc.), headers, and body.
○ Handling: Based on the request type, the server performs the
necessary operations. For example:
■ For Web Servers: Retrieve and send back HTML pages,
execute scripts, or handle forms.
■ For Database Servers: Query the database and return
the results.
3. Generating Response:
○ Response Creation: After processing the request, the server
generates a response. This includes:
■ Status Code: Indicates the outcome (e.g., 200 OK, 404
Not Found).
■ Headers: Provide metadata about the response (e.g.,
content type, length).
■ Body: Contains the actual data being sent back to the
client (e.g., HTML content, JSON data).
4. Sending Response:
○ Transmission: The server sends the response back to the
client over the established connection.
○ Closing Connection: Depending on the protocol, the server
may close the connection or keep it open for further requests
(persistent connections).
5. Logging and Monitoring:
○ Logging: Servers often log requests and responses for
monitoring, debugging, and auditing purposes.
○ Monitoring: Tools are used to track server performance,
resource usage, and error rates.

Protocols and Communication:

● HTTP/HTTPS: Used by web servers for transferring web pages.


HTTPS adds a layer of security through encryption.
● FTP: Used for file transfers between clients and servers.
● SMTP/IMAP/POP3: Used for email services.

Types of Servers:
1. Web Servers: Handle HTTP requests and serve web pages.
2. Database Servers: Manage and respond to database queries.
3. File Servers: Store and provide access to files over a network.
4. Application Servers: Provide a platform for running application
services.

Different Types of Client-Server Architecture

1-Tier Architecture

Overview:

● Definition: In a 1-Tier architecture, all components of the


application—presentation, business logic, and data layers—are
combined into a single unit. This typically means that the entire
application runs on a single device or shared storage.
● Characteristics:
○ Single System: The client and server functionalities are
combined into one application.
○ Offline Capability: Often operates offline, with all data storage
and processing occurring locally on the same device.
○ Limited Scalability: Not suitable for scenarios requiring
multiple users or remote data access.

Example:

● Desktop Application: A desktop application like a local database


manager where all data, application logic, and user interface are
stored and executed on the same computer.

2-Tier Architecture

Overview:

● Definition: In a 2-Tier architecture, the system is divided into two


distinct layers: the client and the server. The client handles the
presentation and business logic, while the server manages the data
layer.
● Characteristics:
○ Separation of Data: The data layer is on a separate server,
which manages data storage and retrieval.
○ Client-Server Communication: Clients interact with the server
to access or modify data. The business logic is handled on the
client side.
○ Moderate Scalability: Better suited for scenarios where data
needs to be shared or updated across multiple clients.

Example:

● Login Application: A desktop app where users log in to an online


account. The client application handles the user interface and
authentication logic, while the server stores user credentials and
handles authentication.

3-Tier Architecture

Overview:

● Definition: A 3-Tier architecture separates the application into three


distinct layers: presentation, business logic, and data. Each layer is
hosted on different servers or systems.
● Characteristics:
○ Client: Manages the presentation layer (user interface).
○ Application Server (Middleware): Hosts the business logic
layer, processing requests and managing application logic.
○ Database Server: Manages the data layer, storing and
retrieving data.
○ Middleware: Acts as an intermediary that handles
communication between the client and the database server,
improving security and data integrity.
○ Enhanced Scalability and Security: Each layer can be scaled
independently and offers better security controls.

Example:
● Smartphone App: A mobile app where the client manages the user
interface, the middleware server handles business logic (e.g.,
processing requests), and the data layer is managed by a separate
database server.

N-Tier Architecture

Overview:

● Definition: An N-Tier architecture extends the 3-Tier model by


adding more layers to further separate different aspects of the
application. This allows for more granular control over each layer's
functionality, improving performance, stability, and manageability.
● Characteristics:
○ Multiple Layers: Different layers handle specific functions,
such as application processing, data management, and
presentation.
○ Layered Responsibilities: Each layer can be optimized and
scaled independently, enhancing overall system performance
and flexibility.
○ Complexity: More complex to design and manage but offers
significant benefits for large-scale and enterprise applications.

Example:

● E-Commerce System: An online shopping platform with distinct


layers for handling different functions:
○ Presentation Layer: Manages the user interface and
interaction.
○ Application Processing Layer: Handles business logic related
to order processing, user management, etc.
○ Data Management Layer: Manages database operations,
transactions, and data storage.
○ Integration Layer: Handles integration with third-party services
(e.g., payment gateways, shipping services).
Node.js
Node.js is designed to build scalable network applications. Its key features
include:

● Event-Driven Architecture: Node.js uses an event-driven,


non-blocking I/O model that makes it lightweight and efficient.
● Single-Threaded with Asynchronous I/O: It operates on a
single-threaded event loop, handling multiple connections
asynchronously.
● Built on V8 Engine: Node.js is built on Google Chrome’s V8
JavaScript engine, which compiles JavaScript to native machine code
for high performance.
● npm (Node Package Manager): Node.js comes with npm, a
package manager that provides access to a vast repository of
open-source libraries and modules.

Advantages of Node.js

1. Performance and Scalability:


○ Non-Blocking I/O: Node.js processes multiple I/O operations
concurrently, making it highly efficient for I/O-heavy applications
like web servers.
○ Event Loop: The event-driven architecture enables Node.js to
handle many connections simultaneously without creating
multiple threads, which reduces overhead.
2. Single Language for Frontend and Backend:
○ JavaScript Everywhere: Developers can use JavaScript for
both client-side and server-side development, leading to a more
unified codebase and easier context switching.
3. Large Ecosystem and Community:
○ npm: Node.js’s package manager provides access to a vast
number of libraries and modules, speeding up development and
reducing the need to reinvent the wheel.
○ Active Community: Node.js has a large, active community that
contributes to a wealth of resources, tools, and best practices.
4. Real-Time Capabilities:
○ WebSockets: Node.js is well-suited for real-time applications
such as chat applications and live updates due to its support for
WebSockets and real-time communication.
5. Microservices and Scalability:
○ Microservices Architecture: Node.js works well with
microservices architecture, enabling scalable, distributed
systems.
6. Cross-Platform Development:
○ Cross-Platform: Node.js supports development on multiple
operating systems (Windows, Linux, macOS), and applications
can be easily deployed across different platforms.

Disadvantages of Node.js

1. Single-Threaded Limitations:
○ CPU-Intensive Tasks: Node.js’s single-threaded nature means
it’s not ideal for CPU-intensive tasks like heavy computations or
data processing. Such tasks can block the event loop, affecting
performance.
2. Callback Hell:
○ Nested Callbacks: Complex asynchronous operations can
lead to "callback hell," where nested callbacks become difficult
to manage. This can make the code harder to read and
maintain.
3. Immaturity of Ecosystem:
○ Evolving Libraries: Some npm packages may not be as
mature or stable as libraries in other languages. This can
sometimes lead to issues with package reliability or long-term
maintenance.
4. Learning Curve for New Developers:
○ Asynchronous Programming: The asynchronous nature of
Node.js requires a good understanding of callbacks, promises,
and async/await, which can be challenging for developers
unfamiliar with these concepts.
5. Memory Leaks:
○ Memory Management: Improper handling of resources can
lead to memory leaks. Node.js applications need careful
management of resources to avoid performance degradation
over time.

Comparison with Other Languages

● Python:
○ Pros: Python’s syntax is often praised for readability and
simplicity, making it easier to learn and use for many
developers. It has a rich ecosystem for scientific computing and
data analysis.
○ Cons: Python’s Global Interpreter Lock (GIL) can be a
bottleneck for multi-threaded applications. Python is also
generally slower than Node.js for I/O operations due to its
synchronous nature.
● Java:
○ Pros: Java offers strong performance, scalability, and a mature
ecosystem with extensive libraries and frameworks. It also has
built-in multi-threading support.
○ Cons: Java applications can be more verbose and complex
compared to JavaScript in Node.js. Java applications also have
a higher memory footprint.
● Ruby (Ruby on Rails):
○ Pros: Ruby on Rails is known for its developer-friendly
conventions and rapid application development.
○ Cons: Rails applications can suffer from performance issues
and can be slower than Node.js applications, especially under
high concurrency.
● PHP:
○ Pros: PHP is widely used for web development and has a large
ecosystem. It’s relatively easy to deploy and has strong support
for web-related tasks.
○ Cons: PHP's performance can lag behind Node.js in handling
real-time applications. It also has a less modern language
structure compared to JavaScript.

How to install Node.js


To install Node.js, you have several options depending on your operating
system. Here’s a basic guide for each major platform:

For Windows:

1. Download the Installer:


○ Go to the Node.js download page.
○ Download the Windows Installer (.msi) for the LTS (Long Term
Support) or Current version.
2. Run the Installer:
○ Open the downloaded .msi file and follow the on-screen
instructions.
○ The installer will guide you through the installation process.
3. Verify Installation:

Open Command Prompt or PowerShell and run:


node -v

npm -v

○ This should display the installed versions of Node.js and npm.

For macOS:

1. Using Homebrew (recommended):

If you don’t have Homebrew installed, first install it by running:

/bin/bash -c "$(curl -fsSL


https://raw.githubusercontent.com/Homebrew/install/
HEAD/install.sh)"

Then install Node.js with:

brew install node

2. Using the Installer:


○ Go to the Node.js download page.
○ Download the macOS Installer (.pkg) for the LTS or Current
version.
○ Open the downloaded .pkg file and follow the on-screen
instructions.
3. Verify Installation:

Open Terminal and run:


node -v

npm -v

○ This should display the installed versions of Node.js and npm

For Linux:

1. Using NodeSource Binaries:

Open your terminal and install Node.js via the NodeSource repository. For
example, for the LTS version:
curl -fsSL https://deb.nodesource.com/setup_lts.x |
sudo -E bash -

sudo apt-get install -y nodejs

○ For other distributions or versions, check the NodeSource


documentation.
2. Using Package Manager:
For Ubuntu/Debian-based systems:

sudo apt update

sudo apt install -y nodejs npm

For Red Hat-based systems:


sudo yum install -y nodejs


3. Verify Installation:

Run the following commands to check the installed versions:


node -v

npm -v

○ This should display the installed versions of Node.js and npm

An Example Node.js Application

The most common example Hello World of Node.js is a web server:

const { createServer } = require('node:http');

const hostname = '127.0.0.1';

const port = 3000;

const server = createServer((req, res) => {

res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');

res.end('Hello World');

});

server.listen(port, hostname, () => {

console.log(`Server running at
http://${hostname}:${port}/`);

});

To run this snippet, save it as a server.js file and run node server.js in your
terminal.

This code first includes the Node.js http module.Node.js has a fantastic
standard library, including first-class support for networking.

The createServer() method of http creates a new HTTP server and returns
it. The server is set to listen on the specified port and host name. When the
server is ready, the callback function is called, in this case informing us that
the server is running.

Whenever a new request is received, the request event is called, providing


two objects: a request (an http.IncomingMessage object) and a response
(an http.ServerResponse object).
Those 2 objects are essential to handle the HTTP call. The first provides
the request details. In this simple example, this is not used, but you could
access the request headers and request data. The second is used to return
data to the caller.

In this case with:

res.statusCode = 200;

we set the statusCode property to 200, to indicate a successful response.

We set the Content-Type header:

res.setHeader('Content-Type', 'text/plain');

and we close the response, adding the content as an argument to end():

res.end('Hello World\n');

npm (Node Package Manager)


npm is the package manager for Node.js. It is used to manage
packages (libraries or modules) that your Node.js application
depends on. npm helps you install, update, and manage these
packages, making it easier to work with third-party libraries and tools.

Key Features of npm:

1. Package Management:
○ Install packages from the npm registry: npm install
package-name.
2. Scripts: npm allows you to define scripts in your package.json
file to automate tasks like starting the server, running tests, or
building the project.
○ Example: "start": "node index.js" runs index.js
when you run npm start.
3. Versioning:
○ Manage versions of packages using semantic versioning.
This helps ensure compatibility and stability.
○ Example: "express": "^4.17.1" specifies a compatible
version of Express.
4. Global vs. Local Packages:
○ Local Packages: Installed in the node_modules directory
of your project and listed in package.json.
■ Example: npm install express installs Express
locally.
○ Global Packages: Installed system-wide and accessible
from any project.
■ Example: npm install -g nodemon installs
nodemon globally.
5. Configuration:
○ package.json file stores metadata about your project,
including dependencies, scripts, and other configurations.

Express.js
Express.js is a web application framework for Node.js that simplifies
the process of building server-side applications and APIs. It provides
a set of robust features to handle HTTP requests, route requests, and
manage middleware.

Key Features of Express.js:

1. Middleware: Middleware functions are functions that have


access to the request (req), response (res), and the next
middleware function in the application's request-response cycle.
They can modify the request and response objects, end the
request-response cycle, and call the next middleware in the
stack.
○ Example: app.use(express.json()) to parse JSON
bodies in requests.
2. Routing: Express allows you to define routes to handle different
HTTP methods (GET, POST, PUT, DELETE). Each route can be
associated with a specific path and HTTP method.
○ Example: app.get('/path', handlerFunction)
defines a route for GET requests.
3. Request Handling: Express simplifies handling different HTTP
requests and responses. You can define how to handle incoming
requests, including sending responses back to the client.
○ Example: res.status(200).json(data) sends a JSON
response with a status code.
4. Static File Serving: Express can serve static files (like HTML,
CSS, JavaScript) from a directory.
○ Example: app.use(express.static('public')) serves
files from the public directory.
5. Error Handling: Express provides a simple way to handle errors
and respond with appropriate messages and status codes.

Case Study: "Book Bazaar" Inventory Management System


Background:

"Book Bazaar" is a small, independent bookstore located in a bustling city


center. The store offers a wide variety of books, from bestsellers to rare
editions. To keep track of their inventory, the bookstore currently uses a
manual system involving spreadsheets, which is time-consuming and prone
to errors. To streamline their operations and improve inventory
management, the bookstore decides to develop a simple digital inventory
management system.

Objective:

Develop a backend system for "Book Bazaar" using Node.js and


Express.js. The system should allow bookstore staff to manage their
inventory efficiently by supporting CRUD operations. The data will be
stored in the file system to facilitate quick development and testing. The
system should provide a RESTful API to interact with the book inventory.

Requirements:

1. Create a New Book:


○ Endpoint: POST /books
○ Description: Adds a new book to the inventory. Each book
should have a unique id, a title, an author, and a price.

Request Body:

{
"title": "string",
"author": "string",
"price": "number"
}

○ Response:

Success (201 Created):

{
"id": "integer",
"title": "string",
"author": "string",
"price": "number"
}

Error (400 Bad Request): If any required field is missing or invalid.

{
"error": "All fields are required and price must be a
positive number"
}


2. Read All Books:
○ Endpoint: GET /books
○ Description: Retrieves a list of all books currently in the
inventory.
○ Response:

Success (200 OK):

[
{
"id": "integer",
"title": "string",
"author": "string",
"price": "number"
},
...
]

3. Read a Specific Book:
○ Endpoint: GET /books/:id
○ Description: Retrieves details of a single book by its unique
id.
○ Parameters:
■ id (path parameter): The unique identifier of the book.
○ Response:

Success (200 OK):

{
"id": "integer",
"title": "string",
"author": "string",
"price": "number"
}

Error (404 Not Found): If the book with the specified id does not exist.

{
"error": "Book not found"
}


4. Update Book Information:
○ Endpoint: PUT /books/:id
○ Description: Updates the details of an existing book identified
by its id.
○ Parameters:
■ id (path parameter): The unique identifier of the book to
be updated.

Request Body:

{
"title": "string",
"author": "string",
"price": "number"
}


○ Response:

Success (200 OK):

{
"id": "integer",
"title": "string",
"author": "string",
"price": "number"
}

Error (400 Bad Request): If any required field is missing or invalid.

{
"error": "All fields are required and price must be a
positive number"
}

Error (404 Not Found): If the book with the specified id does not exist.

{
"error": "Book not found"
}


5. Delete a Book:
○ Endpoint: DELETE /books/:id
○ Description: Removes a book from the inventory by its id.
○ Parameters:
■ id (path parameter): The unique identifier of the book to
be deleted.
○ Response:
■ Success (204 No Content): Indicates that the book was
successfully deleted.

Error (404 Not Found): If the book with the specified id does not exist.

{
"error": "Book not found"
}

Constraints:

● The system will use an in-memory array to store book data. This
means that data will not persist across server restarts.
● Input validation is required to ensure that all fields are provided and
that the price is a positive number.
● Error handling should provide clear and informative messages for
invalid operations (e.g., missing fields, non-existent books).

Project Setup

Setting up the backend for a Node.js-based application involves


several steps. Here's a comprehensive guide to get your backend up
and running:

1. Initialize Your Node.js Project

● First, create a new directory for your project and initialize it with
Node.js :

npm init -y # Initializes a new Node.js project

● This will create a package.json file in your directory, which will


manage your project's dependencies and settings.

2. Install Dependencies

● Install necessary Node.js packages using npm (Node Package


Manager).

npm i express nodemon

● express is the framework you’ll use to build your web server


and handle routing.
● nodemon is a utility that monitors for changes in your source
code and automatically restarts the server. It's useful for
development.

3. Create Server Entry File


● Create an index.js file in the root of your project. This will be
your main server file.

Note : Adding a Start Script in package.json

To streamline the process of starting your Node.js application, it's


recommended to add a start script in your project's package.json file.
This allows you to start your server easily using the npm start
command.

Modifying package.json: Open your package.json file and add the


following line under the scripts section:

"scripts": {
"start": "nodemon server.js"
}

Example :
This script tells npm to start your application using Node.js and run
the index.js file.

Using npm start: Once you've added the start script, you can start
your server by running the following command in your terminal:

npm start

This is a convenient and standardized way to start Node.js


applications and is particularly useful in production environments.
Solution :

index.js (Main Server File)

const express = require('express');


const app = express();
const port = 3001
app.use(express.json())
const {readBooksFile,writeBooksFile} =
require('./bookstore')

//Create a New Book


app.post("/books",(req,res)=>{
const{title, author ,price} = req.body;
if(!title || !author || typeof price != 'number' ||
price<0){
res.status(400).json({
error : "All fields are required and price
must be a positive number"
})
}else{
const books = readBooksFile()
let book_id = books.length + 1;
const newBook = {
id : book_id,
title : title,
author : author,
price : price
}
books.push(newBook)
writeBooksFile(books)
res.status(201).json(newBook)
}
})

//Read All Books


app.get("/books", (req,res)=>{
res.status(200).json(readBooksFile())
})

// Read a Specific Book


app.get("/books/:id", (req,res)=>{
const books = readBooksFile()
const id = req.params.id;
for(let i = 0; i<books.length; i++){
if(books[i].id==id){
res.status(200).json(books[i]);
return;
}
}
res.status(400).json({
error : "Book not found"
})
})

// Update Book Information


app.put("/books/:id", (req,res)=>{
const{title, author ,price} = req.body;
if(!title || !author || typeof price != 'number' ||
price<0){
res.status(400).json({
error : "All fields are required and price
must be a positive number" })
}else{
const books = readBooksFile()
const id = req.params.id
for(let i = 0; i<books.length; i++){
if(books[i].id==id){
books[i].title = title;
books[i].author = author;
books[i].price = price;
writeBooksFile(books)
res.status(200).json(books[i]);
return;
}}
res.status(404).json({
error : "Book not found"
})}})
//Delete a Book
app.delete("/books/:id", (req,res)=>{
const id = req.params.id;
const books = readBooksFile()
for(let i = 0; i<books.length; i++){
if(books[i].id==id){
books.splice(i,1)
writeBooksFile(books)
res.status(204).json();
return;
}
}
res.status(404).json({
error : "Book not found"
})
})
app.listen(port,()=>{
console.log("Server Running..")
})

bookstore.js (Data Management Module)

const fs = require('fs')
const BOOKS_FILE = "./books.json"

const readBooksFile = ()=>{


if(!fs.existsSync(BOOKS_FILE)){
fs.writeFileSync(BOOKS_FILE,JSON.stringify([]))
}
return
JSON.parse(fs.readFileSync(BOOKS_FILE,'utf-8'))
}

const writeBooksFile = (books)=>{

fs.writeFileSync(BOOKS_FILE,JSON.stringify(books,null,2
))
}

module.exports = {readBooksFile,writeBooksFile}

books.json (This file will be used to store book data in JSON format)

[]
Explanation :

Handling Requests and Creating Endpoints

In this example, the Express.js application defines several endpoints for


managing the book inventory:

● POST /books - Adds a new book to the inventory.


● GET /books - Retrieves a list of all books.
● GET /books/
- Retrieves a specific book by its unique ID.
● PUT /books/
- Updates the details of a book identified by its ID.
● DELETE /books/
- Deletes a book identified by its ID.

Here’s how Express handles these:

● Request Handling: Each route handler receives a request (req) and


response (res) object. You use these objects to interact with the
client. For example, req.body contains data sent by the client in a
POST or PUT request, and res.status() sets the HTTP status
code of the response.

3. Modules and npm

● Modules: In Node.js, modules are JavaScript files or packages that


you can use to encapsulate code. For example, express and fs (file
system) are modules used in your application. The fs module is used
to handle file operations, while express provides web server
capabilities.
● npm (Node Package Manager): Manages the packages (libraries or
modules) that your project depends on. In your package.json, you
specify dependencies (like express and nodemon), and npm
handles installing these packages.
4. Importing Modules

In Node.js, you use the require function to import modules. For example:

const express = require('express');


const fs = require('fs');

● express is imported to create the web server.


● fs is used for file system operations (e.g., reading and writing files).

5. index.js (Main Server File)

This file contains the core logic for your Express server.

Here’s a summary of the code:

Dependencies and Setup:

const express = require('express');


const app = express();
const port = 3001;
app.use(express.json());
const { readBooksFile, writeBooksFile } =
require('./bookstore');

○ Import express and initialize the app.


○ Use express.json() middleware to parse JSON request
bodies.
○ Import functions for file operations.

Create a New Book:

app.post("/books", (req, res) => {


const { title, author, price } = req.body;
if (!title || !author || typeof price != 'number'
|| price < 0) {
res.status(400).json({ error: "All fields are
required and price must be a positive number" });
} else {
const books = readBooksFile();
let book_id = books.length + 1;
const newBook = { id: book_id, title, author,
price };
books.push(newBook);
writeBooksFile(books);
res.status(201).json(newBook);
}
});

○ Validates the request body and adds a new book to the


in-memory data store.

Read All Books:

app.get("/books", (req, res) => {


res.status(200).json(readBooksFile());
});

○ Retrieves and returns all books.

Read a Specific Book:

app.get("/books/:id", (req, res) => {


const books = readBooksFile();
const id = parseInt(req.params.id, 10);
const book = books.find(b => b.id === id);
if (book) {
res.status(200).json(book);
} else {
res.status(404).json({ error: "Book not found"
});
}
});

○ Searches for a book by ID and returns it if found.

Update Book Information:


app.put("/books/:id", (req, res) => {
const { title, author, price } = req.body;
if (!title || !author || typeof price != 'number'
|| price < 0) {
res.status(400).json({ error: "All fields are
required and price must be a positive number" });
} else {
const books = readBooksFile();
const id = parseInt(req.params.id, 10);
const index = books.findIndex(b => b.id ===
id);
if (index !== -1) {
books[index] = { id, title, author, price
};
writeBooksFile(books);
res.status(200).json(books[index]);
} else {
res.status(404).json({ error: "Book not
found" });
}
}
});

○ Updates the details of an existing book.

Delete a Book:
app.delete("/books/:id", (req, res) => {
const id = parseInt(req.params.id, 10);
let books = readBooksFile();
const index = books.findIndex(b => b.id === id);
if (index !== -1) {
books.splice(index, 1);
writeBooksFile(books);
res.status(204).end();
} else {
res.status(404).json({ error: "Book not found"
});
}
});

○ Deletes a book from the inventory.

Start the Server:


app.listen(port, () => {
console.log("Server Running..");
});

○ Starts the server and listens on port 3001.

6. bookstore.js (Data Management Module)

This module handles file operations for storing and retrieving book data.
Read Books File:
const fs = require('fs');
const BOOKS_FILE = "./books.json";

const readBooksFile = () => {


if (!fs.existsSync(BOOKS_FILE)) {
fs.writeFileSync(BOOKS_FILE,
JSON.stringify([]));
}
return JSON.parse(fs.readFileSync(BOOKS_FILE,
'utf-8'));
};

○ Checks if the file exists. If not, creates it with an empty array.


Reads and returns the book data.

Write Books File:


const writeBooksFile = (books) => {
fs.writeFileSync(BOOKS_FILE, JSON.stringify(books,
null, 2));
};

○ Writes the updated book data to the file.

Export Functions:

module.exports = { readBooksFile, writeBooksFile };

○ Exports the functions for use in index.js.

7. books.json

Initially an empty array:

[]
● This file will be used to store book data in JSON format.

Summary

1. Project Initialization: Use npm init -y to create package.json.


2. Install Dependencies: Use npm i express nodemon.
3. Create and Configure Server File: Create index.js, define routes,
and add a start script in package.json.
4. File Operations: Use fs in bookstore.js for file handling.
5. Run the Server: Start the server using npm start

Practice Questions :
Client-Server Architecture

1. What is the primary role of a client in a client-server


architecture?
○ A) To store data
○ B) To request services or resources
○ C) To manage network traffic
○ D) To provide network security
○ Answer: B) To request services or resources
2. Which of the following is NOT a characteristic of the server in a
client-server model?
○ A) Provides services
○ B) Waits for client requests
○ C) Executes client requests
○ D) Initiates connections to clients
○ Answer: D) Initiates connections to clients
3. In the client-server model, which component typically initiates a
connection?
○ A) Server
○ B) Client
○ C) Middleware
○ D) Database
○ Answer: B) Client
4. What is the main advantage of a client-server architecture?
○ A) Reduced security
○ B) Centralized management
○ C) Increased network congestion
○ D) Higher cost
○ Answer: B) Centralized management
5. Which protocol is commonly used for web communication
between client and server?
○ A) FTP
○ B) HTTP
○ C) SMTP
○ D) SNMP
○ Answer: B) HTTP

Understanding Server and Request Handling

6. What is a server's primary function?


○ A) To handle user input
○ B) To process requests and provide responses
○ C) To manage local files
○ D) To create user interfaces
○ Answer: B) To process requests and provide responses
7. In web servers, what does HTTP stand for?
○ A) Hypertext Transfer Protocol
○ B) Hyperlink Transfer Protocol
○ C) High Transfer Text Protocol
○ D) Hypertext Transport Protocol
○ Answer: A) Hypertext Transfer Protocol
8. Which HTTP method is used to retrieve data from a server?
○ A) POST
○ B) PUT
○ C) GET
○ D) DELETE
○ Answer: C) GET
9. Which HTTP status code indicates that the request was
successful?
○ A) 404
○ B) 500
○ C) 200
○ D) 302
○ Answer: C) 200
10. What does the server return in response to a client's request?
○ A) Data
○ B) Error message
○ C) Confirmation of receipt
○ D) None of the above
○ Answer: A) Data

Understanding Node.js

11. What is Node.js primarily used for?


○ A) Building desktop applications
○ B) Creating interactive web pages
○ C) Developing server-side applications
○ D) Designing graphics
○ Answer: C) Developing server-side applications
12. Which programming language is Node.js built on?
○ A) Java
○ B) Python
○ C) JavaScript
○ D) Ruby
○ Answer: C) JavaScript
13. Which runtime environment does Node.js use?
○ A) JVM
○ B) .NET Framework
○ C) V8 JavaScript Engine
○ D) Python Interpreter
○ Answer: C) V8 JavaScript Engine
14. What is the primary advantage of Node.js's non-blocking I/O
model?
○ A) Improved graphics rendering
○ B) Increased parallel processing
○ C) Faster handling of concurrent requests
○ D) Reduced memory usage
○ Answer: C) Faster handling of concurrent requests
15. Which of the following is a core module in Node.js?
○ A) React
○ B) Express
○ C) fs
○ D) Angular
○ Answer: C) fs

Advantages and Disadvantages of Node.js

16. Which of the following is an advantage of Node.js?


○ A) Multi-threaded processing
○ B) High concurrency support
○ C) Limited package availability
○ D) Slower execution speed
○ Answer: B) High concurrency support
17. What is a disadvantage of Node.js?
○ A) Single-threaded nature
○ B) Lack of community support
○ C) Limited framework support
○ D) Poor performance in I/O operations
○ Answer: A) Single-threaded nature
18. How does Node.js handle multiple requests simultaneously?
○ A) Using threads
○ B) Using an event-driven, non-blocking I/O model
○ C) By blocking each request until the previous one is processed
○ D) By using synchronous I/O operations
○ Answer: B) Using an event-driven, non-blocking I/O model
19. Which feature of Node.js allows it to handle a large number of
connections with low overhead?
○ A) Thread pooling
○ B) Event-driven architecture
○ C) Multiple processes
○ D) Synchronous execution
○ Answer: B) Event-driven architecture
20. What can be a challenge when using Node.js for
CPU-intensive tasks?
○ A) High concurrency
○ B) Single-threaded execution
○ C) Event loop management
○ D) Non-blocking I/O
○ Answer: B) Single-threaded execution

Installing Node.js and Creating a Server

21. Which command is used to install Node.js on a system?


○ A) node install
○ B) npm install node
○ C) sudo apt-get install nodejs
○ D) nodejs setup
○ Answer: C) sudo apt-get install nodejs
22. Which file is typically used to configure the Node.js
application?
○ A) node.config
○ B) app.config
○ C) index.js
○ D) package.json
○ Answer: D) package.json
23. Which command initializes a new Node.js project?
○ A) npm init
○ B) node init
○ C) npm start
○ D) node start
○ Answer: A) npm init
24. To start a Node.js server, which module is commonly used?
○ A) http
○ B) express
○ C) socket.io
○ D) fs
○ Answer: A) http
25. Which method is used to create a basic HTTP server in
Node.js?
○ A) http.createServer()
○ B) http.startServer()
○ C) server.listen()
○ D) server.create()
○ Answer: A) http.createServer()

Handling Requests and Creating Endpoints

26. How does Node.js handle HTTP requests?


○ A) By using synchronous operations
○ B) By using the http module’s createServer method
○ C) By blocking I/O operations
○ D) By creating multiple threads
○ Answer: B) By using the http module’s createServer
method
27. Which HTTP method is used to submit data to the server?
○ A) GET
○ B) POST
○ C) PUT
○ D) DELETE
○ Answer: B) POST
28. How can you define a new route in Express?
○ A) app.use('/path', handler)
○ B) app.route('/path', handler)
○ C) app.get('/path', handler)
○ D) app.define('/path', handler)
○ Answer: C) app.get('/path', handler)
29. Which method is used in Express to handle POST requests?
○ A) app.get()
○ B) app.post()
○ C) app.put()
○ D) app.delete()
○ Answer: B) app.post()
30. What does the req.body property contain in an Express
request?
○ A) URL parameters
○ B) Query string parameters
○ C) Request payload
○ D) HTTP headers
○ Answer: C) Request payload

Modules and npm

31. What is the purpose of npm in a Node.js project?


○ A) To compile code
○ B) To manage project dependencies
○ C) To serve static files
○ D) To handle HTTP requests
○ Answer: B) To manage project dependencies
32. Which command is used to install a package locally in a
Node.js project?
○ A) npm install -g package-name
○ B) npm install package-name
○ C) npm add package-name
○ D) npm get package-name
○ Answer: B) npm install package-name
33. Which file specifies the dependencies of a Node.js project?
○ A) dependencies.json
○ B) module.json
○ C) package.json
○ D) node_modules.json
○ Answer: C) package.json
34. What does require() do in Node.js?
○ A) Imports a module
○ B) Reads a file
○ C) Creates a new module
○ D) Starts the server
○ Answer: A) Imports a module
35. How do you export a function from a module in Node.js?
○ A) module.export = function() {}
○ B) exports.function = function() {}
○ C) module.exports = function() {}
○ D) export function() {}
○ Answer: C) module.exports = function() {}

Handling Static Pages and File Stream

36. Which module is used to handle file operations in Node.js?


○ A) http
○ B) path
○ C) fs
○ D) url
○ Answer: C) fs
37. Which method of the fs module reads a file synchronously?
○ A) fs.readFile()
○ B) fs.readFileSync()
○ C) fs.open()
○ D) fs.read()
○ Answer: B) fs.readFileSync()
38. How can you serve static files using Express?
○ A) app.use(express.static('public'))
○ B) app.serveStatic('public')
○ C) app.static('public')
○ D) app.use(express.serve('public'))
○ Answer: A) app.use(express.static('public'))
39. Which method of the fs module writes data to a file?
○ A) fs.writeFileSync()
○ B) fs.createFile()
○ C) fs.appendFile()
○ D) fs.saveFile()
○ Answer: A) fs.writeFileSync()
40. How do you handle exceptions in Node.js?
○ A) Using try-catch blocks
○ B) Using error events
○ C) Using process.on('uncaughtException')
○ D) All of the above
○ Answer: D) All of the above

You might also like