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

Unit 4-JavaBean nodejs mongoDB

JavaBeans are reusable software components in Java that encapsulate multiple objects into a single object, following specific conventions such as having a no-argument constructor and getter/setter methods. They offer advantages like portability, ease of use, and integration, while also having disadvantages such as mutability and boilerplate code. The document also discusses the lifecycle of JavaBeans, types of Enterprise Java Beans (EJB), and their functionalities, including session beans, entity beans, and message-driven beans.

Uploaded by

guptadikshant21
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)
5 views

Unit 4-JavaBean nodejs mongoDB

JavaBeans are reusable software components in Java that encapsulate multiple objects into a single object, following specific conventions such as having a no-argument constructor and getter/setter methods. They offer advantages like portability, ease of use, and integration, while also having disadvantages such as mutability and boilerplate code. The document also discusses the lifecycle of JavaBeans, types of Enterprise Java Beans (EJB), and their functionalities, including session beans, entity beans, and message-driven beans.

Uploaded by

guptadikshant21
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/ 98

JavaBean

In any programming language, reusability is the main concern. To achieve the same concern, Java
introduced the concept of JavaBean. It is a software component that has been designed to be
reusable in a variety of environments. In this section, we will dive into the topic and understand the
horizons of concept in this what is JavaBeans, its advantages, disadvantages, Life cycle.

In other words, JavaBeans are classes that encapsulate multiple objects into a single object. It also
helps in accessing these object from multiple places. It contains several elements like Constructors,
getter and setter methods and much more.

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

o Class Definition: They are defined as public classes.

o Serializability (Optional): While not mandatory, they often implement the Serializable
interface to allow object data to be converted into a stream of bytes for storage or
transmission.

o No-argument Constructor: JavaBeans must have a public constructor that takes no


arguments (often called a no-arg constructor). It simplifies object creation.

o Data Encapsulation: They encapsulate data using private member variables (fields) to store
the object's state.

o Getter and Setter Methods: For each private field, there should be a corresponding public
getter and setter method:

o Getter methods (usually prefixed with get or is for booleans) retrieve the value of a
field.

o Setter methods (usually prefixed with set) modify the value of a field.

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.

//Employee.java
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;

File Name: Test.java

public class Test

public static void main(String args[])

Employee e=new Employee();

e.setId(1);

e.setName("Arjun");

System.out.println(e.getId());

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:

Properties of setter Methods

1. It must be public in nature.

2. The return type a should be void.

3. The setter method uses prefix set.

4. It should take some argument.

Properties of getter Methods

1. It must be public in nature.

2. The return type should not be void.

3. The getter method uses prefix get.

4. It does not take any argument.

For Boolean properties getter method name can be prefixed with either "get" or "is". But
recommended to use "is".

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.

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:

o It is portable, compact, and easy.

o The JavaBean properties and methods can be exposed to another application.

o It provides an easiness to reuse the software components.

Disadvantages of JavaBean

The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it cannot take advantages of immutable objects.

o Creating the setter and getter method for each property separately may lead to the
boilerplate code.

Benefits of Using Beans in Java


JavaBeans are a component model in Java, designed to encapsulate many objects into a single object
(the bean). They are serializable, have a zero-argument constructor, and allow access to properties
using getter and setter methods. The JavaBeans model is a standard for developing and using
reusable software components. Here are some of the primary benefits of using JavaBeans:

1. Reusability: JavaBeans are designed with reusability in mind. Once a bean is created, it can
be used across different applications. It allows developers to build upon existing components
rather than starting from scratch, significantly speeding up the development process.

2. Encapsulation: JavaBeans encapsulate many objects into one, hiding the internal complexity
of individual components from other parts of the program. Encapsulation helps in managing
complexity by exposing only necessary parts of the functionality.

3. Ease of Use: It can be manipulated visually in a builder tool. Most IDEs support JavaBeans by
providing features like dragging and dropping beans into applications, which makes it easier
for non-programmers or developers to build applications.

4. Integration and Flexibility: JavaBeans can be integrated into different environments and can
communicate with other components provided these components adhere to the Beans'
conventions. This flexibility also extends to their capability to operate across different
operating systems and platforms.
5. Customization: JavaBeans can be customized easily using property editors and customizers.
It allows other developers and software tools to configure a bean to fit their specific
environment.

6. Persistence: JavaBeans can be made persistent, meaning their state can be saved to and
restored from storage, without the need for the application to understand the beans'
internals. This persistence is facilitated by the Serializable interface.
7. Security: Beans provide a security framework that supports features like signing, constraints,
and role-based authorization, which can be critical for applications that require high security.

8. Interoperability: Since JavaBeans components are written in Java, they are inherently
interoperable with Java applications. However, with appropriate adapters, JavaBeans can
also be made to work with components written in other languages, promoting cross-
platform interaction.

Life Cycle of Java Beans


The life cycle of a JavaBean refers to the various stages it goes through from instantiation to
destruction. Understanding these stages is crucial for effective bean management, especially in
environments where beans are used extensively, such as Java EE or when beans are managed by
containers in frameworks like Spring. Here's a detailed look at the typical life cycle of a JavaBean:

1. Instantiation

The first stage in the life cycle of a JavaBean is instantiation. During this stage, the JavaBean is
created, usually by calling a no-argument constructor. It is a simple creation step where the bean is
allocated memory and its initial state is set up.

2. Customization (Optional)

After a bean is instantiated, it may undergo customization. It involves configuring the bean's
properties and other settings to suit specific needs. Customization typically happens in two ways:
o Design Time: Using tools such as IDEs where beans can be configured using property sheets.

o Runtime: Programmatically setting properties through setter methods or configuration files


(XML, JSON, etc.).

3. Setting Property Values

Once the bean is customized, its properties are set. It is often done through setter methods defined
in the bean.

4. Connection with Other Beans

JavaBeans can be connected to other beans. It can involve setting up event listeners and event
sources, allowing beans to respond to events triggered by other beans.

5. Activation (Optional)

For beans that are serialized and later restored, the activation stage involves restoring the bean from
its serialized state.

6. Introspection

