0% found this document useful (0 votes)
10 views

wt-unit4

agjykr

Uploaded by

g731046
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)
10 views

wt-unit4

agjykr

Uploaded by

g731046
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/ 25

Web Technology (BCS502)

Unit 4 2024-25
B.TECH (CSIT) SEMESTER -V
1: Enterprise Java Bean

2. Creating a JavaBeans

3. JavaBeans Properties, Types of beans, Stateful Session bean, Stateless Session bean, Entity
bean.

4. Node JS introduction and application.

5. Environment Setup

6. REPL Terminal

Faculty
Dr. Aadarsh Malviya
(Associate Professor Department of CSE)

Dronacharya Group of Institutions


Plot No. 27, Knowledge Park-3, Greater Noida, Uttar Pradesh 201308

Affiliated to

Dr. A P J Abdul Kalam Technical University


Lucknow, Uttar Pradesh 226031
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

1. Enterprise Java Bean


Enterprise JavaBeans (EJB) is a server-side component architecture for Java EE (now Jakarta EE) that
simplifies the development of large-scale, distributed, and transactional enterprise applications. EJB provides a
robust framework for building scalable, secure, and transactional business logic in enterprise-level applications.
Key Features of EJB:
1. Component-Based: EJB allows developers to build applications by assembling reusable components.
2. Transaction Management: EJB provides automatic transaction handling, ensuring that business logic
adheres to the "ACID" properties of transactions.
3. Security: EJB allows for declarative security, making it easy to manage roles and permissions.
4. Scalability: EJB components are designed to handle large numbers of concurrent clients, scaling
horizontally across servers.
5. Distributed Computing: EJB supports remote method invocation (RMI), enabling distributed systems.
6. Persistence: Through Container-Managed Persistence (CMP) and Bean-Managed Persistence (BMP),
EJB facilitates object-relational mapping (ORM) for database operations.
7. Lifecycle Management: The EJB container manages the lifecycle of beans, including their creation,
destruction, pooling, and activation.
Types of EJB:
1. Session Beans:
o Handle business logic and operations.
o Types:
 Stateless Session Beans: Do not maintain client state between calls.
 Stateful Session Beans: Maintain conversational state across multiple method calls.
 Singleton Session Beans: A single shared instance of the bean for all clients.
2. Message-Driven Beans (MDBs):
o Handle asynchronous messaging.
o Typically used with Java Message Service (JMS) to process messages asynchronously.
3. Entity Beans (deprecated in later versions, replaced by JPA):
o Represent persistent data stored in a database.
EJB Lifecycle:
 The EJB container controls the lifecycle of beans, which includes:
o Creation: Beans are created either upon client request or at server startup.
o Pooling: Beans can be pooled to manage resources efficiently.
o Passivation/Activation: Stateful session beans can be passivated (saved to disk) when not in use
and reactivated when needed.
o Destruction: Beans are destroyed when they are no longer needed.
EJB Architecture:
 Client: Communicates with EJB components, which reside on an application server.
 EJB Container: Provides services like transaction management, security, and lifecycle management.
 Database: Backend systems where data persists.
Advantages of EJB:
 Simplified development for distributed applications.
 Built-in support for transactions, security, and scalability.
 Reduces boilerplate code, allowing developers to focus on business logic.
EJB has been somewhat overshadowed by modern frameworks like Spring, but it remains a crucial part of legacy
enterprise Java systems.

2. Creating a JavaBeans
Creating a JavaBean is different from working with Enterprise JavaBeans (EJB). While EJB is for server-side
enterprise-level applications, JavaBeans are simple reusable software components that can be manipulated
visually in development tools. They are primarily used for encapsulating data in Java desktop applications but can
also be used in other Java environments.

1
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

Key Properties of a JavaBean:


1. Encapsulation: The properties of the JavaBean are private and accessed via getter and setter methods.
2. No-Argument Constructor: A JavaBean must have a public no-argument constructor.
3. Serializable: JavaBeans must implement java.io.Serializable to support persistence, enabling them to be
saved and restored.
Steps to Create a JavaBean:
1. Define a JavaBean Class:
A JavaBean class encapsulates data by making fields private and providing public getter and setter methods.

import java.io.Serializable;

public class Person implements Serializable {


// Private properties
private String name;
private int age;

// Public no-argument constructor


public Person() {
// Default constructor
}

// Getter for name property


public String getName() {
return name;
}

// Setter for name property


public void setName(String name) {
this.name = name;
}

// Getter for age property


public int getAge() {
return age;
}

// Setter for age property


public void setAge(int age) {
this.age = age;
}

// Additional methods can be added if needed


}

2. Explanation of the JavaBean:


 Serializable: The Person class implements the Serializable interface, allowing the object to be persisted
