0% found this document useful (0 votes)
8 views55 pages

Unit4 Web Tech

A JavaBean is a Java class that follows specific conventions, such as having a no-arg constructor and being Serializable, which allows for easy maintenance and reuse of software components. Enterprise Java Beans (EJB) encapsulate business logic and include types like Session Beans, Entity Beans, and Message-Driven Beans, each serving different purposes in distributed applications. Node.js is an open-source JavaScript runtime environment that enables server-side programming, offering advantages such as scalability, real-time web app capabilities, and a rich ecosystem for building applications.
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)
8 views55 pages

Unit4 Web Tech

A JavaBean is a Java class that follows specific conventions, such as having a no-arg constructor and being Serializable, which allows for easy maintenance and reuse of software components. Enterprise Java Beans (EJB) encapsulate business logic and include types like Session Beans, Entity Beans, and Message-Driven Beans, each serving different purposes in distributed applications. Node.js is an open-source JavaScript runtime environment that enables server-side programming, offering advantages such as scalability, real-time web app capabilities, and a rich ecosystem for building applications.
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/ 55

JavaBean

A JavaBean is a Java class that should follow the following conventions:


● It should have a no-arg constructor.
● It should be Serializable.
● It should provide methods to set and get the values of the properties, known as getter and
setter methods.
Why use JavaBean?
According to Java white paper, it is a reusable software component. A bean encapsulates many
objects into one object so that we can access this object from multiple places. Moreover, it
provides easy maintenance.
Simple example of JavaBean class
● //Employee.java
● package mypack;
● public class Employee implements java.io.Serializable{
● private int id;
● private String name;
● public Employee(){}
● public void setId(int id){this.id=id;}
● public int getId(){return id;}
● public void setName(String name){this.name=name;}
● public String getName(){return name;}
● }
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.
● package mypack;
● public class Test{
● public static void main(String args[]){
● Employee e=new Employee();//object is created
● e.setName("Arjun");//setting value to the object
● System.out.println(e.getName());
● }}
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object. The
feature can be of any Java data type, containing the classes that you define.
A JavaBean property may be read, write, read-only, or write-only. JavaBean features are
accessed through two methods in the JavaBean's implementation class:
1. getPropertyName ()
For example, if the property name is firstName, the method name would be getFirstName() to
read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be setFirstName() to
write that property. This method is called the mutator.
Advantages of JavaBean
The following are the advantages of JavaBean:/p>
● The JavaBean properties and methods can be exposed to another application.
● It provides an easiness to reuse the software components.
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:
● JavaBeans are mutable. So, it can't take advantages of immutable objects.
● Creating the setter and getter method for each property separately may lead to the
boilerplate code.

