Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

Module 4

Node.JS
What is Node.js?

• Node.js is a server-side platform built on Google Chrome's JavaScript


Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009
and its latest version is v0.10.36.
• 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 is an open source, cross-platform runtime environment for
developing server-side and networking applications.

Node.js applications are written in JavaScript, and can be run within the
Node.js runtime on OS X, Microsoft Windows, and Linux.
Node.js also provides a rich library of various JavaScript modules
which simplifies the development of web applications using Node.js to
a great extent.

Node.js = Runtime Environment + JavaScript Library


Features of Node.js
• Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It

essentially means 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.

• Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in cAode

execution.

• Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event

mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed

to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program

and the same program can provide service to a much larger number of requests than traditional servers like

Apache HTTP Server.


• No Buffering − Node.js applications never buffer any data. These
applications simply output the data in chunks.
• License − Node.js is released under the MIT license.
Where to Use Node.js?

Following are the areas where Node.js is proving itself as a perfect


technology partner.
• I/O bound Applications
• Data Streaming Applications
• Data Intensive Real-time Applications (DIRT)
• JSON APIs based Applications
• Single Page Applications
• A Node.js application consists of the following three important
components −
• Import required modules − We use the require directive to load
Node.js modules.
• Create server − A server which will listen to client's requests similar
to Apache HTTP Server.
• Read request and return response − The server created in an earlier
step will read the HTTP request made by the client which can be a
browser or a console and return the response.
Creating Node.js Application

• Step 1 - Import Required Module


var http=require(“http”);
• Step 2 - Create Server
We use the created http instance and call http.createServer() method to create a
server instance and then we bind it at port 8081 using the listen method associated
with the server instance. Pass it a function with parameters request and response.
• Step 3 - Testing Request & Response
Let's put step 1 and 2 together in a file called app.js and start our HTTP server

$ node app.js
Asynchronous Programming

• In Asynchronous programming, one function does not block the execution of


another function. It means it is a way of writing the program so that multiple
functions can run at a time.

• The function that takes less time will execute first than the function that takes more
time. The faster function does not have to wait for the completion of the slower
function which appears before it sequentially. This makes the overall execution
faster and non-blocking and gives the power to perform multiple tasks at once.
How to do Asynchronous Programming in Node.js?

• In Node.js, doing asynchronous programming is straightforward and easy. Whenever you use any of its modules,
you will find that each module has both synchronous and asynchronous methods.

• Always try to choose an asynchronous method because of its non-blocking nature, which increases
performance and speed.

• If an asynchronous method does not exist for the operation you want to perform then you can use third-party
modules to help you accomplish different types of tasks asynchronously.

• There are some techniques for asynchronous programming in Node.js that you will need to use with asynchronous
methods for control flow.

• There are three main techniques for asynchronous programming in Node.js: callback, promises, and async/await.
What is Callback?
• Callback is an asynchronous equivalent for a function. A callback function is
called at the completion of a given task. Node makes heavy use of callbacks. All
the APIs of Node are written in such a way that they support callbacks.

• For example, a function to read a file may start reading file and return the control
to the execution environment immediately so that the next instruction can be
executed. Once file I/O is complete, it will call the callback function while passing
the callback function, the content of the file as a parameter. So there is no blocking
or wait for File I/O. This makes Node.js highly scalable, as it can process a high
number of requests without waiting for any function to return results.
Blocking Code Example
Non-Blocking Code Example
These two examples explain the concept of blocking and non-blocking calls.

• The first example shows that the program blocks until it reads the file and then only it proceeds to

end the program.

• The second example shows that the program does not wait for file reading and proceeds to print

"Program Ended" and at the same time, the program without blocking continues reading the file.

Thus, a blocking program executes very much in sequence. From the programming point of view, it is
easier to implement the logic but non-blocking programs do not execute in sequence.
Event Loop
What is the Event Loop?
The event loop is what allows Node.js to perform non-blocking I/O
operations — despite the fact that JavaScript is single-threaded — by
offloading operations to the system kernel whenever possible.
When Node.js starts, it initializes the event loop, processes the provided
input script
• The following diagram shows a simplified overview of the event loop's
order of operations.
• Each phase has a FIFO queue of callbacks to execute. While each
phase is special in its own way, generally, when the event loop enters a
given phase, it will perform any operations specific to that phase, then
execute callbacks in that phase's queue until the queue has been
exhausted or the maximum number of callbacks has executed. When
the queue has been exhausted or the callback limit is reached, the
event loop will move to the next phase, and so on.
• Since any of these operations may schedule more operations and new
events processed in the poll phase are queued by the kernel, poll
events can be queued while polling events are being processed.
Phases Overview
How to use the Node.js REPL
REPL stands for Read Eval Print Loop and it represents a computer environment like a Windows
console or Unix/Linux shell where a command is entered and the system responds with an output
in an interactive mode. Node.js or Node comes bundled with a REPL environment. It performs the
following tasks:

• Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory.

• Eval − Takes and evaluates the data structure.

• Print − Prints the result.

• Loop − Loops the above command until the user presses ctrl-c twice.
Starting REPL
REPL can be started by simply running node on shell/console without any
arguments as follows.
$ node

You will see the REPL Command prompt > where you can type any Node.js command

$ node
>
Simple Expression

A simple mathematics at the Node.js REPL command prompt −


$ node
> 1 + 5
6
> 2 + (3*3)-7
4
>
• Use Variables

If var keyword is not used, then the value is stored in the variable and printed. Whereas

if var keyword is used, then the value is stored but not printed. You can print variables