(e.g., saved to disk or transferred over a network).
 Private Fields: name and age are private fields, meaning they cannot be accessed directly from outside the
class.
 Getters and Setters: Public getName(), setName(), getAge(), and setAge() methods allow controlled
access to the private properties.

2
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]


No-Argument Constructor: A default constructor (Person()) is provided to allow easy instantiation of the
bean without specifying any initial values.
3. Using the JavaBean:
You can create and use an instance of the JavaBean in a Java application like this:

public class Main {


public static void main(String[] args) {
// Creating an instance of the Person JavaBean
Person person = new Person();

// Using the setter methods to set values


person.setName("John Doe");
person.setAge(30);

// Using the getter methods to retrieve values


System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}

Key Principles of JavaBeans:


 Introspection: JavaBeans can be introspected at runtime, allowing tools like IDEs or UI builders to
automatically discover properties and methods.
 Event Handling: JavaBeans support event listeners to handle user actions like button clicks or other UI
events.
 Customizable: JavaBeans can be customized visually in design tools if used in a graphical interface
context.
While JavaBeans are typically used for user interfaces and desktop applications, their simple, reusable nature
makes them useful in other contexts as well.

3. JavaBeans Properties, Types of beans, Stateful Session bean, Stateless Session bean, Entity bean.
JavaBeans Properties
In JavaBeans, properties represent the data that can be accessed and modified through getter and setter methods.
Properties follow a naming convention where the method names reflect the property name and are used for
encapsulation.
Types of Properties:
1. Simple Property:
o Holds a single value, such as a String or int.
o Example:

private String name;


public String getName() { return name; }
public void setName(String name) { this.name = name; }

Indexed Property:
 Holds an array of values, and the setter/getter methods allow for specific indices to be accessed or
modified.
 Example

private String[] addresses;

3
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

public String getAddress(int index) { return addresses[index]; }


public void setAddress(int index, String address) { this.addresses[index] = address; }

Bound Property:
 When a property changes, the bean notifies listeners about the change.
 Uses PropertyChangeListener to observe changes.
 Example

private PropertyChangeSupport support = new PropertyChangeSupport(this);


private String name;

public void setName(String newName) {


String oldName = this.name;
this.name = newName;
support.firePropertyChange("name", oldName, newName);
}

Constrained Property:
 A property that can veto changes if they are deemed invalid.
 Listeners can throw a PropertyVetoException if a change is unacceptable.

private VetoableChangeSupport vetoSupport = new VetoableChangeSupport(this);

public void setAge(int age) throws PropertyVetoException {


int oldAge = this.age;
vetoSupport.fireVetoableChange("age", oldAge, age);
this.age = age;
}

Types of Beans
1. JavaBeans:
 Standard reusable components in desktop applications.
 They encapsulate many objects into a single object (bean), accessible via properties, events, and methods.
 Example: A Person bean to manage the name and age of a person.
2. Enterprise JavaBeans (EJB):
 Components in the enterprise environment for building scalable, transactional, and distributed
applications.
 EJBs are primarily used in server-side applications.
 Types of EJB:
1. Stateful Session Bean
2. Stateless Session Bean
3. Entity Bean (deprecated, now replaced by Java Persistence API - JPA)
4. Message-Driven Beans (used for handling asynchronous messaging)

Stateful Session Bean (EJB)


 Purpose: A Stateful Session Bean maintains conversational state across multiple method calls and
transactions. It is used when the client and bean interaction requires state retention between invocations.
 State: Each client interacting with the stateful bean has a unique instance, and the bean maintains the state
on behalf of the client during the session.
Example Use Cases:
 Online shopping cart applications.

4
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

 Banking transaction sessions where each client’s data needs to be maintained during the session.
Lifecycle of a Stateful Session Bean:
1. Creation: A new bean instance is created when the client requests the first method call.
2. Passivation: If not in use, the bean may be passivated (i.e., its state is saved to disk).
3. Activation: If the client calls a method again, the bean is activated.
4. Destruction: When the session ends or times out, the bean is destroyed.
Code Example:

import javax.ejb.Stateful;

@Stateful
public class ShoppingCartBean {
private List<String> cartItems = new ArrayList<>();

public void addItem(String item) {


cartItems.add(item);
}

public List<String> getItems() {


return cartItems;
}

public void checkout() {


// Process checkout logic
}
}

Stateless Session Bean (EJB)