Types of EJB
EJB is an acronym for Enterprise Java Beans. It is a server-side software element. It
encapsulates the business logic of an application. It is a specification for developing a
distributed business application on the Java platform. There are three types of EJBs: Session
Bean, Entity Bean, and Message-Driven Bean. In this section,
Session Bean
The bean sprout business idea that can be systematically used by customer, remote, and web
service. When a client wants to use an application distributed on a server, then the client uses
session bean methods. This session bean provides services to customers, protecting them from
complex problems by performing business operations within the server.
To get to an application that is conveyed to the worker, the client summons the meeting bean's
strategies. The meeting bean performs work for its client, safeguarding it from intricacy by
executing business errands inside the worker. Remember that session beans are not persistence.
There are two types of session beans:
● Stateless Session Beans
● Stateful Session Beans
● Singleton Session Beans
Stateless Session Beans
A stateless session bean doesn't keep a conversational state with the customer or client. When
a client invokes the methods for a stateless bean, the bean's instance variable may contain a
state explicitly to that client however only for the span of the invocation.
At the point when the method has finished, the client explicit state should not be held. However,
the client may change the state of instance variable presented in pooled stateless beans, and
this state is held over to the following invocation of the pooled stateless bean.
Since they can maintain various customers, stateless session beans can offer better adaptability
for applications that require large numbers of clients. Ordinarily, an application requires fewer
stateless session beans than stateful session beans to support the same number of clients.
To improve execution, we may choose a stateless session bean in the event that it has any of
these characteristics
● The state of the bean has no information or data for a particular client.
● In a private method invocation, the bean performs a generic task for all clients.
● The bean implements a web service.
Stateful Session Beans
A stateful session bean is the same as an interactive session. The state of an object comprises
the values of its instance variables. In a stateful session bean, the instance variables denote the
state of a unique client/bean session. Since, the client interacts with its bean. The state is usually
called the conversational state. It maintains the state of a client across multiple requests. So, we
cannot implement it in the web services because it cannot be shared. When the client terminates
the session, it is no longer associated with the client.
The state is held for the span of the client/bean session. In case if the client eliminates the bean,
the session closes and the state is omitted. This transient nature of the state isn't an issue,
because the interaction between the client and the beans ends. So, it is not required to hold the
state.
Stateful session beans should be used, if any of the following conditions are valid:
● The bean's state denotes the alliance between the bean and a particular client.
● The bean needs to hold data about the customer across method invocations.
● The bean interferes between the customer and different segments of the application,
introducing an improved visible to the client.
● In the background, the bean deals with the workstream of a few enterprise beans.
Singleton Session Beans
A singleton session bean maintains one instance per application and the instance exists for the
lifecycle of the application. It offers the same functionality as the stateless session beans. But
the only difference is that there is only one singleton session bean per application while in the
stateless session bean a pool of beans is used.
From that pool, any of the session beans may respond to the client. We can implement it in the
web-service endpoints. It takes care of the state but does not hold the state if unexpected
crashes or shutdown occur. It can be used if we want to perform cleanup tasks on closing the
application or shut down as well. It is because it operates throughout the life cycle of the
application.
Singleton session beans are suitable for the following conditions:
● The state of the bean must be shared across the application.
● A single enterprise bean should be accessed by multiple threads concurrently.
● The application needs an enterprise bean to perform undertakings upon application
startup and shutdown.
● The bean implements a web service.
Entity Bean
An entity bean is an unpredictable business substance. It models a business substance or
models different activities inside a business interaction. It is used to encourage business
benefits that include data and calculations on that data. It can deal with various, needy, diligent
articles in playing out its essential assignments. A substance bean is a far-off object that
oversees steady information and performs complex business rationale. It can be extraordinarily
distinguished by an essential key.
It is a far-off object that oversees steady information, performs complex business rationale,
possibly utilizes a few ward Java protests, and can be remarkably distinguished by an essential
key. It ordinarily coarse-grained determined items since they use steady information put away
inside a few fine-grained relentless Java objects. Element beans are diligent on the grounds that
they do endure a worker crash or an organization's disappointment.
Every entity bean has a persistence identity that is associated with it. It means that it comprises
a unique identity that can be fetched if we have a primary key. The type for the unique key is
defined by the bean provider. A client can retrieve the entity bean if the primary has been
misplaced. If the bean is not available, the EJB container first, instantiates the bean and then re-
populates the data for the client.
The diligence for entity bean information is given both to saving state when the bean is
passivated and for improving the state when a failover has detected. It can endure in light of the
fact that the information is put away determinedly by the holder in some type of information
stockpiling framework, like a data set.
Entity beans persist business data by using the following two methods:
● Bean-Managed Persistence (BMP)
● Container-Managed Persistence (CMP)
Bean Managed Persistence
Bean-managed persistence is more complicated in comparison to container-managed
persistence. Because it allows us to write the persistence logic into the bean class, explicitly. In
order to write the persistence handling code into the bean class, we must know the type of
database that is being used and how fields of the bean class are mapped to the database.
Therefore, it provides more flexibility between the database and the bean instance.
Container-Managed Persistence
In container-managed persistence, the EJB container transparently and implicitly handles the
relationship between the bean and the database. Bean developers focus on the data and the
business process. The principal constraint is that the EJB compartment can most likely not
produce information base access articulations with the proficiency of a programmer.
Unlike BMP, CMP does not allow us to write database access calls in the methods of the entity
bean class. It is because the persistence is handled by the container at run-time. The following
two things are required to support the CMP:
● Mapping: It denotes that how to map an entity bean to a resource.
● Runtime Environment: A CMP runtime environment that uses the mapping information to
perform persistence operations on each bean.
Message-Driven Bean (MDB)
MDB is a Java Messaging Service (message listener). It consumes messages from a queue or
subscription of a topic. It provides an easy way to create or implement asynchronous
communication using a JMS message listener. An advantage of using MDB is that it allows us to
use the asynchronous nature of a JMS listener. We can implement message-driven beans with
Oracle JMS (Java Messaging Service).
There is an EJB container (contains MDBs pool) that handles the JMS queue and topic. Each
incoming message is handled by a bean that is invoked by the container. Note that no object
invokes an MDB directly. All invocation for MDB originates from the container. When the
container invokes the MDB, it can invoke other EJBs or Java objects to continue the request.

It is quite similar to stateless session bean. Because it does not save informal state, also used to
handle multiple incoming requests. EJB has the following benefits over the JMS are as follows:
● It creates a consumer for the listener. It means that the container creates QueueReceiver
or TopicSubscriber is created by the container.
● MDB is registered with the consumer. It means that at deployment time QueueReceiver,
TopicSubscriber, and its factory are registered by the container.
● The message ACK mode is specified.
The primary function of MDB is to read (receive) or write (send) incoming from a JMS destination
(i.e. queue or topic). While using MDB ensure that it is configured and installed properly. It
interacts with JMS and the JMS installed on the Oracle database. The database retains queue or
topic. The following figure depicts how MDB interacts with the JMS destination.

The working of MDB is as follows:


● MDB creates and opens a JMS connection to the database by using the data source (JMS
resource provider). The JDBC driver is used to facilitate the JMS connection.
● A JMS session over the JMS connection is opened by the MDB.
● If any message for the MDB is routed to the onMessage() method of the MDB from the
queue o topic. Other clients may also access the same queue and topic to put the
message for the MDB.

Node.js Introduction
Node.js is an open-source JavaScript server environment built on Chrome’s V8 engine. It is
open-source and free and runs on various platforms like Windows, Linux, Unix, MacOS, etc.
Node.js is an open-source, cross-platform JavaScript runtime environment that allows
developers to run JavaScript code on the server side. Created by Ryan Dahl in 2009, Node.js has
revolutionized server-side programming by offering an efficient, event-driven, and non-blocking
I/O model.
It’s a powerful tool used for various types of projects. Let’s explore some key aspects:
● JavaScript Runtime: Node.js runs on the V8 JavaScript engine, which is also the core
engine behind Google Chrome.
● Single Process Model: A Node.js application operates within a single process, avoiding