using console.log().
$ node
> x = 20
20
> var y = 30
undefined
> x + y
50
> console.log("Node js")
Node js
undefined
Multiline Expression
$ node
> var i = 0
undefined
> do {
... i++;
... console.log("i: " + i);
... }
while ( i < 5 );
i: 1
i: 2
i: 3
i: 4
i: 5
undefined
>
Underscore Variable
Use of underscore (_) to get the last result −
$ node
> var x = 60
undefined
> var y = 30
undefined
>x+y
90
> var sum = _
undefined
> console.log(sum)
90
undefined
>
Stopping REPL
As mentioned above, you will need to use ctrl-c twice to come out of
Node.js REPL.
EventEmitter
Node.js allows us to create and handle custom events
easily by using events module. Event module includes
EventEmitter class which can be used to raise and handle
custom events.
The emit() function raises the specified event. First
parameter is name of the event as a string and then
arguments. An event can be emitted with zero or more
arguments. You can specify any name for a custom event
in the emit() function.
// get the reference of EventEmitter class of events module
var events = require('events');

//create an object of EventEmitter class by using above reference


var em = new events.EventEmitter();

em.on('FirstEvent', function (data) {


console.log('Welcome to NodeJs: ' + data);
});

// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
• Multiple callbacks can be registered against that same event.
Node.js Net Module

• The Net module provides a way of creating TCP servers and TCP
clients.
Modules are the blocks of encapsulated code that communicate with
an external application on the basis of their related functionality.
Modules can be a single file or a collection of multiple files/folders. The
reason programmers are heavily reliant on modules is because of their
reusability as well as the ability to break down a complex piece of code
into manageable chunks.
Modules are of three types:
• Core Modules
• local Modules
• Third-party Modules
const module = require('module_name');

• Core Modules: Node.js has many built-in modules that are part of the
platform and come with Node.js installation. These modules can be
loaded into the program by using the required function.
• Local Modules: Unlike built-in and external modules, local modules
are created locally in your Node.js application. Let’s create a simple
calculating module that calculates various operations.
Filename: calc.js
const calculator = require('./calc');
exports.add = function (x, y) {
return x + y; let x = 50, y = 10;
};
console.log("Addition of 50 and 10 is "
exports.sub = function (x, y) {
+ calculator.add(x, y));
return x - y;
}; console.log("Subtraction of 50 and 10 is "
exports.mult = function (x, y) { + calculator.sub(x, y));

return x * y; console.log("Multiplication of 50 and 10 is "


}; + calculator.mult(x, y));
exports.div = function (x, y) {
console.log("Division of 50 and 10 is "
return x / y; + calculator.div(x, y));
};
Third-party modules: Third-party modules are modules that are
available online using the Node Package Manager(NPM). These
modules can be installed in the project folder or globally. Some of the
popular third-party modules are Mongoose, express, angular, and
React.
Example:
npm install express
npm install mongoose
npm install -g @angular/cli
Buffer concept

A buffer is a space in memory (usually RAM) that temporarily stores binary data. The purpose of this
space is to help any running entity not lose data during a transfer using a FIFO system.

Buffer in Nodejs

In Nodejs we can manipulate these memory spaces with the module called Buffer built into its core.
Buffers are widely used when working with binary data at the network level. The Nodejs modules and
functionalities work implicitly based on events and manipulation of Buffer / Streams, such as the
core File System or HTTP modules that store the temporary data flow in a Buffer.

Here are some important features of Buffers:

• Buffers are stored in a sequence of integers.

• Once created they cannot be resized.


• Stream concept
• They are information flows that are used in the transmission of binary
data. They are also a way to handle network communications or any
kind of back-and-forth data exchange efficiently, by breaking
information down into smaller pieces.
• Here are some important features of Streams:
• Streams work sequentially.
• The information is transmitted through “chunks” (pieces).
• Streams rely on buffers to manage content.
• Stream in Nodejs
• Nodejs has a module called stream that helps us with the manipulation of
these flows, but depending on the case we will use some type of stream.
• In general, there are 4 types of Streams in Nodejs:
1.Writable: Streams in which we can write data.
2.Readable: Streams receiving input data.
3.Duplex: Streams that are both read and written.
4.Transform: Streams that can modify or transform data as it is written
and read.
• Buffer and Stream handling are the most powerful core features of
Nodejs. Input and output operations are optimized under easy-to-
process pipelined sequences, helping the system consume large
amounts of information without risking processing.
Node.js – web module
• Web server is a software application which processes request using
HTTP protocol and returns web pages as response to the clients.
• Web server usually delivers html documents along with images, style
sheets and scripts.
• Most web server also support server side scripts using scripting
language or redirect to application server which perform the specific
task of getting data from database, perform complex logic etc. Web
server then returns the output of the application server to client.
• Apache web server is one of the most common web server being
used. It is an open source project.
Web server and Path
• Web server maps the path of a file using URL, Uniform Resource
Locator. It can be a local file system or a external/internal program.
• A client makes a request using browser, URL:
http://www.abc.com/dir/index.html
• Browser will make request as:

GET /dir/index.html HTTP/1.1


HOST www.abc.com
Web Architecture
• Web application are normally divided into four layers:
• Client: this layer consists of web browsers, mobile browsers or applications
which can make HTTP request to server.
• Server: this layer consists of Web Server which can intercepts the request
made by clients and pass them the response.
• Business: this layer consists of application server which is utilized by web
server to do dynamic tasks. This layer interacts with data layer via database or
some external programs.
• Data: this layer consists of databases or any source of data.
Creating Web Server using Node
• Create an HTTP server using http.createServer method. Pass it a
function with parameters request and response.
• Write the sample implementation to return a requested page.
• Pass a port 8081 to listen method.
• wk4_01_http_server.js
• wk4_01_test.html
• wk4_01_http_client.js

You might also like