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

Unit 5

The document provides an introduction to Node.js, describing it as an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. It outlines several key features of Node.js, including its asynchronous and non-blocking nature, large ecosystem of libraries, and use for building scalable backend services like APIs. The document also discusses advantages of Node.js such as easy scalability, use for real-time applications, fast performance, and ease of learning. It provides examples of applications that can be built with Node.js and describes Node.js modules and event-driven programming model.
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)
46 views

Unit 5

The document provides an introduction to Node.js, describing it as an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. It outlines several key features of Node.js, including its asynchronous and non-blocking nature, large ecosystem of libraries, and use for building scalable backend services like APIs. The document also discusses advantages of Node.js such as easy scalability, use for real-time applications, fast performance, and ease of learning. It provides examples of applications that can be built with Node.js and describes Node.js modules and event-driven programming model.
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/ 12

UNIT-5 :

NODE JS.

Introduction:

Node.js is an open-source and cross-platform runtime environment for


executing JavaScript code outside a browser. You need to remember that NodeJS is
not a framework and it’s not a programming language. Most people are confused
and understand it’s a framework or a programming language. We often use Node.js
for building back-end services like APIs like Web App or Mobile App. It’s used in
production by large companies such as Paypal, Uber, Netflix, Walmart, and so on.

Features of NodeJS: There are other programming languages also which we can
use to build back-end services so what makes Node.js different I am going to explain.
1. It’s easy to get started and can be used for prototyping and agile development
2. It provides fast and highly scalable services
3. It uses JavaScript everywhere, so it’s easy for a JavaScript programmer to build
back-end services using Node.js
4. Source code cleaner and consistent.
5. Large ecosystem for open source library.
6. It has Asynchronous or Non-blocking nature.

Advantages of NodeJS: Here are the benefits of using Node.js

1. Easy Scalability: Developers prefer to use Node.js because it is easily scaling


the application in both horizontal and vertical directions. We can also add extra
resources during the scalability of the application.
2. Real-time web apps: If you are building a web app you can also use PHP, and
it will take the same amount of time when you use Node.js, But if I am talking
about building chat apps or gaming apps Node.js is much more preferable
because of faster synchronization. Also, the event loop avoids HTTP
overloaded for Node.js development.
3. Fast Suite: NodeJs runs on the V8 engine developed by Google. Event loop in
NodeJs handles all asynchronous operation so 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
4. Easy to learn and code: NodeJs is easy to learn and code because it uses
JavaScript. If you are a front-end developer and have a good grasp of
JavaScript you can easily learn and build the application on NodeJS
5. 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.
6. Data Streaming: In NodeJs HTTP request and response are considered as
two separate events. They are data stream so when you process a file at the
time of loading it will reduce the overall time and will make it faster when the
data is presented in the form of transmissions. It also allows you to stream audio
and video files at lightning speed.
7. Hosting: PaaS (Platform as a Service) and Heroku are the hosting platforms
for NodeJS application deployment which is easy to use without facing any
issue.
8. Corporate Support: Most of the well-known companies like Walmart, Paypal,
Microsoft, Yahoo are using NodeJS for building the applications. NodeJS uses
JavaScript, so most of the companies are combining front-end and backend
Teams together into a single unit.

Application of NodeJS: NodeJS should be preferred to build:


• Real-Time Chats,
• Complex Single-Page applications,
• Real-time collaboration tools,
• Streaming apps
• JSON APIs based application

NodeJS Event-Driven Programming


As I have already mentioned, Node.js applications are single threaded and event-
driven. Node.js supports concurrency as it is event-driven, and thus makes use of
concepts like events and callbacks. The async function calls help Node.js in
maintaining concurrency throughout the application.
Basically, in a Node.js application, there is a main loop which waits and listens for
events, and once any event is completed, it immediately initiates a callback function.
Below diagram represents how the events are driven in Node.js.