the need to create a new thread for every request.
● Asynchronous I/O: Node.js provides a set of asynchronous I/O primitives in its standard
library. These primitives prevent JavaScript code from blocking, making non-blocking
behavior the norm.
● Concurrency Handling: Node.js efficiently handles thousands of concurrent
connections using a single server. It avoids the complexities of managing thread
concurrency, which can lead to bugs.
● JavaScript Everywhere: Frontend developers familiar with JavaScript can seamlessly
transition to writing server-side code using Node.js.
● ECMAScript Standards: Node.js supports the latest ECMAScript standards. You can
choose the version you want to use, independent of users’ browser updates.
To get started and master the fundamentals, the Full Stack Development with Node JS course
offers a complete guide to creating server-side applications using Node.js.
Why Node.JS?
Node.js is used to build back-end services like APIs like Web App, Mobile App or Web Server. A
Web Server will open a file on the server and return the content to the client. It’s used in
production by large companies such as Paypal, Uber, Netflix, Walmart, and so on.
Reasons to Choose Node.js
● Easy to Get Started: Node.js is beginner-friendly and ideal for prototyping and agile
development.
● Scalability: It scales both horizontally and vertically.
● Real-Time Web Apps: Node.js excels in real-time synchronization.
● Fast Suite: It handles operations quickly (e.g., database access, network connections).
● Unified Language: JavaScript everywhere—frontend and backend.
● Rich Ecosystem: Node.js boasts a large open-source library and supports asynchronous,
non-blocking programming.
How Node.JS Works?
Node.js accepts the request from the clients and sends the response, while working with the
request node.js handles them with a single thread. To operate I/O operations or requests node.js
use the concept of threads. Thread is a sequence of instructions that the server needs to
perform. It runs parallel on the server to provide the information to multiple clients. Node.js is an
event loop single-threaded language. It can handle concurrent requests with a single thread
without blocking it for one request.
Advantages of Node.JS
● Easy Scalability: Easily scalable the application in both horizontal and vertical directions.
● Real-time web apps: Node.js is much more preferable because of faster synchronization.
Also, the event loop avoids HTTP overloaded for Node.js development.
● Fast Suite: NodeJS acts like a fast suite and all the operations can be done quickly like
reading or writing in the database, network connection, or file system
● Easy to learn and code: NodeJS is easy to learn and code because it uses JavaScript.
● Advantage of Caching: It provides the caching of a single module. Whenever there is any
request for the first module, it gets cached in the application memory, so you don’t need
to re-execute the code.
How Node.JS Works?
Node.js accepts the request from the clients and sends the response, while working with the
request node.js handles them with a single thread. To operate I/O operations or requests node.js
use the concept of threads. Thread is a sequence of instructions that the server needs to
perform. It runs parallel on the server to provide the information to multiple clients. Node.js is an
event loop single-threaded language. It can handle concurrent requests with a single thread
without blocking it for one request.
Advantages of Node.JS
● Easy Scalability: Easily scalable the application in both horizontal and vertical directions.
● Real-time web apps: Node.js is much more preferable because of faster synchronization.
Also, the event loop avoids HTTP overloaded for Node.js development.
● Fast Suite: NodeJS acts like a fast suite and all the operations can be done quickly like
reading or writing in the database, network connection, or file system
● Easy to learn and code: NodeJS is easy to learn and code because it uses JavaScript.
● Advantage of Caching: It provides the caching of a single module. Whenever there is any
request for the first module, it gets cached in the application memory, so you don’t need
to re-execute the code.
What is Node.JS file?
Node.js files contain tasks that handle file operations like creating, reading, deleting, etc.,
Node.js provides an inbuilt module called FS (File System).
Application of Node.JS
Node.js is suitable for various applications, including:
● Real-time chats
● Complex single-page applications
● Real-time collaboration tools
● Streaming apps
● JSON APIs
Common Use Cases of Node.JS
Node.js is versatile and finds applications in various domains:
1. Web Servers: Node.js excels at building lightweight and efficient web servers. Its non-
blocking I/O model makes it ideal for handling concurrent connections.
2. APIs and Microservices: Many companies use Node.js to create RESTful APIs and
microservices. Express.js simplifies API development.
3. Real-Time Applications: Node.js shines in real-time scenarios like chat applications, live
notifications, and collaborative tools. Socket.io facilitates real-time communication.
4. Single-Page Applications (SPAs): SPAs benefit from Node.js for server-side rendering
(SSR) and handling API requests.
5. Streaming Services: Node.js is well-suited for streaming data, whether it’s video, audio,
or real-time analytics.
Node.js Environment Setup
This Node.js tutorial consists of a number of ready-to-run examples, so that the learn can
understand the Node.js concepts by running the code. To be able to execute the example code,
you can use our online Node.js environment, or install Node.js environment in your local machine.
Local Environment Setup
If you are still willing to set up your environment for Node.js, this section will guide you. Node.js
can be installed on different OS platforms such as Windows, Linux, Mac OS X, etc. You need the
following tools on your computer −
● The Node.js binary installer
● Node Package Manager (NPM)
● IDE or Text Editor
Binaries for various OS platforms are available on the downloads page of the official website of
Node.js. Visit https://nodejs.org/en/downloadto get the list.