 Purpose: A Stateless Session Bean does not maintain any state between client method calls. Each method
call is independent of any previous call, and the same instance of the bean may be reused for different
clients.
 State: Since stateless beans do not retain state, they are typically used for lightweight operations like
business logic or processing that does not require keeping any client-specific data.
Example Use Cases:
 Stateless services such as calculating tax, sending emails, or processing payments.
 Stateless web services.
Lifecycle of a Stateless Session Bean:
1. Creation: The bean instance is created by the container at server startup.
2. Pooling: The container maintains a pool of stateless beans, and any bean from the pool can handle client
requests.
3. Destruction: Beans are destroyed by the container if they are no longer needed.
Code Example:

import javax.ejb.Stateless;

@Stateless
public class CalculatorBean {

public int add(int a, int b) {


return a + b;
}

5
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

public int subtract(int a, int b) {


return a - b;
}
}

Entity Bean (EJB)


 Purpose: An Entity Bean represents persistent data in a database. Unlike session beans, entity beans have
a one-to-one mapping with database records, making them ideal for database access and manipulation.
 State: Entity beans are used for data persistence and are identified by a primary key.
Entity Beans were part of the original EJB specification but have since been replaced by the Java Persistence
API (JPA). JPA is more powerful and flexible for working with database entities.
Example Use Cases:
 Managing customer information in a database.
 Handling orders in an e-commerce application.
Lifecycle of an Entity Bean:
1. Creation: An entity bean is created when a new record is added to the database.
2. Activation: The bean's state is synchronized with the database.
3. Passivation: The bean's state is saved to the database if not needed.
4. Removal: The entity bean is removed when the record is deleted from the database.
Entity beans were complex and often criticized for their cumbersome use, leading to their replacement by JPA.
Modern Replacement - JPA Example:

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Customer {

@Id
private Long id;
private String name;

// Getters and Setters


public Long getId() { return id; }
public void setId(Long id) { this.id = id; }

public String getName() { return name; }


public void setName(String name) { this.name = name; }
}

Summary:
 JavaBeans: Reusable components for encapsulating data in Java applications.
 Stateful Session Beans: Maintain state across multiple method calls in server-side applications.
 Stateless Session Beans: Do not retain state between method calls and are used for stateless business
logic.
 Entity Beans: Represent persistent data in databases (replaced by JPA in modern applications).
Each bean type serves a different purpose depending on whether state needs to be maintained and the scope of the
application logic.

Introduction to Node.js

6
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

Introduction to Node.js
Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside
of a browser. It is built on the V8 JavaScript engine developed by Google and is designed for building scalable
network applications. Node.js uses an event-driven, non-blocking I/O model, which makes it highly efficient and
suitable for real-time applications.
Key Features of Node.js:
1. Asynchronous and Event-Driven:
o All APIs of Node.js are asynchronous (non-blocking), which means it can handle multiple
operations concurrently without waiting for one operation to complete before starting another.
o Event-driven architecture allows Node.js to manage multiple requests simultaneously using events
and callbacks.
2. Single-Threaded but Scalable:
o Although Node.js operates in a single thread, it is designed for scalability. It uses the event loop to
handle requests asynchronously and delegates heavy I/O operations (like database access, file
reading) to worker threads, allowing it to handle thousands of requests without blocking.
3. Non-Blocking I/O:
o Node.js uses a non-blocking I/O model, meaning it can initiate an I/O operation and continue
executing other code while waiting for the result of the I/O operation, improving performance.
4. Cross-Platform:
o Node.js can be run on various operating systems like Windows, macOS, and Linux, making it
versatile and widely adopted in development environments.
5. NPM (Node Package Manager):
o NPM is the default package manager for Node.js. It provides a vast ecosystem of libraries and
modules that developers can install and use in their applications, significantly speeding up
development.
6. JavaScript Everywhere:
o With Node.js, developers can write both client-side and server-side code in JavaScript, making
full-stack JavaScript development possible and more consistent.
Node.js Architecture
Node.js uses an event-driven architecture, where an event loop continuously listens for events and dispatches
them to event handlers when appropriate. This architecture allows Node.js to handle many connections
concurrently with low overhead compared to traditional multi-threaded models.
1. Event Loop: Handles asynchronous operations by executing callbacks when events are triggered. It
eliminates the need for multiple threads, which reduces overhead.
2. V8 Engine: The underlying JavaScript engine that compiles JavaScript into native machine code for faster
execution.
3. Libuv: A library that provides Node.js with the event-driven architecture and asynchronous I/O
capabilities.
Applications of Node.js
Node.js is particularly well-suited for building applications that require real-time interaction, high concurrency,
and fast data processing. It’s widely used in a variety of scenarios:
1. Web Servers and APIs:
 Node.js can be used to build lightweight, high-performance web servers without the need for third-party
software like Apache or Nginx.
 It is ideal for building RESTful APIs and GraphQL APIs due to its non-blocking I/O and asynchronous
nature.
const http = require('http');

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


res.statusCode = 200;

7
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});

server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});