One thing that you must note here is that, even though events look similar to call-back
functions but the difference lies in their functionalities. When an asynchronous function
returns its results call-backs are invoked on the other hand event handling completely
works on the observer pattern. And in Node.js, methods which listen to the events are
called the observers. The moment, an event is triggered, its listener function
automatically starts executing. Event modules and Event Emitter class provide
multiple in-built events which are used to bind events with event listeners. Below I have
written down the syntax for that.
Node.js Modules
The modules in Node.js represents various functionalities that are bundled up into
single or multiple JS files. These modules have a unique context, thus, they never
interfere nor pollute the scope of other modules.
These modules enable the code reusability and enhance the ease of usage. Node.js
basically provides three types of modules:
1. Core Modules
2. Local Modules
3. Third-Party Modules
Core Module
Since Node.js is a very lightweight framework, the core modules bundle the absolute
minimum functionalities. These modules generally get loaded when the Node process
starts its execution. All you need to do is, import these core modules in order to use
them in your code.
Below I have listed down a few of the important Core modules.
Core Module Description
Contains classes, methods, and events required to create
http
Node.js HTTP server
url Contains methods for URL resolution and parsing in Node
querystring Contains methods to deal with a query string of Node
path Contains methods to deal with file paths
fs Contains classes, methods, and events to work with file I/O
util Contains utility functions that can be useful for programmers
You can load your core module, using the below code:
var module = require('module_name');
Lets now see, what are ‘local modules’.
Local Modules
The local modules of Node.js are custom modules that are created locally by
user/developer in the application. These modules can include various functionalities
bundled into distinct files and folders which can be easily distributed in the Node.js
community using NPM.
These modules are loaded in a similar way to core modules. Let show you, how to do
it using a basic example.

Create your custom/local module.js file


var detail = {
name: function (name) {
console.log('Name: ' + name);
},
domain:function (domain) {
console.log('Domain: ' + domain);
}
};

module.exports = detail;
Include your module file in your main application file.
var myLogModule = require('./Local_module.js');
myLogModule.name('Edureka');
myLogModule.domain('Education');

Now you can execute these files using below command:


node application.js
Let me now show you what are external modules.

External Modules
You can use the external or 3rd party modules only by downloading them via NPM.
These modules are generally developed by other developers and are free to use. Few
of the best external modules are express, react, gulp, mongoose, mocha etc.

Workflow of Node js
A web server using Node.js typically has a workflow that is quite similar to the diagram
illustrated below. Let’s explore this flow of operations in detail.

• Clients send requests to the webserver to interact with the web application.
Requests can be non-blocking or blocking:

• Querying for data

• Deleting data

• Updating the data

• Node.js retrieves the incoming requests and adds those to the Event Queue
• The requests are then passed one-by-one through the Event Loop. It checks
if the requests are simple enough not to require any external resources

• The Event Loop processes simple requests (non-blocking operations), such


as I/O Polling, and returns the responses to the corresponding clients

A single thread from the Thread Pool is assigned to a single complex request. This
thread is responsible for completing a particular blocking request by accessing
external resources, such as computation, database, file system, etc.

Once the task is carried out completely, the response is sent to the Event Loop that
sends that response back to the clien

Node.js is an open-source, cross-platform JavaScript runtime environment and library


to run web applications outside the client’s browser. It is used to create server-side
web applications.

Node.js is perfect for data-intensive applications as it uses an asynchronous, event-


driven model. You can use I/O intensive web applications like video streaming sites.
You can also use it for developing: Real-time web applications, Network applications,
General-purpose applications, and Distributed systems.

Test Pyramid

A test pyramid basically is a diagram that describes the ratio of how many unit tests,
integration tests, and end-to-end test are required to be written for the successful
development of the project.
he test pyramid is a way of thinking about how different kinds of automated tests
should be used to create a balanced portfolio. Its essential point is that you should
have many more low-level UnitTests than high level BroadStackTestsrunning through
a GUI. This tests pyramid give you 3 recomendation :
1. Favour unit tests to e2e tests
2. Cover unit tests gaps with integration tests
3. Use end-to-end tests sparingly
• Unit Test : Tests a unit on application without its external dependencies, this
unit test are cheap to write, execute fast, Don’t give a lot confidence.
• Integration Test : Tests the application with its external dependencies were take
longer to execute but give more confidence.

Unit tests vs Integration tests


• End-to-end Test : Drives an application through its UI. In this tests give you the
greatest confidence but its very slow and very brittle

The pyramid attempts to visually represent a logical organization of testing


standards. It consists of three distinct layers:
The base of the pyramid consists of unit tests. A unit is a small logical piece of code:
it can be a function, a class, or even a method in a class. A unit test only checks that
said unit behaves as the developer intended. By calling the tested code directly and
evaluating its output, a developer can write a unit test without depending on any other
components, services, or the UI.At the top of the pyramid we find the end-to-end
tests (E2E). Also known as UI tests, E2E is testing in its most intuitive sense: use the
application and see if it works. But instead of having a human conducting the
tests, E2E tests are entirely automated. Every user interaction is mimicked; an E2E
test can click buttons, type values, and evaluate what the UI is showing.