This page shows two sets of binaries for different OS platforms, one for the current or latest
version, and the other a version with LTS (Long Term Support), that is recommended for a normal
user. 32 bit and 64 bit installers as well as ZIP archives for Windows, macOS installer as well as
tar archives and binaries for Linux OS on x64 and ARM architecture are available.
Installation on Windows
Assuming that you are working with Windows 10/Windows 11 powered computer, download the
64-bit installer for Windows: https://nodejs.org/dist/v20.9.0/node-v20.9.0-x64.msi, and start the
installation b double-clicking the downloaded file.
The installation takes you through a few steps of the installation wizard. It also adds the
installation directory of Node.js executable to the system path.
To verify if Node.js has been successfully installed, open the command prompt and type node -v.
If Node.js is installed successfully then it will display the version of the Node.js installed on your
machine, as shown below.

Installation on Ubuntu Linux


First, download the tar file corresponding to Linux binary (https://nodejs.org/dist/v20.9.0/node-
v20.9.0-linux-x64.tar.xz) and then, extract the binary using the tar command −
tar -xf node-v20.9.0-linux-x64.tar.gz
Move the extracted files to the installation directory /usr/local/node-v20.9.0.
sudo mv node-<version> /usr/local/node-v20.9.0
Create a symlink to the executable in /usr/bin directory.
sudo ln -s /usr/local/node-v20.9.0/bin/node /usr/bin/node
You can now verify the correct installation with the following command −
node -v
Using Ubuntu package manager
Refresh your local package index first by the following command −
sudo apt update
Then install Node.js −
sudo apt install nodejs
As in above case, verify the installation
node -v
NPM (Node Package Manager) is included in Node.js binaries from its official website since Node
version 0.6.0., so you are not required to install it separately.
You can use any text editor available in your OS (notepad in Windows, vi or nano in Ubuntu) to
key-in and save the Node.js script. However, it is recommended that you use a suitable IDE for
the purpose as it has several features such as syntax highlighting etc. VS Code is a popular
source-code editor, which has out of the box support for JavaScript (and hence Node.js), which
is highly recommended.

Node.js REPL
The term REPL stands for Read Eval Print and Loop. It specifies a computer environment like a
window console or a Unix/Linux shell where you can enter the commands and the system
responds with an output in an interactive mode.
REPL Environment
The Node.js or node come bundled with REPL environment. Each part of the REPL environment
has a specific work.
Read: It reads user's input; parse the input into JavaScript data-structure and stores in memory.
Eval: It takes and evaluates the data structure.
Print: It prints the result.
Loop: It loops the above command until user press ctrl-c twice.
How to start REPL
You can start REPL by simply running "node" on the command prompt. See this:
You can execute various mathematical operations on REPL Node.js command prompt:
Node.js Simple expressions
After starting REPL node command prompt put any mathematical expression:
● Example: >10+20-5
● 25

Using variable
Variables are used to store values and print later. If you don't use var keyword then value is
stored in the variable and printed whereas if var keyword is used then value is stored but not
printed. You can print variables using console.log().
Node.js Multiline expressions
Node REPL supports multiline expressions like JavaScript. See the following do-while loop
example:
● var x = 0
● undefined
● > do {
● ... x++;
● ... console.log("x: " + x);
● ... } while ( x < 10 );

Node.js REPL Commands


Node.js Package Manager
Node Package Manager provides two main functionalities:
● It provides online repositories for node.js packages/modules which are searchable on
search.nodejs.org
● It also provides command line utility to install Node.js packages, do version management
and dependency management of Node.js packages.
The npm comes bundled with Node.js installables in versions after that v0.6.3. You can check the
version by opening Node.js command prompt and typing the following command:
● npm version

Installing Modules using npm


Following is the syntax to install any Node.js module:
● npm install <Module Name>
Let's install a famous Node.js web framework called express:
Open the Node.js command prompt and execute the following command:
● npm install express
You can see the result after installing the "express" framework.
Global vs Local Installation
By default, npm installs dependency in local mode. Here local mode specifies the folder where
Node application is present. For example if you installed express module, it created
node_modules directory in the current directory where it installed express module.
You can use npm ls command to list down all the locally installed modules.
Open the Node.js command prompt and execute "npm ls":
Node.js Package Manager
Node Package Manager provides two main functionalities:
● It provides online repositories for node.js packages/modules which are searchable on
search.nodejs.org
● It also provides command line utility to install Node.js packages, do version management
and dependency management of Node.js packages.
The npm comes bundled with Node.js installables in versions after that v0.6.3. You can check the
version by opening Node.js command prompt and typing the following command:
● npm version
Installing Modules using npm
Following is the syntax to install any Node.js module:
● npm install <Module Name>
Let's install a famous Node.js web framework called express:
Open the Node.js command prompt and execute the following command:
● npm install express
You can see the result after installing the "express" framework.

Global vs Local Installation


By default, npm installs dependency in local mode. Here local mode specifies the folder where
Node application is present. For example if you installed express module, it created
node_modules directory in the current directory where it installed express module.

You can use npm ls command to list down all the locally installed modules.
Open the Node.js command prompt and execute "npm ls":
Globally installed packages/dependencies are stored in system directory. Let's install express
module using global installation. Although it will also produce the same result but modules will be
installed globally.
Open Node.js command prompt and execute the following code:
● npm install express -g
Here first line tells about the module version and its location where it is getting installed.
Uninstalling a Module
To uninstall a Node.js module, use the following command:
● npm uninstall express
The Node.js module is uninstalled. You can verify by using the following command:

● npm ls

You can see that the module is empty now.