Introspection is a process where the capabilities of a bean are examined dynamically. Tools and
frameworks can inspect a bean to determine its properties, events, and methods.

7. Running

During this stage, the bean is in use and performing its intended tasks. It may handle data processing,
respond to user input, or interact with other components and beans.

8. Passivation (Optional)

In environments where beans are managed (like EJB containers), passivation is a stage where a
bean's state is temporarily stored to free resources.

9. Destruction
The final stage in the lifecycle of a JavaBean is its destruction. Here, the bean is marked for garbage
collection, and any resources it used are released. Before destruction, cleanup methods can be called
to ensure that all resources are freed properly, such as closing database connections or releasing file
handles.

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,
we will discuss all types of EJB in detail.
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:

o Stateless Session Beans

o Stateful Session Beans


o 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.

To improve execution, we may choose a stateless session bean in the event that it has any of these
characteristics.

o The state of the bean has no information or data for a particular client.

o In a private method invocation, the bean performs a generic task for all clients.

o 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:

o The bean's state denotes the alliance between the bean and a particular client.

o The bean needs to hold data about the customer across method invocations.

o The bean interferes between the customer and different segments of the application,
introducing an improved visible to the client.

o 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:

o The state of the bean must be shared across the application.

o A single enterprise bean should be accessed by multiple threads concurrently.

o The application needs an enterprise bean to perform undertakings upon application startup
and shutdown.

o 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:

o Bean-Managed Persistence (BMP)


o 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.

The following two things are required to support the CMP:

o Mapping: It denotes that how to map an entity bean to a resource.

o 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:
o It creates a consumer for the listener. It means that the container
creates QueueReceiver or TopicSubscriber is created by the container.

o MDB is registered with the consumer. It means that at deployment time QueueReceiver,
TopicSubscriber, and its factory are registered by the container.

o The message ACK mode is specified.


The primary function of MDB is to read (receive) or write (send) incoming from a JMS destination.

The working of MDB is as follows:

o 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.

o A JMS session over the JMS connection is opened by the MDB.

o 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.

What is Node.js
Node.js is a cross-platform runtime environment and library for running JavaScript applications
outside the browser. It is used for creating server-side and networking web applications. It is open
source and free to use. It can be downloaded from this link https://nodejs.org/en/

Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used to run real-
time server applications.

The definition given by its official documentation is as follows:

?Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable
network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight
and efficient, perfect for data-intensive real-time applications that run across distributed devices.?

Node.js also provides a rich library of various JavaScript modules to simplify the development of web
applications.

1. Node.js = Runtime Environment + JavaScript Library

Different parts of Node.js

The following diagram specifies some important parts of Node.js:


Features of Node.js

Following is a list of some important features of Node.js that makes it the first choice of software
architects.

1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its library is very
fast in code execution.

2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are asynchronous i.e. non-
blocking. So a Node.js based server never waits for an API to return data. The server moves
to the next API after calling it and a notification mechanism of Events of Node.js helps the
server to get a response from the previous API call. It is also a reason that it is very fast.

3. Single threaded: Node.js follows a single threaded model with event looping.

4. Highly Scalable: Node.js is highly scalable because event mechanism helps the server to
respond in a non-blocking way.

5. No buffering: Node.js cuts down the overall processing time while uploading audio and
video files. Node.js applications never buffer any data. These applications simply output the
data in chunks.

6. Open source: Node.js has an open source community which has produced many excellent
modules to add additional capabilities to Node.js applications.

7. License: Node.js is released under the MIT license.

Install Node.js on Windows


To install and setup an environment for Node.js, you need the following two softwares
available on your computer:
1. Text Editor.

2. Node.js Binary installable

Text Editor:

The text editor is used to type your program. For example: Notepad is used in Windows, vim
or vi can be used on Windows as well as Linux or UNIX. The name and version of the text
editor can be different from operating system to operating system.

The files created with text editor are called source files and contain program source code.
The source files for Node.js programs are typically named with the extension ".js".

The Node.js Runtime:


The source code written in source file is simply JavaScript. It is interpreted and executed by
the Node.js interpreter.

How to download Node.js:

You can download the latest version of Node.js installable archive file from
https://nodejs.org/en/

Node.js console-based Example


File: console_example1.js

1. console.log('Hello JavaTpoint');

Open Node.js command prompt and run the following code:

1. node console_example1.js

Here, console.log() function displays message on console.

Node.js web-based Example


var http = require("http");

