Unit 5
Unit 5
NODE JS.
Introduction:
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.
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.
module.exports = detail;
Include your module file in your main application file.
var myLogModule = require('./Local_module.js');
myLogModule.name('Edureka');
myLogModule.domain('Education');
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:
• Deleting 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
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
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.
•
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
• 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
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.