SlideShare a Scribd company logo
NODEJS BASICS
• Node.Js is an open-source runtime environment for javascript. It is built
on chrome’s V8 javascript engine. Node.Js can run on different platforms
 linux,
 windows
 macos, and
 mobile platforms
• It is agnostic of the underlying OS. It allows programs written in javascrip
to be executed on the server. Node.Js is also a part of the famous MEAN
and MERN stack.
• And according to stackoverflow’s developer survey, node.Js is the 6th
most popular technology among programmers.Besides the javascript
knowledge, understanding of databases, familiarity with html5, css3, and
restful api will be greatly advantageous while working with node.Js.
• The primary advantage of using node.js is that you can use javascript
in both frontend and backend. And it’s easier to keep them in sync
because a single language is used on both sides of applications.
• Due to its event-based nature, Node.js is highly efficient for real-time
applications that demand continual data updates. Moreover, the non-
blocking input-output model helps to solve the performance issues.
• Node.js is widely used to make scalable and lightweight web
applications.
• Node.js is renowned for its massive community which continuously
contributes to its improvement.
• Due to node modules, it became easier for developers to use prebuild
modules and reuse code.
WHY NODE.JS?
FEATURES OF NODE.JS
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.
• The webserver can run directly on the Node.js platform as a Node.js module, which means
it’s much easier than using, say, Apache for wiring up new services or server-side scripts.
• The following are just a few reasons Node.js is a great framework:
• JavaScript end-to-end: One of the biggest advantages of Node.js is that it allows you
to write both server- and client-side scripts in JavaScript. There have always been
difficulties in deciding whether to put logic in client-side scripts or server-side scripts.
With Node.js you can take JavaScript written on the client and easily adapt it for the server
and vice versa. An added plus is that client developers and server developers are speaking
the same language.
• Event-driven scalability: Node.js applies a unique logic to handling web requests.
Rather than having multiple threads waiting to process web requests, with Node.js they are
processed on the same thread, using a basic event model. This allows Node.js webservers
to scale in ways that traditional webservers can’t.
• Extensibility: Node.js has a great following and very active development community.
People are providing new modules to extend Node.js functionality all the time. Also, it is
very simple to install and include new modules in Node.js; you can extend a Node.js
project to include new functionality in minutes.
• Fast implementation: Setting up Node.js and developing in it are super easy. In only a
few minutes you can install Node.js and have a working webserver.
NODE.JS-TO-ANGULARJS STACK
COMPONENTS
• In the Node.js-to-AngularJS stack, Node.js provides the fundamental platform for
development. The backend services and server-side scripts are all written in Node.js.
• MongoDB provides the data store for the website but is accessed via a MongoDB driver
Node.js module. The webserver is defined by Express, which is also a Node.js module.
• The view in the browser is defined and controlled using the AngularJS framework.
AngularJS is an MVC framework in which the model is made up of JSON or JavaScript
objects, the view is HTML/CSS, and the controller is AngularJS JavaScript code.
• It provides a very basic diagram of how the Node.js to AngularJS stack fits into the basic
website/web application model.
• The following sections describe each of these technologies and why they were chosen as
part of the Node.js to AngularJS stack. Later chapters in the book will cover each of the
technologies in much more detail.
module for backend full stack applications 1.pptx
• Basic diagram showing where Node.js,
Express, MongoDB, and AngularJS fit in the
web paradigm.
NODE.JS
• Node.js is a development framework that is based on Google’s V8 JavaScript engine and executes it.server-side code
in Node.js, including the webserver and the server-side scripts and any supporting web application functionality. The
fact that the webserver and the supporting web application scripts are running together in the same server-side
application allows for much tighter integration between the webserver and the scripts. Also, the webserver can run
directly on the Node.js platform as a Node.js module, which means it’s much easier than using, say, Apache for wiring
up new services or server-side scripts.
• The following are just a few reasons Node.js is a great framework:
1. JavaScript end-to-end: One of the biggest advantages of Node.js is that it allows you to write both server- and client-
side scripts in JavaScript. There have always been difficulties in deciding whether to put logic in client-side scripts or
server-side scripts. With Node.js you can take JavaScript written on the client and easily adapt it for the server and
vice versa. An added plus is that client developers and server developers are speaking the same language.
2. Event-driven scalability: Node.js applies a unique logic to handling web requests. Rather than having multiple
threads waiting to process web requests, with Node.js they are processed on the same thread, using a basic event
model. This allows Node.js webservers to scale in ways that traditional webservers can’t.
• • Extensibility: Node.js has a great following and very active development community. People are
providing new modules to extend Node.js functionality all the time. Also, it is very simple to install Aand include new
modules in Node.js; you can extend a Node.js project to include new functionality in minutes.
• • Fast implementation: Setting up Node.js and developing in it are super easy. In only a few minutes you
can install Node.js and have a working webserver.
EXPRESS
• The Express module acts as the webserver in the Node.js-to-AngularJS stack. Because it
runs in Node.js, it is easy to configure, implement, and control. The Express module
extends Node.js to provide several key components for handling web requests. It allows
you to implement a running webserver in Node.js with only a few lines of code.
• For example, the Express module provides the ability to easily set up destination routes
(URLs) for users to connect to. It also provides great functionality in terms of working
with HTTP request and response objects, including things like cookies and HTTP
headers.
• The following is a partial list of the valuable features of Express:
• Route management: Express makes it easy to define routes (URL endpoints) that tie
directly to the Node.js script functionality on the server.
• Error handling: Express provides built-in error handling for “document not found” and
other errors.
• Easy integration: An Express server can easily be implemented behind an existing
reverse proxy system, such as Nginx or Varnish. This allows you to easily integrate it
into your existing secured system.
• Cookies: Express provides easy cookie management.
• Session and cache management: Express also enables session management and cache
MONGODB
• MongoDB provides great website backend storage for high-traffic websites
that need to store data such as user comments, blogs, or other items because it
is quickly scalable and easy to implement..Node.js supports a variety of
database access drivers, so the data store can easily be MySQL or some other
database. However, the following are some of the reasons that MongoDB
really fits in the Node.js stack well:
• Document orientation: Because MongoDB is document oriented, data is
stored in the database in a format that is very close to what you deal with in
both server-side and client-side scripts. This eliminates the need to transfer
data from rows to objects and back.
• High performance: MongoDB is one of the highest-performing databases
available. Especially today, with more and more people interacting with
websites, it is important to have a backend that can support heavy traffic.
• High availability: MongoDB’s replication model makes it very easy to
maintain scalability while keeping high performance.
• High scalability: MongoDB’s structure makes it easy to scale horizontally by
sharding the data across multiple servers.
ANGULARJS
• AngularJS is a client-side framework developed by Google. It provides all
the functionality needed to handle user input in the browser, manipulate data
on the client side, and control how elements are displayed in the browser
view. It is written in JavaScript, with a reduced jQuery library. The theory
behind AngularJS is to provide a framework that makes it easy to implement
web applications using the MVC framework.
• Other JavaScript frameworks could be used with the Node.js platform, such
as Backbone, Ember, and Meteor. However, AngularJS has the best design,
feature set, and trajectory at this writing. Here are some of the benefits
AngularJS provides:
• Data binding: AngularJS has a very clean method for binding
data to HTML elements, using its powerful scope mechanism.
• Extensibility: The AngularJS architecture allows you to easily
extend almost every aspect of the language to provide your own
custom implementations.
• Clean: AngularJS forces you to write clean, logical code.
• Reusable code: The combination of extensibility and clean code
makes it very easy to write reusable code in AngularJS. In fact,
the language often forces you to do so when creating custom
services.
• Support: Google is investing a lot into this project, which gives it
an advantage over similar initiatives that have failed.
• Compatibility: AngularJS is based on JavaScript and has a close
relationship with jQuery. This makes it easier to begin integrating
AngularJS into your environment and reuse pieces of your
existing code within the structure of the AngularJS framework.
Installing Node On Windows (WINDOWS 10):
• You have to follow the following steps to install the Node.js on your
Windows :
• Step-1: Downloading the Node.js ‘.msi’ installer.
• The first step to install Node.js on windows is to download the installer.
Visit the official Node.js website i.e) https://nodejs.org/en/download/
and download the .msi file according to your system environment (32-
bit & 64-bit). An MSI installer will be downloaded on your system.
module for backend full stack applications 1.pptx
• Step-2: Running the Node.js installer.
• Now you need to install the node.js installer on your PC. You need to
follow the following steps for the Node.js to be installed:-
• Double click on the .msi installer.
The Node.js Setup wizard will open.
• Welcome To Node.js Setup Wizard.
Select “Next”
module for backend full stack applications 1.pptx
• After clicking “Next”, End-User License Agreement (EULA) will
open.
Check “I accept the terms in the License Agreement”
Select “Next”
• Destination Folder
Set the Destination Folder where you want to install Node.js &
Select “Next”
• Custom Setup
Select “Next”
module for backend full stack applications 1.pptx
NOTE :
• A prompt saying – “This step requires administrative privileges”
will appear.
• Authenticate the prompt as an “Administrator”
• Installing Node.js.Do not close or cancel the installer until the
install is complete
• Complete the Node.js Setup Wizard.
Click “Finish”
• Step 3:Verify that Node.js was properly installed or not.
• To check that node.js was completely installed on your system or
not, you can run the following command in your command prompt
or Windows Powershell and test it:-
• C:UsersAdmin> node -v
module for backend full stack applications 1.pptx
Step 4: Updating the Local npm version.
• The final step in node.js installed is the updation of your local npm version(if
required) – the package manager that comes bundled with Node.js.
• You can run the following command, to quickly update the npm
• npm install npm –global // Updates the ‘CLI’ client
NOTE :
• You do not need to do anything to the system variables as the windows installer
takes care of the system variables itself while installing through the .msi installer
• If you use any other format for installing node.js on your PC, you should put the
system variable path for node.js as follows:
• PATH : C:Users[username]AppDataRoamingnpm
C:Program Filesnodejs (Path to the nodejs folder)
CREATION
• Before creating an actual "Hello, World!" application using Node.js, let
us see the components of a Node.js application. 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.
Step 1 - Import Required Module
• We use the require directive to load the http module and store the
returned HTTP instance into an http variable as follows −
• 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.Write the
sample implementation to always return "Hello World".
http.createServer(function (request, response)
{
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain response.writeHead(200, {'Content-Type':
'text/plain'});
// Send the response body as "Hello World" response.end('Hello
Worldn'); }).listen(8081);
// Console will print the message console.log('Server running at
http://127.0.0.1:8081/');
• Step 3 - Testing Request & Response
• Let's put step 1 and 2 together in a file called main.js and start our
HTTP server as shown below −
var http = require("http"); http.createServer(function (request,
response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain response.writeHead(200, {'Content-Type':
'text/plain'});
// Send the response body as "Hello World" response.end('Hello
Worldn'); }).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
• Now execute the main.js to start the server as follows −
• $ node main.jsVerify the Output. Server has started.
• Server running at http://127.0.0.1:8081/
WRITING DATA TO THE CONSOLE
•One of the most useful modules in Node.js during the development process is
the console module.
•This module provides a lot of functionality when writing debug and information
statements to the console.
•The console module allows you to control output to the console, implement time
delta output, and write tracebacks and assertions to the console.
•Because the console module is so widely used, you do not need to load it into
your modules using a require() statement. You simply call the console function
using console.<function> (<parameters>).
Function Description
log([data],[...]) Writes data output to the console.The data variable can
be a string or an object that can be resolved to a string.
Additional parameters can also be sent. For example:
console.log("There are %d items", 5); >>There are 5
items
info([data],[...]) Same as console.log.
error([data],[...]) Same as console.log; however, the output is also sent
to stderr.
warn([data],[...]) Same as console.error.
dir(obj) Writes out a string representation of a JavaScript object
to the console. For example:
console.dir({name:"Brad", role:"Author"}); >> { name:
'Brad', role: 'Author' }
time(label) Assigns a current timestamp with ms precision to the
string label.
timeEnd(label) Creates a delta between the current time and the
timestamp assigned to label and outputs the results.
For example:
console.time("FileWrite"); f.write(data); //takes
about 500ms console.timeEnd("FileWrite"); >>
FileWrite: 500ms
trace(label) Writes out a stack trace of the current position in code
to stderr. For example:
module.trace("traceMark"); >>Trace: traceMark at
Object.<anonymous> (C:test.js:24:9) at
Module._compile (module.js:456:26) at
Object.Module._ext.js (module.js:474:10) at Module.load
(module.js:356:32) at Function.Module._load
(module.js:312:12) at
Function.Module.runMain(module.js:497:10) at startup
(node.js:119:16) at node.js:901:3
assert(expression,
[message])
Writes the message and stack trace to the console if
expression evaluates to false.
NODE.JS EVENTS
• According to the official documentation of Node.js, it is an asynchronous event-driven
JavaScript runtime. Node.js has an event-driven architecture which can perform
asynchronous tasks.
• Node.js has ‘events’ module which emits named events that can cause corresponding
functions or callbacks to be called.
• Functions(Callbacks) listen or subscribe to a particular event to occur and when that event
triggers, all the callbacks subscribed to that event are fired one by one in order to which
they were registered.
• The EventEmmitter class: All objects that emit events are instances of the EventEmitter
class. The event can be emitted or listen to an event with the help of EventEmitter
Syntax:
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
• Listening events: Before emits any event, it must register
functions(callbacks) to listen to the events.
Syntax:
eventEmitter.addListener(event, listener) eventEmitter.on(event, listener)
eventEmitter.once(event, listener)
eventEmmitter.on(event,listener) and
eventEmitter.addListener(event, listener)
are pretty much similar.
• It adds the listener at the end of the listener’s array for the specified event.
• Multiple calls to the same event and listener will add the listener multiple
times and correspondingly fire multiple times.
• Both functions return emitter, so calls can be chained.
• eventEmitter.once(event, listener) fires at most once for a
particular event and will be removed from listeners array after
it has listened once. Returns emitter, so calls can be chained.
• Emitting events: Every event is named event in nodejs. We
can trigger an event by emit(event, [arg1], [arg2], […])
function. We can pass an arbitrary set of arguments to the
listener functions
Syntax:
eventEmitter.emit(event, [arg1], [arg2], [...])
Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Registering to myEvent
eventEmitter.on('myEvent', (msg) => {
console.log(msg);
});
// Triggering myEvent
eventEmitter.emit('myEvent', "First event");
Output:
First event
• RemovingListener: The eventEmitter.removeListener() take
s two argument event and listener, and removes that listener
from the listeners array that is subscribed to that event.
• While eventEmitter.removeAllListeners() removes all the
listener from the array which are subscribed to the mentioned
event.
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])
• eventEmitter.listeners(): It returns an array of listeners for the
specified event.
Syntax:
eventEmitter.listeners(event)
• eventEmitter.listenerCount(): It returns the number of
listeners listening to the specified event.
Syntax:
eventEmitter.listenerCount(event)
• eventEmitter.prependOnceListener(): It will add the
one-time listener to the beginning of the array.
Syntax:
eventEmitter.prependOnceListener(event, listener)
• eventEmitter.prependListener(): It will add the
listener to the beginning of the array.
Syntax:
eventEmitter.prependListener(event, listener)
Adding work to event queue
• Node.js is a single-threaded event-driven platform that is capable of running
non-blocking, asynchronously programming.
• These functionalities of Node.js make it memory efficient. The event loop
allows Node.js to perform non-blocking I/O operations despite the fact that
JavaScript is single-threaded.
• It is done by assigning operations to the operating system whenever and
wherever possible.
• Most operating systems are multi-threaded and hence can handle multiple
operations executing in the background.
• When one of these operations is completed, the kernel tells Node.js and the
respective callback assigned to that operation is added to the event queue which
will eventually be executed.
Features of Event Loop:
• Event loop is an endless loop, which waits for tasks, executes them
and then sleeps until it receives more tasks.
• The event loop executes tasks from the event queue only when the
call stack is empty i.e. there is no ongoing task.
• The event loop allows us to use callbacks and promises.
• The event loop executes the tasks starting from the oldest first.
Writing data to console
Console.log("This is the first statement");
setTimeout(function(){
console.log("This is the second statement");
}, 1000);
console.log("This is the third statement");
Output: This is the first statement
This is the third statement
This is the second statement
• In the above example, the first console log statement is pushed to the call stack and “This is
the first statement” is logged on the console and the task is popped from the stack.
• Next, the setTimeout is pushed to the queue and the task is sent to the Operating system and
the timer is set for the task. This task is then popped from the stack.
• Next, the third console log statement is pushed to the call stack and “This is the third
statement” is logged on the console and the task is popped from the stack.
• When the timer set by setTimeout function (in this
case 1000 ms) runs out, the callback is sent to the
event queue.
• The event loop on finding the call stack empty takes
the task at the top of the event queue and sends it to
the call stack.
• The callback function for setTimeout function runs the
instruction and “This is the second statement” is
logged on the console and the task is popped from the
stack.
Working of the Event loop:
• When Node.js starts, it initializes the event loop, processes the
provided input script which may make async API calls, schedule
timers, then begins processing the event loop.
• In the previous example, the initial input script consisted of
console.log() statements and a setTimeout() function which schedules
a timer.
• When using Node.js, a special library module called libuv is used to
perform async operations. This library is also used, together with the
back logic of Node, to manage a special thread pool called the libuv
thread pool.
• This thread pool is composed of four threads used to delegate
operations that are too heavy for the event loop.
• I/O operations, Opening and closing connections, setTimeouts
are the example of such operations.
• When the thread pool completes a task, a callback function is
called which handles the error(if any) or does some other
operation.
• This callback function is sent to the event queue. When the call
stack is empty, the event goes through the event queue and
sends the callback to the call stack.
The following diagram is a proper representation of the event
loop in a Node.js server:
Phases of the Event loop: The following diagram shows a
simplified overview of the event loop order of operations:
• Timers: Callbacks scheduled by setTimeout() or setInterval()
are executed in this phase.
• Pending Callbacks: I/O callbacks deferred to the next loop
iteration are executed here.
• Idle, Prepare: Used internally only.
• Poll: Retrieves new I/O events.
• Check: It invokes setIntermediate() callbacks.
• Close Callbacks: It handles some close callbacks. Eg:
socket.on(‘close’, …)
module for backend full stack applications 1.pptx

More Related Content

PPTX
Node js installation steps.pptx slide share ppts
HemaSenthil5
 
PDF
What is mean stack?
Rishabh Saxena
 
PPTX
What is Mean Stack Development ?
Balajihope
 
PPTX
mearn-stack-new_ccvbhbhvgvgcdszsxdxfcf.pptx
aravym456
 
PPTX
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
PPT
Node js
Chirag Parmar
 
PPTX
Unit 1 Express J for mean stack and mern
Rahul Borate
 
PDF
Node.js Web Development SEO Expert Bangladesh LTD.pdf
Tasnim Jahan
 
Node js installation steps.pptx slide share ppts
HemaSenthil5
 
What is mean stack?
Rishabh Saxena
 
What is Mean Stack Development ?
Balajihope
 
mearn-stack-new_ccvbhbhvgvgcdszsxdxfcf.pptx
aravym456
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
Node js
Chirag Parmar
 
Unit 1 Express J for mean stack and mern
Rahul Borate
 
Node.js Web Development SEO Expert Bangladesh LTD.pdf
Tasnim Jahan
 

Similar to module for backend full stack applications 1.pptx (20)

PDF
An introduction to Node.js
Kasey McCurdy
 
PPT
Top java script frameworks ppt
Omkarsoft Bangalore
 
PDF
Professional Node.js Development Services | Node.js Development Company
Infowind Technologies (IT) Pvt Ltd
 
PPTX
After the LAMP, it's time to get MEAN
Jeff Fox
 
PPTX
NodeJS guide for beginners
Enoch Joshua
 
PPTX
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
PDF
Node.JS Development_ Features and Trends.pdf
JPLoft Solutions
 
PDF
Node js (runtime environment + js library) platform
Sreenivas Kappala
 
PPTX
mearn-stackjdksjdsfjdkofkdokodkojdj.pptx
aravym456
 
PPTX
Nodejs
Vinod Kumar Marupu
 
PDF
Node.js for beginner
Sarunyhot Suwannachoti
 
PDF
Nodejs presentation
Arvind Devaraj
 
PPTX
NodeJS - Server Side JS
Ganesh Kondal
 
PPTX
Node.js & Express.js Unleashed
Elewayte
 
PPTX
Nodejs
Bhushan Patil
 
PDF
Node.js Web Development .pdf
Abanti Aazmin
 
PPTX
Node js Introduction
sanskriti agarwal
 
DOCX
Understanding Node.js and Django.docx
Savior_Marketing
 
PDF
Node.js Web Development: Powering the Future of Web Applications
company
 
ODP
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
An introduction to Node.js
Kasey McCurdy
 
Top java script frameworks ppt
Omkarsoft Bangalore
 
Professional Node.js Development Services | Node.js Development Company
Infowind Technologies (IT) Pvt Ltd
 
After the LAMP, it's time to get MEAN
Jeff Fox
 
NodeJS guide for beginners
Enoch Joshua
 
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
Node.JS Development_ Features and Trends.pdf
JPLoft Solutions
 
Node js (runtime environment + js library) platform
Sreenivas Kappala
 
mearn-stackjdksjdsfjdkofkdokodkojdj.pptx
aravym456
 
Node.js for beginner
Sarunyhot Suwannachoti
 
Nodejs presentation
Arvind Devaraj
 
NodeJS - Server Side JS
Ganesh Kondal
 
Node.js & Express.js Unleashed
Elewayte
 
Node.js Web Development .pdf
Abanti Aazmin
 
Node js Introduction
sanskriti agarwal
 
Understanding Node.js and Django.docx
Savior_Marketing
 
Node.js Web Development: Powering the Future of Web Applications
company
 
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Ad

Recently uploaded (20)

PPTX
PHISHING ATTACKS. _. _.pptx[]
kumarrana7525
 
PPTX
DOC-20250728-WAprocess releases large amounts of carbon dioxide (CO₂), sulfur...
samt56673
 
PPTX
cocomo-220726173706-141e08f0.tyuiuuupptx
DharaniMani4
 
PPT
community diagnosis slides show health. ppt
michaelbrucebwana
 
PPTX
Query and optimizing operating system.pptx
YoomifTube
 
PPTX
西班牙海牙认证瓦伦西亚国际大学毕业证与成绩单文凭复刻快速办理毕业证书
sw6vvn9s
 
PPTX
原版UMiami毕业证文凭迈阿密大学学费单定制学历在线制作硕士毕业证
jicaaeb0
 
PDF
INTEL CPU 3RD GEN.pdf variadas de computacion
juancardozzo26
 
PPTX
办理HFM文凭|购买代特莫尔德音乐学院毕业证文凭100%复刻安全可靠的
1cz3lou8
 
PPTX
22. PSYCHOTOGENIC DRUGS.pptx 60d7co Gurinder
sriramraja650
 
PPTX
PPT FOR BASIC UNDERSTANDING OF COMPUTER HARDWARE, SOFTWARE & FIRMWARE
kavishvora10
 
PDF
Portable Veterinary Ultrasound Scanners & Animal Medical Equipment - TcCryo
3447752272
 
PPTX
Modern machinery.pptx sjsjnshhsnsnnjnnbbbb
raipureastha08
 
PPTX
Operating-Systems-A-Journey ( by information
parthbhanushali307
 
PPTX
G6Q1 WEEK 2 SCIENCE PPT.pptxLVLLLLLLLLLLLLLLLLL
DitaSIdnay
 
PPTX
INTERNET OF THINGS (IOT) network of interconnected devices.
rp1256748
 
PPTX
Basics of Memristors from zero to hero.pptx
onterusmail
 
PPTX
Intro_S4HANA_Using_Global_Bike_Slides_SD_en_v4.1.pptx
trishalasharma7
 
PPT
Susunan & Bagian DRAWING 153UWYHSGDGH.ppt
RezaFbriadi
 
PPTX
Boolean Algebra-Properties and Theorems.pptx
bhavanavarri5458
 
PHISHING ATTACKS. _. _.pptx[]
kumarrana7525
 
DOC-20250728-WAprocess releases large amounts of carbon dioxide (CO₂), sulfur...
samt56673
 
cocomo-220726173706-141e08f0.tyuiuuupptx
DharaniMani4
 
community diagnosis slides show health. ppt
michaelbrucebwana
 
Query and optimizing operating system.pptx
YoomifTube
 
西班牙海牙认证瓦伦西亚国际大学毕业证与成绩单文凭复刻快速办理毕业证书
sw6vvn9s
 
原版UMiami毕业证文凭迈阿密大学学费单定制学历在线制作硕士毕业证
jicaaeb0
 
INTEL CPU 3RD GEN.pdf variadas de computacion
juancardozzo26
 
办理HFM文凭|购买代特莫尔德音乐学院毕业证文凭100%复刻安全可靠的
1cz3lou8
 
22. PSYCHOTOGENIC DRUGS.pptx 60d7co Gurinder
sriramraja650
 
PPT FOR BASIC UNDERSTANDING OF COMPUTER HARDWARE, SOFTWARE & FIRMWARE
kavishvora10
 
Portable Veterinary Ultrasound Scanners & Animal Medical Equipment - TcCryo
3447752272
 
Modern machinery.pptx sjsjnshhsnsnnjnnbbbb
raipureastha08
 
Operating-Systems-A-Journey ( by information
parthbhanushali307
 
G6Q1 WEEK 2 SCIENCE PPT.pptxLVLLLLLLLLLLLLLLLLL
DitaSIdnay
 
INTERNET OF THINGS (IOT) network of interconnected devices.
rp1256748
 
Basics of Memristors from zero to hero.pptx
onterusmail
 
Intro_S4HANA_Using_Global_Bike_Slides_SD_en_v4.1.pptx
trishalasharma7
 
Susunan & Bagian DRAWING 153UWYHSGDGH.ppt
RezaFbriadi
 
Boolean Algebra-Properties and Theorems.pptx
bhavanavarri5458
 
Ad

module for backend full stack applications 1.pptx

  • 1. NODEJS BASICS • Node.Js is an open-source runtime environment for javascript. It is built on chrome’s V8 javascript engine. Node.Js can run on different platforms  linux,  windows  macos, and  mobile platforms • It is agnostic of the underlying OS. It allows programs written in javascrip to be executed on the server. Node.Js is also a part of the famous MEAN and MERN stack. • And according to stackoverflow’s developer survey, node.Js is the 6th most popular technology among programmers.Besides the javascript knowledge, understanding of databases, familiarity with html5, css3, and restful api will be greatly advantageous while working with node.Js.
  • 2. • The primary advantage of using node.js is that you can use javascript in both frontend and backend. And it’s easier to keep them in sync because a single language is used on both sides of applications. • Due to its event-based nature, Node.js is highly efficient for real-time applications that demand continual data updates. Moreover, the non- blocking input-output model helps to solve the performance issues. • Node.js is widely used to make scalable and lightweight web applications. • Node.js is renowned for its massive community which continuously contributes to its improvement. • Due to node modules, it became easier for developers to use prebuild modules and reuse code.
  • 4. FEATURES OF NODE.JS 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.
  • 5. • The webserver can run directly on the Node.js platform as a Node.js module, which means it’s much easier than using, say, Apache for wiring up new services or server-side scripts. • The following are just a few reasons Node.js is a great framework: • JavaScript end-to-end: One of the biggest advantages of Node.js is that it allows you to write both server- and client-side scripts in JavaScript. There have always been difficulties in deciding whether to put logic in client-side scripts or server-side scripts. With Node.js you can take JavaScript written on the client and easily adapt it for the server and vice versa. An added plus is that client developers and server developers are speaking the same language. • Event-driven scalability: Node.js applies a unique logic to handling web requests. Rather than having multiple threads waiting to process web requests, with Node.js they are processed on the same thread, using a basic event model. This allows Node.js webservers to scale in ways that traditional webservers can’t. • Extensibility: Node.js has a great following and very active development community. People are providing new modules to extend Node.js functionality all the time. Also, it is very simple to install and include new modules in Node.js; you can extend a Node.js project to include new functionality in minutes. • Fast implementation: Setting up Node.js and developing in it are super easy. In only a few minutes you can install Node.js and have a working webserver.
  • 6. NODE.JS-TO-ANGULARJS STACK COMPONENTS • In the Node.js-to-AngularJS stack, Node.js provides the fundamental platform for development. The backend services and server-side scripts are all written in Node.js. • MongoDB provides the data store for the website but is accessed via a MongoDB driver Node.js module. The webserver is defined by Express, which is also a Node.js module. • The view in the browser is defined and controlled using the AngularJS framework. AngularJS is an MVC framework in which the model is made up of JSON or JavaScript objects, the view is HTML/CSS, and the controller is AngularJS JavaScript code. • It provides a very basic diagram of how the Node.js to AngularJS stack fits into the basic website/web application model. • The following sections describe each of these technologies and why they were chosen as part of the Node.js to AngularJS stack. Later chapters in the book will cover each of the technologies in much more detail.
  • 8. • Basic diagram showing where Node.js, Express, MongoDB, and AngularJS fit in the web paradigm.
  • 9. NODE.JS • Node.js is a development framework that is based on Google’s V8 JavaScript engine and executes it.server-side code in Node.js, including the webserver and the server-side scripts and any supporting web application functionality. The fact that the webserver and the supporting web application scripts are running together in the same server-side application allows for much tighter integration between the webserver and the scripts. Also, the webserver can run directly on the Node.js platform as a Node.js module, which means it’s much easier than using, say, Apache for wiring up new services or server-side scripts. • The following are just a few reasons Node.js is a great framework: 1. JavaScript end-to-end: One of the biggest advantages of Node.js is that it allows you to write both server- and client- side scripts in JavaScript. There have always been difficulties in deciding whether to put logic in client-side scripts or server-side scripts. With Node.js you can take JavaScript written on the client and easily adapt it for the server and vice versa. An added plus is that client developers and server developers are speaking the same language. 2. Event-driven scalability: Node.js applies a unique logic to handling web requests. Rather than having multiple threads waiting to process web requests, with Node.js they are processed on the same thread, using a basic event model. This allows Node.js webservers to scale in ways that traditional webservers can’t. • • Extensibility: Node.js has a great following and very active development community. People are providing new modules to extend Node.js functionality all the time. Also, it is very simple to install Aand include new modules in Node.js; you can extend a Node.js project to include new functionality in minutes. • • Fast implementation: Setting up Node.js and developing in it are super easy. In only a few minutes you can install Node.js and have a working webserver.
  • 10. EXPRESS • The Express module acts as the webserver in the Node.js-to-AngularJS stack. Because it runs in Node.js, it is easy to configure, implement, and control. The Express module extends Node.js to provide several key components for handling web requests. It allows you to implement a running webserver in Node.js with only a few lines of code. • For example, the Express module provides the ability to easily set up destination routes (URLs) for users to connect to. It also provides great functionality in terms of working with HTTP request and response objects, including things like cookies and HTTP headers. • The following is a partial list of the valuable features of Express: • Route management: Express makes it easy to define routes (URL endpoints) that tie directly to the Node.js script functionality on the server. • Error handling: Express provides built-in error handling for “document not found” and other errors. • Easy integration: An Express server can easily be implemented behind an existing reverse proxy system, such as Nginx or Varnish. This allows you to easily integrate it into your existing secured system. • Cookies: Express provides easy cookie management. • Session and cache management: Express also enables session management and cache
  • 11. MONGODB • MongoDB provides great website backend storage for high-traffic websites that need to store data such as user comments, blogs, or other items because it is quickly scalable and easy to implement..Node.js supports a variety of database access drivers, so the data store can easily be MySQL or some other database. However, the following are some of the reasons that MongoDB really fits in the Node.js stack well: • Document orientation: Because MongoDB is document oriented, data is stored in the database in a format that is very close to what you deal with in both server-side and client-side scripts. This eliminates the need to transfer data from rows to objects and back. • High performance: MongoDB is one of the highest-performing databases available. Especially today, with more and more people interacting with websites, it is important to have a backend that can support heavy traffic. • High availability: MongoDB’s replication model makes it very easy to maintain scalability while keeping high performance. • High scalability: MongoDB’s structure makes it easy to scale horizontally by sharding the data across multiple servers.
  • 12. ANGULARJS • AngularJS is a client-side framework developed by Google. It provides all the functionality needed to handle user input in the browser, manipulate data on the client side, and control how elements are displayed in the browser view. It is written in JavaScript, with a reduced jQuery library. The theory behind AngularJS is to provide a framework that makes it easy to implement web applications using the MVC framework. • Other JavaScript frameworks could be used with the Node.js platform, such as Backbone, Ember, and Meteor. However, AngularJS has the best design, feature set, and trajectory at this writing. Here are some of the benefits AngularJS provides:
  • 13. • Data binding: AngularJS has a very clean method for binding data to HTML elements, using its powerful scope mechanism. • Extensibility: The AngularJS architecture allows you to easily extend almost every aspect of the language to provide your own custom implementations. • Clean: AngularJS forces you to write clean, logical code. • Reusable code: The combination of extensibility and clean code makes it very easy to write reusable code in AngularJS. In fact, the language often forces you to do so when creating custom services. • Support: Google is investing a lot into this project, which gives it an advantage over similar initiatives that have failed. • Compatibility: AngularJS is based on JavaScript and has a close relationship with jQuery. This makes it easier to begin integrating AngularJS into your environment and reuse pieces of your existing code within the structure of the AngularJS framework.
  • 14. Installing Node On Windows (WINDOWS 10): • You have to follow the following steps to install the Node.js on your Windows : • Step-1: Downloading the Node.js ‘.msi’ installer. • The first step to install Node.js on windows is to download the installer. Visit the official Node.js website i.e) https://nodejs.org/en/download/ and download the .msi file according to your system environment (32- bit & 64-bit). An MSI installer will be downloaded on your system.
  • 16. • Step-2: Running the Node.js installer. • Now you need to install the node.js installer on your PC. You need to follow the following steps for the Node.js to be installed:- • Double click on the .msi installer. The Node.js Setup wizard will open. • Welcome To Node.js Setup Wizard. Select “Next”
  • 18. • After clicking “Next”, End-User License Agreement (EULA) will open. Check “I accept the terms in the License Agreement” Select “Next”
  • 19. • Destination Folder Set the Destination Folder where you want to install Node.js & Select “Next”
  • 22. NOTE : • A prompt saying – “This step requires administrative privileges” will appear. • Authenticate the prompt as an “Administrator” • Installing Node.js.Do not close or cancel the installer until the install is complete • Complete the Node.js Setup Wizard. Click “Finish”
  • 23. • Step 3:Verify that Node.js was properly installed or not. • To check that node.js was completely installed on your system or not, you can run the following command in your command prompt or Windows Powershell and test it:- • C:UsersAdmin> node -v
  • 25. Step 4: Updating the Local npm version. • The final step in node.js installed is the updation of your local npm version(if required) – the package manager that comes bundled with Node.js. • You can run the following command, to quickly update the npm • npm install npm –global // Updates the ‘CLI’ client NOTE : • You do not need to do anything to the system variables as the windows installer takes care of the system variables itself while installing through the .msi installer • If you use any other format for installing node.js on your PC, you should put the system variable path for node.js as follows: • PATH : C:Users[username]AppDataRoamingnpm C:Program Filesnodejs (Path to the nodejs folder)
  • 26. CREATION • Before creating an actual "Hello, World!" application using Node.js, let us see the components of a Node.js application. 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.
  • 27. Step 1 - Import Required Module • We use the require directive to load the http module and store the returned HTTP instance into an http variable as follows − • 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.Write the sample implementation to always return "Hello World".
  • 28. http.createServer(function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello Worldn'); }).listen(8081); // Console will print the message console.log('Server running at http://127.0.0.1:8081/');
  • 29. • Step 3 - Testing Request & Response • Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown below − var http = require("http"); http.createServer(function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello Worldn'); }).listen(8081); // Console will print the message console.log('Server running at http://127.0.0.1:8081/');
  • 30. • Now execute the main.js to start the server as follows − • $ node main.jsVerify the Output. Server has started. • Server running at http://127.0.0.1:8081/
  • 31. WRITING DATA TO THE CONSOLE •One of the most useful modules in Node.js during the development process is the console module. •This module provides a lot of functionality when writing debug and information statements to the console. •The console module allows you to control output to the console, implement time delta output, and write tracebacks and assertions to the console. •Because the console module is so widely used, you do not need to load it into your modules using a require() statement. You simply call the console function using console.<function> (<parameters>).
  • 32. Function Description log([data],[...]) Writes data output to the console.The data variable can be a string or an object that can be resolved to a string. Additional parameters can also be sent. For example: console.log("There are %d items", 5); >>There are 5 items info([data],[...]) Same as console.log. error([data],[...]) Same as console.log; however, the output is also sent to stderr. warn([data],[...]) Same as console.error. dir(obj) Writes out a string representation of a JavaScript object to the console. For example: console.dir({name:"Brad", role:"Author"}); >> { name: 'Brad', role: 'Author' } time(label) Assigns a current timestamp with ms precision to the string label.
  • 33. timeEnd(label) Creates a delta between the current time and the timestamp assigned to label and outputs the results. For example: console.time("FileWrite"); f.write(data); //takes about 500ms console.timeEnd("FileWrite"); >> FileWrite: 500ms trace(label) Writes out a stack trace of the current position in code to stderr. For example: module.trace("traceMark"); >>Trace: traceMark at Object.<anonymous> (C:test.js:24:9) at Module._compile (module.js:456:26) at Object.Module._ext.js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain(module.js:497:10) at startup (node.js:119:16) at node.js:901:3 assert(expression, [message]) Writes the message and stack trace to the console if expression evaluates to false.
  • 34. NODE.JS EVENTS • According to the official documentation of Node.js, it is an asynchronous event-driven JavaScript runtime. Node.js has an event-driven architecture which can perform asynchronous tasks. • Node.js has ‘events’ module which emits named events that can cause corresponding functions or callbacks to be called. • Functions(Callbacks) listen or subscribe to a particular event to occur and when that event triggers, all the callbacks subscribed to that event are fired one by one in order to which they were registered. • The EventEmmitter class: All objects that emit events are instances of the EventEmitter class. The event can be emitted or listen to an event with the help of EventEmitter Syntax: const EventEmitter=require('events'); var eventEmitter=new EventEmitter();
  • 35. • Listening events: Before emits any event, it must register functions(callbacks) to listen to the events. Syntax: eventEmitter.addListener(event, listener) eventEmitter.on(event, listener) eventEmitter.once(event, listener) eventEmmitter.on(event,listener) and eventEmitter.addListener(event, listener) are pretty much similar. • It adds the listener at the end of the listener’s array for the specified event. • Multiple calls to the same event and listener will add the listener multiple times and correspondingly fire multiple times. • Both functions return emitter, so calls can be chained.
  • 36. • eventEmitter.once(event, listener) fires at most once for a particular event and will be removed from listeners array after it has listened once. Returns emitter, so calls can be chained. • Emitting events: Every event is named event in nodejs. We can trigger an event by emit(event, [arg1], [arg2], […]) function. We can pass an arbitrary set of arguments to the listener functions Syntax: eventEmitter.emit(event, [arg1], [arg2], [...])
  • 37. Importing events const EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); // Registering to myEvent eventEmitter.on('myEvent', (msg) => { console.log(msg); }); // Triggering myEvent eventEmitter.emit('myEvent', "First event"); Output: First event
  • 38. • RemovingListener: The eventEmitter.removeListener() take s two argument event and listener, and removes that listener from the listeners array that is subscribed to that event. • While eventEmitter.removeAllListeners() removes all the listener from the array which are subscribed to the mentioned event. Syntax: eventEmitter.removeListener(event, listener) eventEmitter.removeAllListeners([event])
  • 39. • eventEmitter.listeners(): It returns an array of listeners for the specified event. Syntax: eventEmitter.listeners(event) • eventEmitter.listenerCount(): It returns the number of listeners listening to the specified event. Syntax: eventEmitter.listenerCount(event)
  • 40. • eventEmitter.prependOnceListener(): It will add the one-time listener to the beginning of the array. Syntax: eventEmitter.prependOnceListener(event, listener) • eventEmitter.prependListener(): It will add the listener to the beginning of the array. Syntax: eventEmitter.prependListener(event, listener)
  • 41. Adding work to event queue • Node.js is a single-threaded event-driven platform that is capable of running non-blocking, asynchronously programming. • These functionalities of Node.js make it memory efficient. The event loop allows Node.js to perform non-blocking I/O operations despite the fact that JavaScript is single-threaded. • It is done by assigning operations to the operating system whenever and wherever possible. • Most operating systems are multi-threaded and hence can handle multiple operations executing in the background. • When one of these operations is completed, the kernel tells Node.js and the respective callback assigned to that operation is added to the event queue which will eventually be executed.
  • 42. Features of Event Loop: • Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks. • The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task. • The event loop allows us to use callbacks and promises. • The event loop executes the tasks starting from the oldest first.
  • 43. Writing data to console Console.log("This is the first statement"); setTimeout(function(){ console.log("This is the second statement"); }, 1000); console.log("This is the third statement"); Output: This is the first statement This is the third statement This is the second statement • In the above example, the first console log statement is pushed to the call stack and “This is the first statement” is logged on the console and the task is popped from the stack. • Next, the setTimeout is pushed to the queue and the task is sent to the Operating system and the timer is set for the task. This task is then popped from the stack. • Next, the third console log statement is pushed to the call stack and “This is the third statement” is logged on the console and the task is popped from the stack.
  • 44. • When the timer set by setTimeout function (in this case 1000 ms) runs out, the callback is sent to the event queue. • The event loop on finding the call stack empty takes the task at the top of the event queue and sends it to the call stack. • The callback function for setTimeout function runs the instruction and “This is the second statement” is logged on the console and the task is popped from the stack.
  • 45. Working of the Event loop: • When Node.js starts, it initializes the event loop, processes the provided input script which may make async API calls, schedule timers, then begins processing the event loop. • In the previous example, the initial input script consisted of console.log() statements and a setTimeout() function which schedules a timer. • When using Node.js, a special library module called libuv is used to perform async operations. This library is also used, together with the back logic of Node, to manage a special thread pool called the libuv thread pool. • This thread pool is composed of four threads used to delegate operations that are too heavy for the event loop.
  • 46. • I/O operations, Opening and closing connections, setTimeouts are the example of such operations. • When the thread pool completes a task, a callback function is called which handles the error(if any) or does some other operation. • This callback function is sent to the event queue. When the call stack is empty, the event goes through the event queue and sends the callback to the call stack.
  • 47. The following diagram is a proper representation of the event loop in a Node.js server:
  • 48. Phases of the Event loop: The following diagram shows a simplified overview of the event loop order of operations:
  • 49. • Timers: Callbacks scheduled by setTimeout() or setInterval() are executed in this phase. • Pending Callbacks: I/O callbacks deferred to the next loop iteration are executed here. • Idle, Prepare: Used internally only. • Poll: Retrieves new I/O events. • Check: It invokes setIntermediate() callbacks. • Close Callbacks: It handles some close callbacks. Eg: socket.on(‘close’, …)