http.createServer(function (request, response) {

response.writeHead(200, {'Content-Type': 'text/plain'});

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

}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');

How to start your server:

Go to start menu and click on the Node.js command prompt.

Now command prompt is open:


Set path: Here we have save "main.js" file on the desktop.

So type cd desktop on the command prompt. After that execute the main.js to start the
server as follows:

1. node main.js

Now server is started.

Make a request to Node.js server:

Open http://127.0.0.1:8081/ in any browser. You will see the following result.
Node.js Console
The Node.js console module provides a simple debugging console similar to JavaScript
console mechanism provided by web browsers.

There are three console methods that are used to write any node.js stream:

1. console.log()

2. console.error()

3. console.warn()

Node.js console.log()

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:

1. Example: >10+20-5

2. 25

1. Example2: >10+12 + (5*4)/7


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().

Example:

Node.js Multiline expressions

Node REPL supports multiline expressions like JavaScript. See the following do-while loop
example:

1. var x = 0

2. undefined

3. > do {
4. ... x++;

5. ... console.log("x: " + x);

6. ... } while ( x < 10 );

Node.js Underscore Variable

You can also use underscore _ to get the last result.

Example:

Node.js REPL Commands

Commands Description
It is used to terminate the current
ctrl + c
command.

ctrl + c twice It terminates the node repl.

ctrl + d It terminates the node repl.

It is used to see command history


up/down keys
and modify previous commands.

It specifies the list of current


tab keys
command.

It specifies the list of all


.help
commands.

It is used to exit from multi-line


.break
expressions.

It is used to exit from multi-line


.clear
expressions.

It saves current node repl session


.save filename
to a file.

It is used to load file content in


.load filename
current node repl session.

Node.js Exit REPL

Use ctrl + c command twice to come out of Node.js REPL.


Node.js Package Manager
Node Package Manager provides two main functionalities:

o It provides online repositories for node.js packages/modules which are searchable on


search.nodejs.org

o 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:

1. npm version

Installing Modules using npm

Following is the syntax to install any Node.js module:


1. 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:

1. 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:

1. 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:

1. npm uninstall express


The Node.js module is uninstalled. You can verify by using the following command:

1. 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.


1. npm search express

Node.js Command Line Options

There is a wide variety of command line options in Node.js. These options provide multiple
ways to execute scripts and other helpful run-time options.

Let's see the list of Node.js command line options:

Index Option Description

It is used to print
1. v, --version
node's version.

It is used to print
2. -h, --help node command
line options.

It evaluates the
following argument
as JavaScript. The
3. -e, --eval "script" modules which are
predefined in the
REPL can also be
used in script.
It is identical to -e
4. -p, --print "script" but prints the
result.

Syntax check the


5. -c, --check script without
executing.

It opens the REPL


even if stdin does
6. -i, --interactive
not appear to be a
terminal.

It is used to
preload the
specified module
at startup. It
-r, --require follows require()'s
7.
module module resolution
rules. Module may
be either a path to
a file, or a node
module name.

Silence
8. --no-deprecation deprecation
warnings.

It is used to print
9. --trace-deprecation stack traces for
deprecations.

--throw- It throws errors for


10.
deprecation deprecations.

It silence all
process warnings
11. --no-warnings
(including
deprecations).

12. --trace-warnings It prints stack


traces for process
warnings (including
deprecations).

It prints a stack
trace whenever
synchronous i/o is
13. --trace-sync-io
detected after the
first turn of the
event loop.

Automatically zero-
fills all newly
14. --zero-fill-buffers allocated buffer
and slowbuffer
instances.

It tracks heap
--track-heap- object allocations
15.
objects for heap
snapshots.

It processes V8
profiler output
16. --prof-process generated using
the v8 option --
prof.

It prints V8
17. --V8-options command line
options.

It specifies an
alternative default
tls cipher list.
18. --tls-cipher-list=list (requires node.js to
be built with
crypto support.
(default))

It enables fips-
19. --enable-fips compliant crypto at
startup. (requires
node.js to be built
with ./configure --
openssl-fips)

It forces fips-
compliant crypto
on startup. (cannot
20. --force-fips be disabled from
script code.) (same
requirements as --
enable-fips)

It specifies ICU
data load path.
21. --icu-data-dir=file
(Overrides
node_icu_data)

Node.js Command Line Options Examples


To see the version of the running Node:

Open Node.js command prompt and run command node -v or node --version

For Help:

Use command node ?h or node --help


To evaluate an argument (but not print result):

Use command node -e, --eval "script"

To evaluate an argument and print result also:

Use command node -p "script"

To open REPL even if stdin doesn't appear:

Use command node -i, or node --interactive


Node.js Global Objects
Node.js global objects are global in nature and available in all modules. You don't need to
include these objects in your application; rather they can be used directly. These objects are
modules, functions, strings and object etc. Some of these objects aren't actually in the global
scope but in the module scope.

A list of Node.js global objects are given below:

o __dirname

o __filename

o Console

o Process

o Buffer

o setImmediate(callback[, arg][, ...])

o setInterval(callback, delay[, arg][, ...])

o setTimeout(callback, delay[, arg][, ...])

o clearImmediate(immediateObject)

o clearInterval(intervalObject)

o clearTimeout(timeoutObject)

Node.js __dirname

It is a string. It specifies the name of the directory that currently contains the code.

File: global-example1.js

1. console.log(__dirname);

Open Node.js command prompt and run the following code:

1. node global-example1.js
Node.js __filename

It specifies the filename of the code being executed. This is the resolved absolute path of this
code file. The value inside a module is the path to that module file.

File: global-example2.js

1. console.log(__filename);

Open Node.js command prompt and run the following code:

1. node global-example2.js

Node.js Callbacks
Callback is an asynchronous equivalent for a function. It is called at the completion of each
task. In Node.js, callbacks are generally used. All APIs of Node are written in a way to
supports callbacks. For example: when a function start reading file, it returns the control to
execution environment immediately so that the next instruction can be executed.

In Node.js, once file I/O is complete, it will call the callback function. So there is no blocking
or wait for File I/O. This makes Node.js highly scalable, as it can process high number of
request without waiting for any function to return result.

Blocking Code Example

Follow these steps:

1. Create a text file named input.txt having the following content:

1. Javatpoint is an online platform providing self learning tutorials on

2. different technologies, in a very simple language.

2. Create a JavaScript file named main.js having the following code:


1. var fs = require("fs");

2. var data = fs.readFileSync('input.txt');

3. console.log(data.toString());

4. console.log("Program Ended");

3. Open the Node.js command prompt and execute the following code.

1. node main.js

Non Blocking Code Example


Follow these steps:

1. Create a text file named input.txt having the following content:

1. Javatpoint is an online platform providing self learning tutorials on

2. different technologies, in a very simple language.

2. Create a JavaScript file named main.js having the following code:

1. var fs = require("fs");

2.

3. fs.readFile('input.txt', function (err, data) {

4. if (err) return console.error(err);

5. console.log(data.toString());

6. });

7. console.log("Program Ended");

3. Open the Node.js command prompt and execute the following code.
1. node main.js

Node.js Events

In Node.js applications, Events and Callbacks concepts are used to provide concurrency. As
Node.js applications are single threaded and every API of Node js are asynchronous. So it
uses async function to maintain the concurrency. Node uses observer pattern. Node thread
keeps an event loop and after the completion of any task, it fires the corresponding event
which signals the event listener function to get executed.

Event Driven Programming

Node.js uses event driven programming. It means as soon as Node starts its server, it simply
initiates its variables, declares functions and then simply waits for event to occur. It is the
one of the reason why Node.js is pretty fast compared to other similar technologies.

There is a main loop in the event driven application that listens for events, and then triggers
a callback function when one of those events is detected.
Difference between Events and Callbacks:

Although, Events and Callbacks look similar but the differences lies in the fact that callback
functions are called when an asynchronous function returns its result where as event
handling works on the observer pattern. Whenever an event gets fired, its listener function
starts executing. Node.js has multiple in-built events available through events module and
EventEmitter class which is used to bind events and event listeners.

EventEmitter class to bind event and event listener:

1. // Import events module

2. var events = require('events');

3. // Create an eventEmitter object

4. var eventEmitter = new events.EventEmitter();

To bind event handler with an event:

1. // Bind event and even handler as follows

2. eventEmitter.on('eventName', eventHandler);

To fire an event:

1. // Fire an event

2. eventEmitter.emit('eventName');

Node.js Event Example

File: main.js

1. // Import events module

2. var events = require('events');

3. // Create an eventEmitter object

4. var eventEmitter = new events.EventEmitter();

5.
6. // Create an event handler as follows

7. var connectHandler = function connected() {

8. console.log('connection succesful.');

9.

10. // Fire the data_received event

11. eventEmitter.emit('data_received');

12. }

13.

14. // Bind the connection event with the handler

15. eventEmitter.on('connection', connectHandler);

16. // Bind the data_received event with the anonymous function

17. eventEmitter.on('data_received', function(){

18. console.log('data received succesfully.');

19. });

20. // Fire the connection event

21. eventEmitter.emit('connection');

22. console.log("Program Ended.");

Now, open the Node.js command prompt and run the following code:

1. node main.js
MONGO-DB
Node.js Create Connection with MongoDB

Node.js MongoDB Create Database

To create a database in MongoDB, First create a MongoClient object and specify a connection URL
with the correct ip address and the name of the database which you want to create.

Note: MongoDB will automatically create the database if it does not exist, and make a connection to
it.

Example

Create a folder named "MongoDatabase" as a database. Suppose you create it on Desktop. Create a
js file named "createdatabase.js" within that folder and having the following code:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/MongoDatabase";

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

if (err) throw err;

console.log("Database created!");

db.close();

});