Searching a Module
"npm search express" command is used to search express or module.
● npm search express
What is Callback?
A Callback in Node.js is an asynchronous equivalent for a function. It is a special type of function
passed as an argument to another function. Node.js makes heavy use of callbacks. Callbacks
help us make asynchronous calls. All the APIs of Node are written in such a way that they
support callbacks.
Programming instructions are executed synchronously by default. If one of the instructions in a
program is expected to perform a lengthy process, the main thread of execution gets blocked.
The subsequent instructions can be executed only after the current I/O is complete. This is
where callbacks come in to the picture.
The callback is called when the function that contains the callback as an argument completes its
execution, and allows the code in the callback to run in the meantime. This makes Node.js highly
scalable, as it can process a high number of requests without waiting for any function to return
results.
The syntax of implementing callback in Node.js is as follows −
function function_name(argument, function (callback_argument){
// callback body
})
The setTimeout() function in Node.js is a typical example of callback. The following code calls
the asynchronous setTimeout() method, which waits for 1000 milliseconds, but doesn't block the
thread. Instead, the subsequent Hello World message, followed by the timed message.

setTimeout(function () {
console.log('This prints after 1000 ms');
}, 1000);

console.log("Hello World");
Output
Hello World
This prints after 1000 ms

Node.js Events
Node.js is built on an event-driven architecture that allows you to build highly scalable
applications. Understanding the event-driven nature of Node.js and how to work with events is
important for building efficient and responsive applications.
What Are Events in Node.js?
In Node.js, an event is an action or occurrence that the program can detect and handle. The
event-driven architecture allows asynchronous programming, and your application becomes able
to perform non-blocking operations. This means that while waiting for an operation to complete
(like reading a file or making a network request), the application can continue processing other
tasks.
EventEmitter Class
At the core of the Node.js event system is the EventEmitter class. This class allows objects to
emit named events that can be listened to by other parts of your application. It is included in the
built-in events module.
Key Features of EventEmitter:
● Event Registration: You can register listeners for specific events using the on() method.
● Event Emission: Use the emit() method to trigger an event and call all registered listeners
for that event.
● Asynchronous Execution: Listeners can execute asynchronously, allowing other
operations to continue while waiting for events.
Syntax:
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
Working with Events in Node.js
Step 1: Importing the Events Module
To start using events in your application, you need to import the events module
and create an instance of the EventEmitter class.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
Step 2: Registering Event Listeners
You can register listeners for specific events using the on() method. The first
argument is the event name, and the second argument is the callback function to
be executed when the event is emitted.
myEmitter.on('event', () => {
console.log('An event occurred!');
});
Step 3: Emitting Events
To trigger an event, use the emit() method with the event name as the first
argument.
myEmitter.emit('event'); // Output: An event occurred!
Listening events
Before emitting any event, it must register functions(callbacks) to listen to the
events.
Syntax:
eventEmitter.addListener(event, listener)
eventEmitter.on(event, listener)
eventEmitter.once(event, listener)
Removing Listener
The eventEmitter.removeListener() takes two argument event and listener, and
removes that listener from the listeners array that is subscribed to that event.
While eventEmitter.removeAllListeners() removes all the listener from the array
which are subscribed to the mentioned event.
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])

Node.js - Packaging
A large-sized Node.js project usually has a number of dependencies and a number of source
files as well as other assets such as images, web pages, setting files etc. To distribute a Node.js
project and deploy it on any other environment becomes difficult, and hence it needs to
packaged so that it can be easily ported to other machine. There are a number of packaging
tools available on NPM repository. This chapter discusses nexe packaging tool, and also takes
overview of some other packaging libraries.
Nexe
To demonstrate how the Nexe utility works, we shall an ExpressJs app with the following script −
Index.js
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,"index.html"));
})
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
app.post("/process_post", )
var server = app.listen(5000, function () {
console.log("Express App running at http://127.0.0.1:5000/");
})

The ‘/’ route renders a HTML form from the following script −
Index.html
<html>
<body>
<form action = "/process_POST" method = "POST">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name"> <br>
<input type = "submit" value = "Submit">
</form>