As you can see, the three types of tests have very different scopes:

1. Unit tests can only find logical errors at the most fundamental level. They are
fast and require very few resources to run.
2. Integration tests verify that services and databases work well together with the
code and the classes you’ve written. They can only find problems at the
interfaces where two or more components meet.
3. E2E tests depend on the complete application being able to start. These are
the most comprehensive type of tests we have and, accordingly, need the most
computing resources and time to run.
So, why a pyramid?

To understand how the pyramid got its shape, we must understand the intricacies of
each type of test.

Unit tests are small and therefore easy to write and maintain. Because they test very
narrow parts of the code, we need plenty of them. This is usually not a problem
because unit tests are light enough that we can run thousands of them in a few
seconds.

E2E tests are at the far end of the spectrum. They are complex to write, difficult to
maintain, need plenty of resources, and are slow to run. But, since we can cover a
lot of the application with a few E2E tests, we need fewer of them.
In the middle, we find integration tests. Complexity-wise, they are on the same page
as unit tests. But we don’t need as many of them since we are only interested in testing
the “edges” of the application. Compared with unit tests, integration tests need more
resources to run but are the same order of magnitude.

Hopefully, you now understand why the pyramid has its shape: the width of each layer
represents the ideal relative quantity for each kind of test. In other words, the pyramid
says we must have a few end-to-end tests, a decent amount of integration tests, and
a swarm of unit tests.

As you work up the pyramid, tests get more complex and cover a more significant
portion of the codebase. At the same time, the effort of writing, running and maintaining
them increases. The pyramid illustrates an ideal ratio that maximizes the chance of
finding a bug with the least work.
A second factor that shapes the pyramid is speed. The faster the test suite is, the more
often developers run it. Slow tests hurt the vital feedback loop needed for a productive
environment.

Tests at the bottom of the pyramid are the fastest. So developers tend to write more
of them. Conversely, E2E tests are slow and thus used more sparingly. As a result, a
large web app can have thousands of unit tests, hundreds of integration tests, and a
few dozen E2E tests.

The testing pyramid is the most widely-known format of designing automated tests.

Node.js REPL

Node.js Read-Eval-Print-Loop (REPL) is an easy-to-use command-line tool, used for


processing Node.js expressions. It captures the user’s JavaScript code inputs,
interprets, and evaluates the result of this code. It displays the result to the screen,
and repeats the process till the user quits the shell.
It is also important to note that this tool does not require file creation to write code.
REPL comes ready to use with the Node.js development environment.

A REPL has the following:

• A read function, which accepts an expression from the user and parses it into
a data structure in memory.
• An eval function, which takes the data structure and evaluates the expression.
• A print function, which prints the result.
• A loop function, which runs the three commands above until termination

In this tutorial, we will learn the basics of Node.js REPL and how we can use this
amazing tool to run scripts without creating .js files.

Imp: Below is the list of the tasks which must be done asynchronously using the
event loop:

• I/O operations
• Heavy computation
• Anything requiring blocking

Node.js Timer Module

The Timers module in Node.js contains various functions that allow us to execute a
block of code or a function after a set period of time. The Timers module is global,
we do not need to use require() to import it.
Timers module has the following functions:
1. Scheduling Timers: It is used to call a function after a set period of time.
• setImmediate()
• setInterval()
• setTimeout()
2. Cancelling Timers: It is used to cancel the scheduled timer.
• clearImmediate()
• clearInterval()
• clearTimeout()
1. setImmediate() method: It schedules the “immediate” execution of the
callback after I/O events callbacks. In the following example, multiple
setImmediate functions are called. Whenever we do these callback functions
are queued for execution in the order in which they are created. The entire
callback queue is processed after every event loop iteration. If an immediate
timer is queued from inside an executing callback, that timer will not be
triggered until the next event loop iteration.

2. setInterval() method: It repeats the execution of the callback after every t


time in milliseconds passed as a parameter.
3. setTimeout() method: It schedules the execution of the callback after a
certain time in milliseconds which is passed as a parameter.

4. clearImmediate() method: It is used to simply cancel the Immediate object


created by setImmediate() method.

In Node.js, process.nextTick() and setImmediate(), both are functions of the Timers


module which help in executing the code after a predefined period of time. But these
functions differ in their execution. The process.nextTick function waits for the
execution of action till the next pass around in the event loop or once the event loop
is completed only then it will invoke the callback function. On the other hand,
setImmediate() is used to execute a callback method on the next cycle of the event
loop which eventually returns it to the event loop in order to execute the I/O operations.

You might also like