Now open the command terminal and set the path where MongoDatabase exists. Now execute the
following command:

1. Node createdatabase.js

Now database is created.

Node.js MongoDB Create Collection

MongoDB is a NoSQL database so data is stored in collection instead of table. createCollection


method is used to create a collection in MongoDB.

Example

Create a collection named "employees".

Create a js file named "employees.js", having the following data:


1. var MongoClient = require('mongodb').MongoClient;

2. var url = "mongodb://localhost:27017/ MongoDatabase";

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

4. if (err) throw err;

5. db.createCollection("employees", function(err, res) {

6. if (err) throw err;

7. console.log("Collection is created!");

8. db.close();

9. });

10. });

Open the command terminal and run the following command:

1. Node employees.js

Node.js MongoDB Insert Record

The insertOne method is used to insert record in MongoDB's collection. The first argument of the
insertOne method is an object which contains the name and value of each field in the record you
want to insert.

Example

(Insert Single record)

Insert a record in "employees" collection.

Create a js file named "insert.js", having the following code:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/ MongoDatabase";

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

if (err) throw err;

var myobj = { name: "Ajeet Kumar", age: "28", address: "Delhi" };

db.collection("employees").insertOne(myobj, function(err, res) {

if (err) throw err;

console.log("1 record inserted");

db.close();
});

});

Open the command terminal and run the following command:

1. Node insert.js

Now a record is inserted in the collection.

Insert Multiple Records

You can insert multiple records in a collection by using insert() method. The insert() method uses
array of objects which contain the data you want to insert.

Example

Insert multiple records in the collection named "employees".

Create a js file name insertall.js, having the following code:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/ MongoDatabase";

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

if (err) throw err;

var myobj = [

{ name: "Mahesh Sharma", age: "25", address: "Ghaziabad"},

{ name: "Tom Moody", age: "31", address: "CA"},

{ name: "Zahira Wasim", age: "19", address: "Islamabad"},

{ name: "Juck Ross", age: "45", address: "London"}

];

db.collection("customers").insert(myobj, function(err, res) {

if (err) throw err;

console.log("Number of records inserted: " + res.insertedCount);

db.close();

});

});

Open the command terminal and run the following command:


1. Node insertall.js

You can see here 4 records are inserted.

Node.js MongoDB Select Record

The findOne() method is used to select a single data from a collection in MongoDB. This method
returns the first record of the collection.

Example

(Select Single Record)

Select the first record from the ?employees? collection.

Create a js file named "select.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;

db.collection("employees").findOne({}, function(err, result) {

if (err) throw err;

console.log(result.name);

db.close();

});

});

Open the command terminal and run the following command:

1. Node select.js

Select Multiple Records

The find() method is used to select all the records from collection in MongoDB.

Example
Select all the records from "employees" collection.

Create a js file named "selectall.js", having the following code:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/MongoDatabase";

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

if (err) throw err;

db.collection("employees").find({}).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Open the command terminal and run the following command:

1. Node selectall.js

You can see that all records are retrieved.

Node.js MongoDB Filter Query

The find() method is also used to filter the result on a specific parameter. You can filter the result by
using a query object.

Example

Filter the records to retrieve the specific employee whose address is "Delhi".
Create a js file named "query1.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 query = { address: "Delhi" };

db.collection("employees").find(query).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Open the command terminal and run the following command:

1. Node query1.js

Node.js MongoDB Filter With Regular Expression

You can also use regular expression to find exactly what you want to search. Regular expressions can
be used only to query strings.

Example

Retrieve the record from the collection where address start with letter "L".

Create a js file named "query2", 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 query = { address: /^L/ };


db.collection("employees").find(query).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Open the command terminal and run the following command:

1. Node query2.js

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.

1. Value used for sorting in ascending order:

2. { name: 1 }

3. Value used for sorting in descending order:

4. { 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:

1. 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:

1. Node sortdsc.js

Node.js MongoDB Remove

In MongoDB, you can delete records or documents by using the remove() method. The first
parameter of the remove() method is a query object which specifies the document to delete.

Example

Remove the record of employee whose address is Ghaziabad.

Create a js file named "remove.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 myquery = { address: 'Ghaziabad' };


db.collection("employees").remove(myquery, function(err, obj) {

if (err) throw err;

console.log(obj.result.n + " record(s) deleted");

db.close();

});

});

Open the command terminal and run the following command:

1. Node remove.js

Verification

You can check that the record having address "Ghaziabad" is deleted and only following records are
available now:

JavaBean
In any programming language, reusability is the main concern. To achieve the same concern, Java
introduced the concept of JavaBean. It is a software component that has been designed to be
reusable in a variety of environments. In this section, we will dive into the topic and understand the
horizons of concept in this what is JavaBeans, its advantages, disadvantages, Life cycle.
In other words, JavaBeans are classes that encapsulate multiple objects into a single object. It also
helps in accessing these object from multiple places. It contains several elements like Constructors,
getter and setter methods and much more.

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

o Class Definition: They are defined as public classes.

o Serializability (Optional): While not mandatory, they often implement the Serializable
interface to allow object data to be converted into a stream of bytes for storage or
transmission.

o No-argument Constructor: JavaBeans must have a public constructor that takes no


arguments (often called a no-arg constructor). It simplifies object creation.

o Data Encapsulation: They encapsulate data using private member variables (fields) to store
the object's state.

o Getter and Setter Methods: For each private field, there should be a corresponding public
getter and setter method:

o Getter methods (usually prefixed with get or is for booleans) retrieve the value of a
field.

o Setter methods (usually prefixed with set) modify the value of a field.

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.

//Employee.java
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;

File Name: Test.java

public class Test

public static void main(String args[])

Employee e=new Employee();

e.setId(1);

e.setName("Arjun");

System.out.println(e.getId());

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:

Properties of setter Methods

5. It must be public in nature.

6. The return type a should be void.


7. The setter method uses prefix set.

8. It should take some argument.

Properties of getter Methods

5. It must be public in nature.

6. The return type should not be void.

7. The getter method uses prefix get.

8. It does not take any argument.

For Boolean properties getter method name can be prefixed with either "get" or "is". But
recommended to use "is".

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.

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:

o It is portable, compact, and easy.

o The JavaBean properties and methods can be exposed to another application.

o It provides an easiness to reuse the software components.

Disadvantages of JavaBean

The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it cannot take advantages of immutable objects.

o Creating the setter and getter method for each property separately may lead to the
boilerplate code.

Benefits of Using Beans in Java


JavaBeans are a component model in Java, designed to encapsulate many objects into a single object
(the bean). They are serializable, have a zero-argument constructor, and allow access to properties
using getter and setter methods. The JavaBeans model is a standard for developing and using
reusable software components. Here are some of the primary benefits of using JavaBeans:

9. Reusability: JavaBeans are designed with reusability in mind. Once a bean is created, it can
be used across different applications. It allows developers to build upon existing components
rather than starting from scratch, significantly speeding up the development process.
10. Encapsulation: JavaBeans encapsulate many objects into one, hiding the internal complexity
of individual components from other parts of the program. Encapsulation helps in managing
complexity by exposing only necessary parts of the functionality.

11. Ease of Use: It can be manipulated visually in a builder tool. Most IDEs support JavaBeans by
providing features like dragging and dropping beans into applications, which makes it easier
for non-programmers or developers to build applications.

12. Integration and Flexibility: JavaBeans can be integrated into different environments and can
communicate with other components provided these components adhere to the Beans'
conventions. This flexibility also extends to their capability to operate across different
operating systems and platforms.

13. Customization: JavaBeans can be customized easily using property editors and customizers.
It allows other developers and software tools to configure a bean to fit their specific
environment.

14. Persistence: JavaBeans can be made persistent, meaning their state can be saved to and
restored from storage, without the need for the application to understand the beans'
internals. This persistence is facilitated by the Serializable interface.

15. Security: Beans provide a security framework that supports features like signing, constraints,
and role-based authorization, which can be critical for applications that require high security.

16. Interoperability: Since JavaBeans components are written in Java, they are inherently
interoperable with Java applications. However, with appropriate adapters, JavaBeans can
also be made to work with components written in other languages, promoting cross-
platform interaction.

Life Cycle of Java Beans


The life cycle of a JavaBean refers to the various stages it goes through from instantiation to
destruction. Understanding these stages is crucial for effective bean management, especially in
environments where beans are used extensively, such as Java EE or when beans are managed by
containers in frameworks like Spring. Here's a detailed look at the typical life cycle of a JavaBean:

1. Instantiation
The first stage in the life cycle of a JavaBean is instantiation. During this stage, the JavaBean is
created, usually by calling a no-argument constructor. It is a simple creation step where the bean is
allocated memory and its initial state is set up.

2. Customization (Optional)

After a bean is instantiated, it may undergo customization. It involves configuring the bean's
properties and other settings to suit specific needs. Customization typically happens in two ways:

o Design Time: Using tools such as IDEs where beans can be configured using property sheets.
o Runtime: Programmatically setting properties through setter methods or configuration files
(XML, JSON, etc.).

3. Setting Property Values


Once the bean is customized, its properties are set. It is often done through setter methods defined
in the bean.

4. Connection with Other Beans

JavaBeans can be connected to other beans. It can involve setting up event listeners and event
sources, allowing beans to respond to events triggered by other beans.

5. Activation (Optional)

For beans that are serialized and later restored, the activation stage involves restoring the bean from
its serialized state.

6. Introspection
Introspection is a process where the capabilities of a bean are examined dynamically. Tools and
frameworks can inspect a bean to determine its properties, events, and methods.

7. Running

During this stage, the bean is in use and performing its intended tasks. It may handle data processing,
respond to user input, or interact with other components and beans.

8. Passivation (Optional)

In environments where beans are managed (like EJB containers), passivation is a stage where a
bean's state is temporarily stored to free resources.

9. Destruction