</body>
</html>
The Node.js server displays the following form −
Features of Nexe
● Self contained applications
● Ability to run multiple applications with different node.js runtimes.
● Distribute binaries without needing node / npm.
● Start and deploy faster.
● Flexible build pipeline
● Cross platform builds
Install Nexe on Windows
Perform global installation of Nexe as follows −
npm install nexe -g
You also need Netwide Assembler (NASM) tool. Download and install the same from
www.nasm.us
The nexe utility requires Python installed on the system. Ensure that Python is one of the
versions 3.11 to 3.7.
Assuming that you are using nexe for 64-bit Windows OS, you also need to install The "Desktop
development with C++" workload from Visual Studio 2022. It can be installed from aka.ms.
(For other OS platforms, follow the instructions on github.com/nodejs
Once all the prerequisites are installed, run the following command in the CMD terminal −
D:\expressApp>nexe index.js --build windows-x64-20.9.0 –verbose
The compilation may take a while, but in the end, it will create expressApp.exe in the application
folder.

D:\expressApp
│ expressApp.exe
│ index.html
│ index.js
│ package-lock.json
│ package.json
│ users.json

├───node_modules
│ │ .package-lock.json
│ ├───body-parser
│ │ │ HISTORY.md
│ │ │ index.js
│ │ │ LICENSE
│ │ │ package.json
│ │ │ README.md
│ │ │ SECURITY.md
│ │ │ ...
│ │ │ ...
│ │ │ ...
│ ├───express
│ │ │ History.md
│ │ │ index.js
│ │ │ LICENSE
│ │ │ package.json
│ │ │ Readme.md
│ │ │ ...
│ │ │ ...
│ │ │ ...
└───public
└───images
logo.png
Run it from the command line, and the Node.js server starts.
D:\expressApp>expressapp
Express App running at http://127.0.0.1:5000/

pkg tool
The pkg tool is a command-line interface that enables the developer to create executables from
Node.JS projects; allowing you to run the app even on environments that do not have Node.JS
installed on them.
To install pkg, use the command −
npm install -g pkg
Then use pkg to build the executable
pkg myapp.js
Running the above command will generate three programmes; namely an executable for
Windows, macOS, and Linux. More details can be found at www.npmjs.com.
JXCore
JXcore, which is an open source project, introduces a unique feature for packaging and
encryption of source files and other assets into JX packages.
Download and install the JXcore package from https://github.com/jxcore, as per your operating
system and machine architecture.
To package the above project, you simply need to go inside this directory and issue the following
jx command. Assuming index.js is the entry file for your Node.js project −
jx package index.js index
the above command will pack everything and will create the following two files −
index.jxp − This is an intermediate file which contains the complete project detail needed to
compile the project.
index.jx − This is the binary file having the complete package that is ready to be shipped to your
client or to your production environment.
Consider your original Node.js project was running as follows −
node index.js command_line_arguments
After compiling your package using JXcore, it can be started as follows −

jx index.jx command_line_arguments

Node.js - Express Framework


Express.js is a minimal and flexible web application framework that provides a robust set of
features to develop Node.js based web and mobile applications. Express.js is one of the most
popular web frameworks in the Node.js ecosystem. Express.js provides all the features of a
modern web framework, such as templating, static file handling, connectivity with SQL and
NoSQL databases.
Node.js has a built-in web server. The createServer() method in its http module launches an
asynchronous http server. It is possible to develop a web application with core Node.js features.
However, all the low level manipulations of HTTP request and responses have to be tediously
handled. The web application frameworks take care of these common tasks, allowing the
developer to concentrate on the business logic of the application. A web framework such as
Express.js is a set of utilities that facilitates rapid, robust and scalable web applications.
Following are some of the core features of Express framework −
● Allows to set up middlewares to respond to HTTP Requests.
● Defines a routing table which is used to perform different actions based on
HTTP Method and URL.
● Allows to dynamically render HTML Pages based on passing arguments to
templates.
The Express.js is built on top of the connect middleware, which in turn is based on http, one of
the core modules of Node.js API.
Installing Express
The Express.js package is available on npm package repository. Let us install express package
locally in an application folder named ExpressApp.
D:\expressApp> npm init
D:\expressApp> npm install express --save
The above command saves the installation locally in the node_modules directory and creates a
directory express inside node_modules.

Hello world Example


Following is a very basic Express app which starts a server and listens on port 5000 for
connection. This app responds with Hello World! for requests to the homepage. For every other
path, it will respond with a 404 Not Found.
var express = require('express');
var app = express();

app.get('/', function (req, res) {


res.send('Hello World');
})

var server = app.listen(5000, function () {


console.log("Express App running at http://127.0.0.1:5000/");
})
Save the above code as index.js and run it from the command-line.

D:\expressApp> node index.js


Express App running at http://127.0.0.1:5000/

Visit http://localhost:5000/ in a browser window. It displays the Hello World message.


Basic Routing
The app object handles HTTP requests GET, POST, PUT and DELETE with app.get(), app.post(),
app.put() and app.delete() method respectively. The HTTP request and HTTP response objects
are provided as arguments to these methods by the NodeJS server. The first parameter to these
methods is a string that represents the endpoint of the URL. These methods are asynchronous,
and invoke a callback by passing the request and response objects.
GET method
In the above example, we have provided a method that handles the GET request when the client
visits '/' endpoint.
app.get('/', function (req, res) {
res.send('Hello World');
})
● Request Object − The request object represents the HTTP request and has
properties for the request query string, parameters, body, HTTP headers, and so on.
● Response Object − The response object represents the HTTP response that an
Express app sends when it gets an HTTP request. The send() method of the response
object formulates the server's response to the client.

REST API Introduction


REpresentational State Transfer (REST) is an architectural style that defines a set of constraints
to be used for creating web services. REST API is a way of accessing web services in a simple
and flexible way without having any processing.
REST technology is generally preferred to the more robust Simple Object Access Protocol
(SOAP) technology because REST uses less bandwidth, simple and flexible making it more
suitable for internet usage. It’s used to fetch or give some information from a web service. All
communication done via REST API uses only HTTP request.
As you explore advanced techniques like building and integrating REST APIs , consider
expanding your skill set further. A comprehensive Full Stack Web Development course can
enhance both your frontend and backend development skills. This course will provide you with
the knowledge to effectively implement REST APIs within your web applications.
Working: A request is sent from client to server in the form of a web URL as HTTP GET or POST
or PUT or DELETE request. After that, a response comes back from the server in the form of a
resource which can be anything like HTML, XML, Image, or JSON. But now JSON is the most
popular format being used in Web Services.
Build REST API Mastery Learn to integrate popular and practical Python REST APIs in Django
web applications with Educative’s interactive skill path Become a Python-based API Integrator.
Sign up at Educative.io with the code GEEKS10 to save 10% on your subscription.

In HTTP there are five methods that are commonly used in a REST-based Architecture i.e., POST,
GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD)
operations respectively. There are other methods which are less frequently used like OPTIONS
and HEAD.