Introduction to Node.js
Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside
of a browser. It is built on the V8 JavaScript engine developed by Google and is designed for building scalable
network applications. Node.js uses an event-driven, non-blocking I/O model, which makes it highly efficient
and suitable for real-time applications.
Key Features of Node.js:
1. Asynchronous and Event-Driven:
o All APIs of Node.js are asynchronous (non-blocking), which means it can handle multiple
operations concurrently without waiting for one operation to complete before starting another.
o Event-driven architecture allows Node.js to manage multiple requests simultaneously using events
and callbacks.
2. Single-Threaded but Scalable:
o Although Node.js operates in a single thread, it is designed for scalability. It uses the event loop to
handle requests asynchronously and delegates heavy I/O operations (like database access, file
reading) to worker threads, allowing it to handle thousands of requests without blocking.
3. Non-Blocking I/O:
o Node.js uses a non-blocking I/O model, meaning it can initiate an I/O operation and continue
executing other code while waiting for the result of the I/O operation, improving performance.
4. Cross-Platform:
o Node.js can be run on various operating systems like Windows, macOS, and Linux, making it
versatile and widely adopted in development environments.
5. NPM (Node Package Manager):
o NPM is the default package manager for Node.js. It provides a vast ecosystem of libraries and
modules that developers can install and use in their applications, significantly speeding up
development.
6. JavaScript Everywhere:
o With Node.js, developers can write both client-side and server-side code in JavaScript, making
full-stack JavaScript development possible and more consistent.
Node.js Architecture
Node.js uses an event-driven architecture, where an event loop continuously listens for events and dispatches
them to event handlers when appropriate. This architecture allows Node.js to handle many connections
concurrently with low overhead compared to traditional multi-threaded models.
1. Event Loop: Handles asynchronous operations by executing callbacks when events are triggered. It
eliminates the need for multiple threads, which reduces overhead.
2. V8 Engine: The underlying JavaScript engine that compiles JavaScript into native machine code for faster
execution.
3. Libuv: A library that provides Node.js with the event-driven architecture and asynchronous I/O
capabilities.
Applications of Node.js
Node.js is particularly well-suited for building applications that require real-time interaction, high concurrency,
and fast data processing. It’s widely used in a variety of scenarios:
1. Web Servers and APIs:
 Node.js can be used to build lightweight, high-performance web servers without the need for third-party

8
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

software like Apache or Nginx.


 It is ideal for building RESTful APIs and GraphQL APIs due to its non-blocking I/O and asynchronous
nature.
Example:
javascript
Copy code
const http = require('http');

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


res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});

server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
2. Real-Time Applications:
 Node.js is great for real-time applications like chat applications, collaboration tools, and gaming
servers due to its event-driven, non-blocking architecture.
 WebSockets can be used to establish a real-time, two-way communication between the client and the
server.
Example: Real-time chat application using Socket.io.

const express = require('express');


const http = require('http');
const socketIo = require('socket.io');

const app = express();


const server = http.createServer(app);
const io = socketIo(server);