The final stage in the lifecycle of a JavaBean is its destruction. Here, the bean is marked for garbage
collection, and any resources it used are released. Before destruction, cleanup methods can be called
to ensure that all resources are freed properly, such as closing database connections or releasing file
handles.

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,
we will discuss all types of EJB in detail.
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:

o Stateless Session Beans

o Stateful Session Beans


o 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.

To improve execution, we may choose a stateless session bean in the event that it has any of these
characteristics.

o The state of the bean has no information or data for a particular client.

o In a private method invocation, the bean performs a generic task for all clients.

o 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:

o The bean's state denotes the alliance between the bean and a particular client.

o The bean needs to hold data about the customer across method invocations.

o The bean interferes between the customer and different segments of the application,
introducing an improved visible to the client.

o 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:

o The state of the bean must be shared across the application.

o A single enterprise bean should be accessed by multiple threads concurrently.

o The application needs an enterprise bean to perform undertakings upon application startup
and shutdown.

o 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:

o Bean-Managed Persistence (BMP)


o 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.

The following two things are required to support the CMP:

o Mapping: It denotes that how to map an entity bean to a resource.

o 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:
o It creates a consumer for the listener. It means that the container
creates QueueReceiver or TopicSubscriber is created by the container.

o MDB is registered with the consumer. It means that at deployment time QueueReceiver,
TopicSubscriber, and its factory are registered by the container.

o The message ACK mode is specified.


The primary function of MDB is to read (receive) or write (send) incoming from a JMS destination.

The working of MDB is as follows:

o 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.

o A JMS session over the JMS connection is opened by the MDB.

o 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.

What is Node.js
Node.js is a cross-platform runtime environment and library for running JavaScript applications
outside the browser. It is used for creating server-side and networking web applications. It is open
source and free to use. It can be downloaded from this link https://nodejs.org/en/

Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used to run real-
time server applications.

The definition given by its official documentation is as follows:

?Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable
network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight
and efficient, perfect for data-intensive real-time applications that run across distributed devices.?

Node.js also provides a rich library of various JavaScript modules to simplify the development of web
applications.

2. Node.js = Runtime Environment + JavaScript Library

Different parts of Node.js

The following diagram specifies some important parts of Node.js:


Features of Node.js

Following is a list of some important features of Node.js that makes it the first choice of software
architects.

8. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its library is very
fast in code execution.

9. I/O is Asynchronous and Event Driven: All APIs of Node.js library are asynchronous i.e. non-
blocking. So a Node.js based server never waits for an API to return data. The server moves
to the next API after calling it and a notification mechanism of Events of Node.js helps the
server to get a response from the previous API call. It is also a reason that it is very fast.

10. Single threaded: Node.js follows a single threaded model with event looping.

11. Highly Scalable: Node.js is highly scalable because event mechanism helps the server to
respond in a non-blocking way.

12. No buffering: Node.js cuts down the overall processing time while uploading audio and
video files. Node.js applications never buffer any data. These applications simply output the
data in chunks.

13. Open source: Node.js has an open source community which has produced many excellent
modules to add additional capabilities to Node.js applications.

14. License: Node.js is released under the MIT license.

Install Node.js on Windows


To install and setup an environment for Node.js, you need the following two softwares
available on your computer:
3. Text Editor.

4. Node.js Binary installable

Text Editor:

The text editor is used to type your program. For example: Notepad is used in Windows, vim
or vi can be used on Windows as well as Linux or UNIX. The name and version of the text
editor can be different from operating system to operating system.

The files created with text editor are called source files and contain program source code.
The source files for Node.js programs are typically named with the extension ".js".

The Node.js Runtime:


The source code written in source file is simply JavaScript. It is interpreted and executed by
the Node.js interpreter.

How to download Node.js:

You can download the latest version of Node.js installable archive file from
https://nodejs.org/en/

Node.js console-based Example


File: console_example1.js

2. console.log('Hello JavaTpoint');

Open Node.js command prompt and run the following code:

2. node console_example1.js

Here, console.log() function displays message on console.

Node.js web-based Example


var http = require("http");