● GET: The HTTP GET method is used to read (or retrieve) a representation of a resource. In
the safe path, GET returns a representation in XML or JSON and an HTTP response code
of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD
REQUEST).
● POST: The POST verb is most often utilized to create new resources. In particular, it’s
used to create subordinate resources. That is, subordinate to some other (e.g. parent)
resource. On successful creation, return HTTP status 201, returning a Location header
with a link to the newly-created resource with the 201 HTTP status.
NOTE: POST is neither safe nor idempotent.
● PUT: It is used for updating the capabilities. However, PUT can also be used to create a
resource in the case where the resource ID is chosen by the client instead of by the server.
In other words, if the PUT is to a URI that contains the value of a non-existent resource ID.
On successful update, return 200 (or 204 if not returning any content in the body) from a
PUT. If using PUT for create, return HTTP status 201 on successful creation. PUT is not
safe operation but it’s idempotent.
● PATCH: It is used to modify capabilities. The PATCH request only needs to contain the
changes to the resource, not the complete resource. This resembles PUT, but the body
contains a set of instructions describing how a resource currently residing on the server
should be modified to produce a new version. This means that the PATCH body should not
just be a modified part of the resource, but in some kind of patch language like JSON
Patch or XML Patch. PATCH is neither safe nor idempotent.
● DELETE: It is used to delete a resource identified by a URI. On successful deletion, return
HTTP status 200 (OK) along with a response body.
MongoDB - Create Database
The use Command
MongoDB use DATABASE_NAME is used to create database. The command will create a new
database if it doesn't exist, otherwise it will return the existing database.
Syntax
Basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME
Example
If you want to use a database with name <mydb>, then use DATABASE statement would be as
follows −
>use mydb
switched to db mydb
To check your currently selected database, use the command db
>db
mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert at
least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
In MongoDB default database is test. If you didn't create any database, then collections will be
stored in test database.
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
Basic syntax of dropDatabase() command is as follows −
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete
default 'test' database.
Example
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
If you want to delete new database <mydb>, then dropDatabase() command would be as
follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local 0.78125GB
test 0.23012GB
>

The createCollection() Method