io.on('connection', (socket) => {


console.log('a user connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});

server.listen(3000, () => {
console.log('listening on *:3000');
});

3. Microservices:
 Node.js is commonly used to develop microservices—small, independent services that work together to
form a large application. Its lightweight nature and support for RESTful APIs make it ideal for breaking
down monolithic applications into microservices.

9
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

4. Single-Page Applications (SPAs):


 Node.js is often paired with front-end frameworks like React, Angular, or Vue.js to build SPAs. These
applications rely on a fast backend for API requests, which Node.js can handle efficiently.
 Since Node.js allows JavaScript to run both on the client and server, it can be used with Server-Side
Rendering (SSR) for improved performance in SPAs.
5. Data-Intensive Real-Time Applications (DIRT):
 Node.js is perfect for applications that require real-time data processing, such as streaming services, real-
time analytics, or online multiplayer games.
 For example, Netflix uses Node.js to stream movies and optimize delivery speed.
6. IoT (Internet of Things):
 Node.js can be used to build scalable IoT systems, where many devices are connected and
sending/receiving data in real-time. Its asynchronous nature makes it suitable for handling numerous
device connections simultaneously.
7. Command-Line Tools:
 Node.js can also be used to create powerful command-line utilities and scripts for automation.
 Tools like Webpack, Gulp, and Yeoman are built with Node.js.
8. Task Runners and Build Tools:
 Node.js is often used for automating repetitive tasks in the development process, such as minifying files,
running tests, and bundling code (e.g., Grunt, Gulp, Parcel).
9. Backend for Mobile Applications:
 Node.js serves as an efficient backend for mobile applications, especially when paired with frameworks
like Express.js and databases like MongoDB.
10. Streaming Applications:
 Applications like video or audio streaming benefit from Node.js due to its ability to process and upload
large amounts of data in small chunks, rather than buffering the entire file. This makes it ideal for media
streaming platforms.

Examples of Companies Using Node.js:


 Netflix: Optimized the performance of its web servers to handle millions of users.
 LinkedIn: Reduced server resources and improved performance for mobile apps using Node.js.
 Uber: Built a scalable and efficient backend for handling real-time data and requests.
 PayPal: Improved response times and performance by switching from Java to Node.js.

Conclusion
Node.js is a powerful, flexible, and efficient runtime for building a variety of applications, especially those that
require high concurrency, real-time interaction, and scalability. Its non-blocking, event-driven architecture makes
it well-suited for I/O-heavy applications, and its extensive ecosystem of packages through NPM allows
developers to rapidly build and deploy applications across different industries.

Environment Setup

Setting up the Node.js environment involves installing Node.js, its package manager (NPM), and setting up the
basic tools needed to develop and run Node.js applications. Below is a step-by-step guide to get Node.js up and
running on your system:
1. Download and Install Node.js
For Windows, macOS, and Linux:
 Official Website: Go to the official Node.js website.
 You will see two versions available for download:
o LTS (Long Term Support): Recommended for most users because it's more stable and receives
long-term updates.

10
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

o
Current Version: Contains the latest features but may be less stable.
Choose the LTS version unless you specifically need the latest features in the current release.
For Linux (Alternative via Terminal):
Ubuntu/Debian-based systems:
1. Update the package repository and install Node.js

sudo apt update


sudo apt install nodejs npm

CentOS/RHEL-based systems:
1. Use curl to fetch and add the Node.js repository:

curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -


sudo yum install -y nodejs

Verify Installation:
After installation, verify that Node.js and NPM are installed correctly by running the following commands:

node -v # To check the Node.js version


npm -v # To check the NPM version

2. Setting Up a Node.js Project


Step 1: Create a Project Directory
Create a new directory where your Node.js project will reside.

mkdir my-node-app
cd my-node-app

Step 2: Initialize a Node.js Project


Use the npm init command to create a package.json file, which holds metadata about the project and its
dependencies.

npm init

This command will prompt you for various inputs such as project name, version, description, entry point, and
author. You can hit "Enter" to accept the defaults or customize them as per your needs.
Alternatively, you can use the -y flag to skip all the prompts and create a default package.json file:

npm init –y

This generates a package.json file similar to the following:

{
"name": "my-node-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},

11
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

"author": "",
"license": "ISC"
}

Step 3: Create a Simple Node.js Application


Create a new file named index.js in your project directory.

touch index.js

Add a simple "Hello World" HTTP server to the index.js file:

// Load the http module to create an HTTP server.


const http = require('http');

// Configure the HTTP server to respond with "Hello, World!" to all requests.
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});

// Listen on port 3000, IP defaults to 127.0.0.1 (localhost)


server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});

Step 4: Run the Node.js Application


To run the application, use the following command:

node index.js

You should see the message: Server running at http://localhost:3000/.


Open your web browser and navigate to http://localhost:3000/, and you should see the message Hello, World!.

3. Installing Packages with NPM


NPM (Node Package Manager) is used to install and manage external libraries and dependencies. To install a
package, you use the npm install command.
Example: Installing Express.js (a web framework for Node.js)
1. Install the Express package:

npm install express

const express = require('express');


const app = express();

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


res.send('Hello from Express!');

12
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

});

app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});

Run the application:

node index.js

Visit http://localhost:3000/, and you will see the message: Hello from Express!.

4. Using Nodemon for Auto-Restarting the Server


During development, it can be tedious to manually restart the server each time you make a change. Nodemon is a
tool that automatically restarts your Node.js application when it detects changes in your source files.
Step 1: Install Nodemon Globally
Install Nodemon globally using NPM:

npm install -g nodemon

Step 2: Run the Application with Nodemon


Instead of using node index.js, use nodemon to run your application:

nodemon index.js

Now, the server will automatically restart whenever you make changes to any files in the project.

5. Setting Environment Variables


Environment variables are often used to configure the behavior of Node.js applications (e.g., database credentials,
API keys).
Example: Using the dotenv Package
1. Install dotenv package:

npm install dotenv

Create a .env file in your project directory:

PORT=4000
MESSAGE="Hello from the environment"

Use environment variables in your index.js:

require('dotenv').config(); // Load environment variables from .env file

const express = require('express');


const app = express();

const port = process.env.PORT || 3000;

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


res.send(process.env.MESSAGE || 'Hello, World!');

13
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

});

app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

Run the application:

nodemon index.js

The server will now run on port 4000 (from the .env file), and the message will be read from the environment
variable.

6. Basic Project Structure


For larger applications, organizing your Node.js project into separate folders and modules is important for
maintainability.
Example directory structure:

my-node-app/
├── node_modules/ # Installed packages
├── public/ # Static files (CSS, JS, images)
├── routes/ # Route handlers
│ └── index.js # Example route handler
├── views/ # Views for rendering HTML (if using a templating engine)
├── .env # Environment variables
├── package.json # Project metadata and dependencies
├── index.js # Main entry point
└── README.md # Project documentation

7. Conclusion
By following these steps, you can easily set up a Node.js environment, create a basic application, manage
packages, and improve your workflow with tools like nodemon. Once set up, you're ready to start building
scalable, high-performance web applications using Node.js!

REPL Terminal
Node.js REPL (Read-Eval-Print-Loop) Terminal
The REPL is an interactive shell that allows you to execute JavaScript and Node.js code directly in a terminal. It
stands for Read-Eval-Print Loop:
 Read: The REPL reads your input (JavaScript code).
 Eval: It evaluates your code.
 Print: It prints the result of the evaluation.
 Loop: It loops, waiting for more code or commands.
The REPL is very useful for quickly testing small pieces of code, debugging, or experimenting with Node.js
functionality.
Accessing the Node.js REPL
To start the Node.js REPL:
1. Open your terminal (Command Prompt, PowerShell, or terminal in macOS/Linux).
2. Simply type the following command and press Enter

Node

14
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

You will see the REPL prompt:

>

Now, you're inside the REPL environment, and you can execute JavaScript code interactively.
Example Usage of REPL
Basic Math Operations
You can perform simple math operations directly:

>2+3
5
> 10 * 4
40

Variable Declaration and Functions


You can define variables, functions, and use them:

> let name = "Alice";


undefined
> console.log("Hello, " + name + "!");
Hello, Alice!
undefined

> function square(x) { return x * x; }


undefined
> square(5);
25

Accessing Node.js Modules


You can also load and use Node.js built-in modules, such as fs for file system operations or http to create servers:

> const fs = require('fs');


undefined
> fs.readdirSync('.')
[ 'index.js', 'package.json', 'node_modules' ]

Multi-line Code
The REPL also supports multi-line input. For example, you can define a function block like this:

> function add(a, b) {


... return a + b;
... }
undefined
> add(2, 3);
5

REPL Commands
The Node.js REPL has several built-in commands:
1. .help: Displays help and lists all REPL commands.

15
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

> .help

.exit: Exits the REPL.

> .exit

.save [filename]: Saves the current REPL session to a file.

> .save mySession.js

.load [filename]: Loads a JavaScript file into the REPL.

> .load mySession.js

.clear: Resets the REPL context, clearing any defined variables.

> .clear

_ (underscore): The last evaluated expression result is stored in the _ variable.

> 10 + 20
30
>_
30

Features of Node.js REPL


 Tab Completion: Start typing a variable or function name and press Tab to auto-complete or see
suggestions.
 History: The REPL maintains a history of commands. Use the up/down arrow keys to cycle through
previously entered commands.
 Error Handling: If you enter invalid code, the REPL will print the error without crashing:

> console.log(unknownVar);
ReferenceError: unknownVar is not defined

REPL Use Cases


 Quick Prototyping: You can quickly try out code snippets or experiment with JavaScript and Node.js
features.
 Debugging: Test small pieces of code to debug functions or logic.
 Learning: It's a great tool for beginners to practice and learn JavaScript and Node.js concepts
interactively.
Exiting the REPL
To exit the REPL, you can:
 Type .exit and press Enter, or
 Press Ctrl + C twice.

NPM (Node Package Manager)


NPM (Node Package Manager)
NPM (Node Package Manager) is the default package manager for Node.js and is a critical part of the Node.js
ecosystem. It allows developers to download, install, manage, and share reusable code (libraries or packages)

16
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

with other developers. NPM also serves as a repository of open-source libraries that developers can integrate into
their Node.js projects.
NPM is automatically installed when you install Node.js.

Key Features of NPM:


1. Package Installation:
o NPM provides a simple way to install packages (libraries, modules) into your project, and it
manages the package dependencies automatically.
2. Version Management:
o NPM tracks versions of packages, allowing you to specify which version of a package you need.
o Developers can update packages to newer versions when needed or lock to specific versions to
maintain stability.
3. Package Publishing:
o Developers can publish their own libraries to the NPM registry, making them available to others.
4. Scripts and Task Automation:
o NPM allows you to define custom scripts within the package.json file that automate tasks like
running tests, building code, or starting servers.
5. NPM Registry:
o The NPM registry is a large database of public and private packages, which you can access via the
command line or through the NPM website.

NPM Commands
Here are some of the most commonly used NPM commands:
1. Installing Packages
 Local Installation: To install a package locally (specific to the project):
npm install <package-name>

This installs the package inside the node_modules/ folder of your project and adds it to your package.json file
under "dependencies".
Example:

npm install express

Global Installation: To install a package globally (available system-wide, outside of the current project):

npm install -g <package-name>

Example:

npm install -g nodemon

2. Uninstalling Packages
To uninstall a package from your project:

npm uninstall <package-name>

This removes the package from node_modules/ and updates the package.json file.
3. Creating a package.json File
To initialize a new Node.js project with a package.json file, use the following command in the root of your
project directory:

17
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

npm init

This will prompt you with a series of questions about your project (name, version, description, etc.) and create the
package.json file. If you want to skip the prompts and create a default file, use:

npm init –y

4. Updating Packages
To update a package to the latest version:

npm update <package-name>

5. Viewing Installed Packages


To see a list of all locally installed packages:

npm list
For globally installed packages:

6. Package Versions
 Install a specific version of a package

npm install <package-name>@<version>

Example:
npm install [email protected]

7. Managing Dev Dependencies


For packages that are only required for development (e.g., testing frameworks, linters), you can add them as dev
dependencies:

npm install <package-name> --save-dev

This will add the package to the devDependencies section in package.json.


8. Running Scripts
NPM allows you to define scripts in the package.json file to automate tasks:

{
"scripts": {
"start": "node index.js",
"test": "mocha"
}
}

You can run the script by using:

npm run <script-name>

For example:

npm run start

18
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

Understanding package.json
The package.json file is a crucial part of any Node.js project. It holds metadata about the project and contains
information about the project's dependencies, scripts, and version control.
Here’s an example of a basic package.json file:

{
"name": "my-node-app",
"version": "1.0.0",
"description": "A simple Node.js app",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"No test specified\" && exit 1"
},
"author": "Your Name",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"nodemon": "^2.0.12"
}
}

of the project (typically index.js).


-name>.

NPM Configuration and Cache


 NPM Config: NPM allows you to set configuration options that affect its behavior globally or for a
specific project. You can set configuration options using the following:

npm config set <key> <value>


Example:
npm config set init-author-name "John Doe"

NPM Cache: NPM caches packages after downloading them to make future installs faster. If you encounter
issues with cached files, you can clear the cache using:

npm cache clean –force

Working with Private Packages


NPM allows you to create and manage private packages that can only be accessed by authorized users. This is
particularly useful for organizations that want to share packages internally but don’t want to make them public.
1. Creating a Private Package:
o In your package.json, set "private": true to ensure the package is not accidentally published as a
public package.

19
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

2. Publishing a Private Package: You need to be logged into your NPM account to publish a private package.
To publish a package:

npm publish --access restricted

NPM vs Yarn
Yarn is an alternative package manager to NPM that was created by Facebook. It was introduced to address some
of the shortcomings of NPM (e.g., speed, consistency) but both have improved over time.
Key differences between NPM and Yarn:
 Speed: Yarn was initially faster due to better caching, but NPM has significantly improved with features
like npm ci.
 Lock Files: Both use lock files (package-lock.json for NPM, yarn.lock for Yarn) to ensure consistency in
installed packages.
 Community: NPM has a larger user base, but Yarn is popular in some large organizations.

Conclusion
NPM is an essential tool for any Node.js developer. It simplifies the management of packages, dependencies, and
version control, making the development process faster and more efficient. With its wide range of features like
scripts, versioning, and task automation, NPM is at the core of the modern JavaScript ecosystem.

callbacks Concept, Events, Packaging, Express Framework, Restful API.

1. Callbacks in Node.js
A callback is a function that is passed as an argument to another function and is executed after the first function
has completed its operation. In Node.js, callbacks are widely used to handle asynchronous operations such as file
reading, database queries, and API requests.
Example of a Callback Function:

function fetchData(callback) {
console.log("Fetching data...");

setTimeout(() => {
console.log("Data fetched.");
callback("Here is the data.");
}, 2000);
}

function processData(data) {
console.log("Processing: " + data);
}

fetchData(processData);

In this example, fetchData simulates an asynchronous operation using setTimeout, and processData is passed as a
callback to execute after the data is fetched.
Callback Pattern in Node.js APIs
Node.js follows the common convention of passing the error as the first argument in callback functions, known as
error-first callbacks.
Example using fs.readFile():

20
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {


if (err) {
console.error("Error reading file: ", err);
return;
}
console.log("File contents: ", data);
});

Here, err will hold any error that occurs during file reading, and data will contain the file's content if the operation
is successful.

2. Events in Node.js
Node.js has a built-in event-driven architecture, where certain objects (like EventEmitter) can emit named
events that other objects can listen to and react to. This makes Node.js powerful for handling asynchronous tasks
like network operations, file I/O, and server requests.
EventEmitter in Node.js
The events module in Node.js provides the EventEmitter class that allows you to create, emit, and listen for
custom events.
Example of Using EventEmitter:

const EventEmitter = require('events');


const eventEmitter = new EventEmitter();

// Define an event listener


eventEmitter.on('dataReceived', (data) => {
console.log("Data received: ", data);
});

// Emit an event
eventEmitter.emit('dataReceived', 'Hello from Node.js!');

In this example, the dataReceived event is emitted and caught by a listener, which then processes the data.

3. Packaging in Node.js
In Node.js, packages are collections of modules (libraries) that you can use in your project. A package typically
includes a set of JavaScript files and a package.json file that defines the metadata of the package.
Package Creation
To create your own package:
1. Initialize a new project: Use the following command to create a package.json file

npm init

Add dependencies: Install external packages (like Express or Lodash) by running

npm install <package-name>

1. Share your package: You can publish your package to the npm registry so others can install it.
Package Structure Example:

21
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

my-package/
├── index.js
├── package.json
└── node_modules/

4. Express Framework
Express.js is a minimalist web framework for Node.js that simplifies building web applications and APIs. It
provides utilities to manage HTTP requests, define routes, and handle middleware.
Key Features of Express:
 Routing: Express allows you to define routes for different HTTP methods (GET, POST, PUT, DELETE,
etc.).
 Middleware: Middleware functions in Express are used to process requests and responses. They are
executed in the order they are defined.
 Templating Engines: You can render dynamic HTML using template engines like EJS, Pug, or
Handlebars.
Example of Express.js Setup:
1. Install Express:

npm install express

Create a Simple Web Server with Express:

const express = require('express');


const app = express();

// Define a route for the root URL


app.get('/', (req, res) => {
res.send('Hello from Express!');
});

// Start the server on port 3000


app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});

This code starts a basic HTTP server on port 3000 and responds with "Hello from Express!" when visiting
http://localhost:3000/.
Middleware Example:
const express = require('express');
const app = express();

// Middleware function
app.use((req, res, next) => {
console.log('Request received at: ' + new Date());
next();
});

// Route
app.get('/', (req, res) => {
res.send('Hello with middleware!');
});

22
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

// Start server
app.listen(3000);
In this example, the middleware logs the date and time of each request before proceeding to the route handler.

5. RESTful API
A RESTful API (Representational State Transfer) is an architectural style for designing networked applications,
particularly web services. A RESTful API uses HTTP methods to perform CRUD (Create, Read, Update, Delete)
operations on resources.
HTTP Methods in REST:
 GET: Retrieve data (read).
 POST: Create new data (create).
 PUT: Update existing data (update).
 DELETE: Remove data (delete).
Example of a RESTful API with Express:
const express = require('express');
const app = express();

app.use(express.json()); // Middleware to parse JSON request bodies

// Sample data (in-memory)


let books = [
{ id: 1, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
{ id: 2, title: '1984', author: 'George Orwell' }
];

// GET: Retrieve all books


app.get('/books', (req, res) => {
res.json(books);
});

// GET: Retrieve a single book by ID


app.get('/books/:id', (req, res) => {
const book = books.find(b => b.id == req.params.id);
if (!book) return res.status(404).send('Book not found');
res.json(book);
});

// POST: Create a new book


app.post('/books', (req, res) => {
const newBook = {
id: books.length + 1,
title: req.body.title,
author: req.body.author
};
books.push(newBook);
res.status(201).json(newBook);
});

// PUT: Update an existing book


app.put('/books/:id', (req, res) => {

23
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

const book = books.find(b => b.id == req.params.id);


if (!book) return res.status(404).send('Book not found');

book.title = req.body.title;
book.author = req.body.author;
res.json(book);
});

// DELETE: Delete a book


app.delete('/books/:id', (req, res) => {
const bookIndex = books.findIndex(b => b.id == req.params.id);
if (bookIndex === -1) return res.status(404).send('Book not found');

books.splice(bookIndex, 1);
res.send('Book deleted');
});

// Start the server


app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
REST API Example Summary:
 GET /books: Retrieves all books.
 GET /books/
: Retrieves a specific book by its ID.
 POST /books: Adds a new book to the collection.
 PUT /books/
: Updates the details of a book.
 DELETE /books/
: Removes a book from the collection.

Conclusion
 Callbacks in Node.js handle asynchronous operations.
 Events are emitted and listened to in Node.js, using the event-driven architecture.
 Packaging in Node.js involves using and managing third-party libraries through NPM.
 Express is a popular Node.js web framework for handling HTTP requests, routing, and middleware.
 RESTful APIs enable interaction with resources over the web using HTTP methods (GET, POST, PUT,
DELETE).
Together, these concepts form a foundation for building powerful, scalable, and efficient web applications using
Node.js.

24

You might also like