http.createServer(function (request, response) {

response.writeHead(200, {'Content-Type': 'text/plain'});

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

}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');

How to start your server:

Go to start menu and click on the Node.js command prompt.

Now command prompt is open:


Set path: Here we have save "main.js" file on the desktop.

So type cd desktop on the command prompt. After that execute the main.js to start the
server as follows:

2. node main.js

Now server is started.

Make a request to Node.js server:

Open http://127.0.0.1:8081/ in any browser. You will see the following result.
Node.js Console
The Node.js console module provides a simple debugging console similar to JavaScript
console mechanism provided by web browsers.

There are three console methods that are used to write any node.js stream:

4. console.log()

5. console.error()

6. console.warn()

Node.js console.log()

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:

3. Example: >10+20-5

4. 25

2. Example2: >10+12 + (5*4)/7


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().

Example:

Node.js Multiline expressions

Node REPL supports multiline expressions like JavaScript. See the following do-while loop
example:

7. var x = 0

8. undefined

9. > do {
10. ... x++;

11. ... console.log("x: " + x);

12. ... } while ( x < 10 );

Node.js Underscore Variable

You can also use underscore _ to get the last result.

Example:

Node.js REPL Commands

Commands Description
It is used to terminate the current
ctrl + c
command.

ctrl + c twice It terminates the node repl.

ctrl + d It terminates the node repl.

It is used to see command history


up/down keys
and modify previous commands.

It specifies the list of current


tab keys
command.

It specifies the list of all


.help
commands.

It is used to exit from multi-line


.break
expressions.

It is used to exit from multi-line


.clear
expressions.

It saves current node repl session


.save filename
to a file.

It is used to load file content in


.load filename
current node repl session.

Node.js Exit REPL

Use ctrl + c command twice to come out of Node.js REPL.


Node.js Package Manager
Node Package Manager provides two main functionalities:

o It provides online repositories for node.js packages/modules which are searchable on


search.nodejs.org

o 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:

2. npm version

Installing Modules using npm

Following is the syntax to install any Node.js module:


2. 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:

2. 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:

2. 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:

2. npm uninstall express


The Node.js module is uninstalled. You can verify by using the following command:

2. 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.


2. npm search express

Node.js Command Line Options

There is a wide variety of command line options in Node.js. These options provide multiple
ways to execute scripts and other helpful run-time options.

Let's see the list of Node.js command line options:

Index Option Description

It is used to print
1. v, --version
node's version.

It is used to print
2. -h, --help node command
line options.

It evaluates the
following argument
as JavaScript. The
3. -e, --eval "script" modules which are
predefined in the
REPL can also be
used in script.
It is identical to -e
4. -p, --print "script" but prints the
result.

Syntax check the


5. -c, --check script without
executing.

It opens the REPL


even if stdin does
6. -i, --interactive
not appear to be a
terminal.

It is used to
preload the
specified module
at startup. It
-r, --require follows require()'s
7.
module module resolution
rules. Module may
be either a path to
a file, or a node
module name.

Silence
8. --no-deprecation deprecation
warnings.

It is used to print
9. --trace-deprecation stack traces for
deprecations.

--throw- It throws errors for


10.
deprecation deprecations.

It silence all
process warnings
11. --no-warnings
(including
deprecations).

12. --trace-warnings It prints stack


traces for process
warnings (including
deprecations).

It prints a stack
trace whenever
synchronous i/o is
13. --trace-sync-io
detected after the
first turn of the
event loop.

Automatically zero-
fills all newly
14. --zero-fill-buffers allocated buffer
and slowbuffer
instances.

It tracks heap
--track-heap- object allocations
15.
objects for heap
snapshots.

It processes V8
profiler output
16. --prof-process generated using
the v8 option --
prof.

It prints V8
17. --V8-options command line
options.

It specifies an
alternative default
tls cipher list.
18. --tls-cipher-list=list (requires node.js to
be built with
crypto support.
(default))

It enables fips-
19. --enable-fips compliant crypto at
startup. (requires
node.js to be built
with ./configure --
openssl-fips)

It forces fips-
compliant crypto
on startup. (cannot
20. --force-fips be disabled from
script code.) (same
requirements as --
enable-fips)

It specifies ICU
data load path.
21. --icu-data-dir=file
(Overrides
node_icu_data)

Node.js Command Line Options Examples


To see the version of the running Node:

Open Node.js command prompt and run command node -v or node --version

For Help:

Use command node ?h or node --help


To evaluate an argument (but not print result):

Use command node -e, --eval "script"

To evaluate an argument and print result also:

Use command node -p "script"

To open REPL even if stdin doesn't appear:

Use command node -i, or node --interactive


Node.js Global Objects
Node.js global objects are global in nature and available in all modules. You don't need to
include these objects in your application; rather they can be used directly. These objects are
modules, functions, strings and object etc. Some of these objects aren't actually in the global
scope but in the module scope.

A list of Node.js global objects are given below:

o __dirname

o __filename

o Console

o Process

o Buffer

o setImmediate(callback[, arg][, ...])

o setInterval(callback, delay[, arg][, ...])

o setTimeout(callback, delay[, arg][, ...])

o clearImmediate(immediateObject)

o clearInterval(intervalObject)

o clearTimeout(timeoutObject)

Node.js __dirname

It is a string. It specifies the name of the directory that currently contains the code.

File: global-example1.js

2. console.log(__dirname);

Open Node.js command prompt and run the following code:

2. node global-example1.js
Node.js __filename

It specifies the filename of the code being executed. This is the resolved absolute path of this
code file. The value inside a module is the path to that module file.

File: global-example2.js

2. console.log(__filename);

Open Node.js command prompt and run the following code:

2. node global-example2.js

Node.js Callbacks
Callback is an asynchronous equivalent for a function. It is called at the completion of each
task. In Node.js, callbacks are generally used. All APIs of Node are written in a way to
supports callbacks. For example: when a function start reading file, it returns the control to
execution environment immediately so that the next instruction can be executed.

In Node.js, once file I/O is complete, it will call the callback function. So there is no blocking
or wait for File I/O. This makes Node.js highly scalable, as it can process high number of
request without waiting for any function to return result.

Blocking Code Example

Follow these steps:

4. Create a text file named input.txt having the following content:

1. Javatpoint is an online platform providing self learning tutorials on

2. different technologies, in a very simple language.

5. Create a JavaScript file named main.js having the following code:


1. var fs = require("fs");

2. var data = fs.readFileSync('input.txt');

3. console.log(data.toString());

4. console.log("Program Ended");

6. Open the Node.js command prompt and execute the following code.

1. node main.js

Non Blocking Code Example


Follow these steps:

4. Create a text file named input.txt having the following content:

1. Javatpoint is an online platform providing self learning tutorials on

2. different technologies, in a very simple language.

5. Create a JavaScript file named main.js having the following code:

1. var fs = require("fs");

2.

3. fs.readFile('input.txt', function (err, data) {

4. if (err) return console.error(err);

5. console.log(data.toString());

6. });

7. console.log("Program Ended");

6. Open the Node.js command prompt and execute the following code.
1. node main.js

Node.js Events

In Node.js applications, Events and Callbacks concepts are used to provide concurrency. As
Node.js applications are single threaded and every API of Node js are asynchronous. So it
uses async function to maintain the concurrency. Node uses observer pattern. Node thread
keeps an event loop and after the completion of any task, it fires the corresponding event
which signals the event listener function to get executed.

Event Driven Programming

Node.js uses event driven programming. It means as soon as Node starts its server, it simply
initiates its variables, declares functions and then simply waits for event to occur. It is the
one of the reason why Node.js is pretty fast compared to other similar technologies.

There is a main loop in the event driven application that listens for events, and then triggers
a callback function when one of those events is detected.
Difference between Events and Callbacks:

Although, Events and Callbacks look similar but the differences lies in the fact that callback
functions are called when an asynchronous function returns its result where as event
handling works on the observer pattern. Whenever an event gets fired, its listener function
starts executing. Node.js has multiple in-built events available through events module and
EventEmitter class which is used to bind events and event listeners.

EventEmitter class to bind event and event listener:

5. // Import events module

6. var events = require('events');

7. // Create an eventEmitter object

8. var eventEmitter = new events.EventEmitter();

To bind event handler with an event:

3. // Bind event and even handler as follows

4. eventEmitter.on('eventName', eventHandler);

To fire an event:

3. // Fire an event

4. eventEmitter.emit('eventName');

Node.js Event Example

File: main.js

23. // Import events module

24. var events = require('events');

25. // Create an eventEmitter object

26. var eventEmitter = new events.EventEmitter();

27.
28. // Create an event handler as follows

29. var connectHandler = function connected() {

30. console.log('connection succesful.');

31.

32. // Fire the data_received event

33. eventEmitter.emit('data_received');

34. }

35.

36. // Bind the connection event with the handler

37. eventEmitter.on('connection', connectHandler);

38. // Bind the data_received event with the anonymous function

39. eventEmitter.on('data_received', function(){

40. console.log('data received succesfully.');

41. });

42. // Fire the connection event

43. eventEmitter.emit('connection');

44. console.log("Program Ended.");

Now, open the Node.js command prompt and run the following code:

2. node main.js
MONGO-DB
Node.js Create Connection with MongoDB

Node.js MongoDB Create Database

To create a database in MongoDB, First create a MongoClient object and specify a connection URL
with the correct ip address and the name of the database which you want to create.

Note: MongoDB will automatically create the database if it does not exist, and make a connection to
it.

Example

Create a folder named "MongoDatabase" as a database. Suppose you create it on Desktop. Create a
js file named "createdatabase.js" within that folder and having the following code:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/MongoDatabase";

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

if (err) throw err;

console.log("Database created!");

db.close();

});