MongoDB db.createCollection(name, options) is used to create collection.
Syntax
Basic syntax of createCollection() command is as follows −
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and is used to
specify configuration of collection.
While inserting the document, MongoDB first checks size field of capped collection, then it
checks max field.
Examples
Basic syntax of createCollection() method without options is as follows −
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections.
>show collections
mycollection
system.indexes
The following example shows the syntax of createCollection() method with few important
options −
> db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max :
10000 } ){
"ok" : 0,
"errmsg" : "BSON field 'create.autoIndexID' is an unknown field.",
"code" : 40415,
"codeName" : "Location40415"
}
>
In MongoDB, you don't need to create collection. MongoDB creates collection automatically,
when you insert some document.
>db.tutorialspoint.insert({"name" : "tutorialspoint"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
MongoDB - Drop Collection
The drop() Method
MongoDB's db.collection.drop() is used to drop a collection from the database.
Syntax
Basic syntax of drop() command is as follows −
db.COLLECTION_NAME.drop()
Example
First, check the available collections into your database mydb.
>use mydb
switched to db mydb
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
Now drop the collection with the name mycollection.
>db.mycollection.drop()
true
>
Again check the list of collections into database.
>show collections
mycol
system.indexes
tutorialspoint
>
drop() method will return true, if the selected collection is dropped successfully, otherwise it will
return false.
MongoDB - Datatypes
MongoDB supports many datatypes. Some of them are −
● String − This is the most commonly used datatype to store the data. String in
MongoDB must be UTF-8 valid.
● Integer − This type is used to store a numerical value. Integer can be 32 bit or
64 bit depending upon your server.
● Boolean − This type is used to store a boolean (true/ false) value.
● Double − This type is used to store floating point values.
● Min/ Max keys − This type is used to compare a value against the lowest and
highest BSON elements.
● Arrays − This type is used to store arrays or list or multiple values into one key.
● Timestamp − ctimestamp. This can be handy for recording when a document
has been modified or added.
● Object − This datatype is used for embedded documents.
● Null − This type is used to store a Null value.
● Symbol − This datatype is used identically to a string; however, it's generally
reserved for languages that use a specific symbol type.
● Date − This datatype is used to store the current date or time in UNIX time
format. You can specify your own date time by creating object of Date and passing day,
month, year into it.
● Object ID − This datatype is used to store the document’s ID.
● Binary data − This datatype is used to store binary data.
● Code − This datatype is used to store JavaScript code into the document.
● Regular expression − This datatype is used to store regular expression.

MongoDB - Insert Document


The insert() Method
To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.
Syntax
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insert(document)
Example
> db.users.insert({
... _id : ObjectId("507f191e810c19729de860ea"),
... title: "MongoDB Overview",
... description: "MongoDB is no sql database",
... by: "tutorials point",
... url: "http://www.tutorialspoint.com",
... tags: ['mongodb', 'database', 'NoSQL'],
... likes: 100
... })
WriteResult({ "nInserted" : 1 })
>
Here mycol is our collection name, as created in the previous chapter. If the collection doesn't
exist in the database, then MongoDB will create this collection and then insert a document into it.
In the inserted document, if we don't specify the _id parameter, then MongoDB assigns a unique
ObjectId for this document.
_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are
divided as follows −
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
You can also pass an array of documents into the insert() method as shown below:.
> db.createCollection("post")
> db.post.insert([
{
title: "MongoDB Overview",
description: "MongoDB is no SQL database",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
title: "NoSQL Database",
description: "NoSQL database doesn't have tables",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 20,
comments: [
{
user:"user1",
message: "My first comment",
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
To insert the document you can use db.post.save(document) also. If you don't specify _id in the
document then save() method will work same as insert() method. If you specify _id then it will
replace whole data of document containing _id as specified in save() method.

The insertOne() method


If you need to insert only one document into a collection you can use this method.
Syntax
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insertOne(document)
Example
Following example creates a new collection named empDetails and inserts a document using the
insertOne() method.
> db.createCollection("empDetails")
{ "ok" : 1 }

> db.empDetails.insertOne(
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "[email protected]",
phone: "9848022338"
})
{
"acknowledged" : true,
"insertedId" : ObjectId("5dd62b4070fb13eec3963bea")
}
>

The insertMany() method


You can insert multiple documents using the insertMany() method. To this method you need to
pass an array of documents.
Example
Following example inserts three different documents into the empDetails collection using the
insertMany() method.
> db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "[email protected]",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Date_Of_Birth: "1990-02-16",
e_mail: "[email protected]",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Date_Of_Birth: "1990-02-16",
e_mail: "[email protected]",
phone: "9000054321"
}
]
)
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5dd631f270fb13eec3963bed"),
ObjectId("5dd631f270fb13eec3963bee"),
ObjectId("5dd631f270fb13eec3963bef")
]
}
>
MongoDB - Query Document
The find() Method
To query data from MongoDB collection, you need to use MongoDB's find() method.
Syntax
The basic syntax of find() method is as follows −
>db.COLLECTION_NAME.find()
find() method will display all the documents in a non-structured way.
Example
Assume we have created a collection named mycol as −
> use sampleDB
switched to db sampleDB
> db.createCollection("mycol")
{ "ok" : 1 }
>
And inserted 3 documents in it using the insert() method as shown below −
> db.mycol.insert([
{
title: "MongoDB Overview",
description: "MongoDB is no SQL database",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
title: "NoSQL Database",
description: "NoSQL database doesn't have tables",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 20,
comments: [
{
user:"user1",
message: "My first comment",
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
Following method retrieves all the documents in the collection −
> db.mycol.find()
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://
www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "description" :
"NoSQL database doesn't have tables", "by" : "tutorials point", "url" : "http://
www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20,
"comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" :
ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
>

Node.js MongoDB Update


Update Document
You can update a record, or document as it is called in MongoDB, by using the
updateOne()method.
The first parameter of the updateOne() method is a query object defining which document to
update.
Note: If the query finds more than one record, only the first occurrence is updated.
The second parameter is an object defining the new values of the document.
Example
Get your own Node.js Server
Update the document with the address "Valley 345" to name="Mickey" and address="Canyon
123":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myquery = { address: "Valley 345" };
var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };
dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});
Save the code above in a file called "demo_update_one.js" and run the file:
Run "demo_update_one.js"
C:\Users\Your Name>node demo_update_one.js
Which will give you this result:
1 document updated
Node.js - MongoDB Join
MongoDB is a NoSQL database, and it doesn’t support JOIN operations as found in relation
databases such as MySQL. However, a similar functionality can be achieved by calling the
aggregate() method of the Collection object, and the $lookup stage.

$aggregate() function
This function Performs a left outer join to another collection in the same database to filter in
documents from the "joined" collection for processing.
$lookup: Performs a left outer join to a collection in the same database to filter in documents
from the "joined" collection for processing. The $lookup stage adds a new array field to each
input document. The new array field contains the matching documents from the "joined"
collection.
To perform an equality match between a field from the input documents with a field from the
documents of the "joined" collection, the $lookup stage has this syntax −
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
The parameters in $lookup stage are as follows −
Node.js MongoDB Sorting
In MongoDB, the sort() method is used for sorting the results in ascending or descending order.
The sort() method uses a parameter to define the object sorting order.

● Value used for sorting in ascending order:


● { name: 1 }
● Value used for sorting in descending order:
● { name: -1 }

Sort in Ascending Order


Example
Sort the records in ascending order by the name.
Create a js file named "sortasc.js", having the following code:
● var http = require('http');
● var MongoClient = require('mongodb').MongoClient;
● var url = "mongodb://localhost:27017/ MongoDatabase";
● MongoClient.connect(url, function(err, db) {
● if (err) throw err;
● var mysort = { name: 1 };
● db.collection("employees").find().sort(mysort).toArray(function(err, result) {
● if (err) throw err;
● console.log(result);
● db.close();
● });
● });
Open the command terminal and run the following command:

● Node sortasc.js
Sort in Descending Order
Example
Sort the records in descending order according to name:
Create a js file named "sortdsc.js", having the following code:

● var http = require('http');


● var MongoClient = require('mongodb').MongoClient;
● var url = "mongodb://localhost:27017/ MongoDatabase";
● MongoClient.connect(url, function(err, db) {
● if (err) throw err;
● var mysort = { name: -1 };
● db.collection("employees").find().sort(mysort).toArray(function(err, result) {
● if (err) throw err;
● console.log(result);
● db.close();
● });
● });
Open the command terminal and run the following command:

● Node sortdsc.js

You might also like