Now open the command terminal and set the path where MongoDatabase exists. Now execute the
following command:

2. Node createdatabase.js

Now database is created.

Node.js MongoDB Create Collection

MongoDB is a NoSQL database so data is stored in collection instead of table. createCollection


method is used to create a collection in MongoDB.

Example

Create a collection named "employees".

Create a js file named "employees.js", having the following data:


11. var MongoClient = require('mongodb').MongoClient;

12. var url = "mongodb://localhost:27017/ MongoDatabase";

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

14. if (err) throw err;

15. db.createCollection("employees", function(err, res) {

16. if (err) throw err;

17. console.log("Collection is created!");

18. db.close();

19. });

20. });

Open the command terminal and run the following command:

2. Node employees.js

Node.js MongoDB Insert Record

The insertOne method is used to insert record in MongoDB's collection. The first argument of the
insertOne method is an object which contains the name and value of each field in the record you
want to insert.

Example

(Insert Single record)

Insert a record in "employees" collection.

Create a js file named "insert.js", having the following code:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/ MongoDatabase";

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

if (err) throw err;

var myobj = { name: "Ajeet Kumar", age: "28", address: "Delhi" };

db.collection("employees").insertOne(myobj, function(err, res) {

if (err) throw err;

console.log("1 record inserted");

db.close();
});

});

Open the command terminal and run the following command:

2. Node insert.js

Now a record is inserted in the collection.

Insert Multiple Records

You can insert multiple records in a collection by using insert() method. The insert() method uses
array of objects which contain the data you want to insert.

Example

Insert multiple records in the collection named "employees".

Create a js file name insertall.js, having the following code:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/ MongoDatabase";

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

if (err) throw err;

var myobj = [

{ name: "Mahesh Sharma", age: "25", address: "Ghaziabad"},

{ name: "Tom Moody", age: "31", address: "CA"},

{ name: "Zahira Wasim", age: "19", address: "Islamabad"},

{ name: "Juck Ross", age: "45", address: "London"}

];

db.collection("customers").insert(myobj, function(err, res) {

if (err) throw err;

console.log("Number of records inserted: " + res.insertedCount);

db.close();

});

});

Open the command terminal and run the following command:


2. Node insertall.js

You can see here 4 records are inserted.

Node.js MongoDB Select Record

The findOne() method is used to select a single data from a collection in MongoDB. This method
returns the first record of the collection.

Example

(Select Single Record)

Select the first record from the ?employees? collection.

Create a js file named "select.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;

db.collection("employees").findOne({}, function(err, result) {

if (err) throw err;

console.log(result.name);

db.close();

});

});

Open the command terminal and run the following command:

2. Node select.js

Select Multiple Records

The find() method is used to select all the records from collection in MongoDB.

Example
Select all the records from "employees" collection.

Create a js file named "selectall.js", having the following code:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/MongoDatabase";

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

if (err) throw err;

db.collection("employees").find({}).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Open the command terminal and run the following command:

2. Node selectall.js

You can see that all records are retrieved.

Node.js MongoDB Filter Query

The find() method is also used to filter the result on a specific parameter. You can filter the result by
using a query object.

Example

Filter the records to retrieve the specific employee whose address is "Delhi".
Create a js file named "query1.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 query = { address: "Delhi" };

db.collection("employees").find(query).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Open the command terminal and run the following command:

2. Node query1.js

Node.js MongoDB Filter With Regular Expression

You can also use regular expression to find exactly what you want to search. Regular expressions can
be used only to query strings.

Example

Retrieve the record from the collection where address start with letter "L".

Create a js file named "query2", 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 query = { address: /^L/ };


db.collection("employees").find(query).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Open the command terminal and run the following command:

2. Node query2.js

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.

5. Value used for sorting in ascending order:

6. { name: 1 }

7. Value used for sorting in descending order:

8. { 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:

2. 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:

2. Node sortdsc.js

Node.js MongoDB Remove

In MongoDB, you can delete records or documents by using the remove() method. The first
parameter of the remove() method is a query object which specifies the document to delete.

Example

Remove the record of employee whose address is Ghaziabad.

Create a js file named "remove.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 myquery = { address: 'Ghaziabad' };


db.collection("employees").remove(myquery, function(err, obj) {

if (err) throw err;

console.log(obj.result.n + " record(s) deleted");

db.close();

});

});

Open the command terminal and run the following command:

2. Node remove.js

Verification

You can check that the record having address "Ghaziabad" is deleted and only following records are
available now:

You might also like