SlideShare a Scribd company logo
Node.js – Server Side JavaScript
GaneshKondal
June 13, 2014
Agenda
• Intent
• Node JS – Background & Overview
• JS Basics
• Pre-Cursors
• Installation, Setup, IDE & NPM
• JS Basics – callback, blocking & non-blocking I/O
• NodeJS –Modules, simple server
• Node JS Architecture
• Blocking vs. Non-Blocking I/O – Comparison
• Web Application with Express MVC
• Project – Code Structure
• App Development Sequence
• Code Parts – UI Template, Router, Database invocation
• Industry Adoption
• Applicability – Suited / Not Suited for
• Next Session – Topics
Intent
• To introduce listeners to the NodeJS platform; discuss the key aspect of non-
blocking I/O; run through a sample web app developed using Express framework
• An hour of glimpsing around NodeJS – Nothing else
Follow-up
Follow-up sessions will extend the sample application to work with files, show case a
socket I/O based file explorer and integrate with NoSQL databases like MongoDB
4
Node JS – Background
• Node.js runs on V8 Javascript Engine
• V8 is Google’s open source engine; written in C++ for Chrome
• Created by Ryan Dahl in 2009 and first published in 2011
• Runs on Linux and Windows
• Development and Maintenance of NodeJS is done by Joyent
• Written in C/C++ (80%) and JavaScript (20%) and it is open source.
Overview
• Node.js is ‘server-side JavaScript’; event-driven async I/O
• Well optimized for high concurrency, high performance and network applications
• Uses an event-driven, non-blocking I/O model.
• Non-blocking I/O happens via JavaScript’s callbacks.
• Programs for Node.js are written in JavaScript [not DOM manipulation like in jQuery]
• Node JS executes in a single threaded fashion
5
Pre-Cursors
• Installation
• From website or
• Homebrew (mac OS) or Synaptic (Ubuntu)
• IDE –
• JetBrains WebStorm 8.0.1 OR
• Sublime Text OR
• Eclipse with nodeclipse
• NPM
• Node Package Manager enables get third party modules
• Two modes
• Global - installs modules c:users356992appdata…
• Local – in the same directory under node_modules
• Works based on package.json in the root folder
• Comes packaged with Node installation
Open Source
Node Repository
6
JavaScript – Basics
s1
s2
s3
s4
s5
• Functions in JavaScript are objects – first class citizens
• Essentially, you can pass a function as a variable to another function call
• Closure
Callbacks are – a
Functional
programming paradigm
Callbacks a.k.a Higher-
Order function
Only the function
definition is passed;
function is not
executed
A closure is an inner
function that has
access to the outer
(enclosing) function’s
variables—scope chain
• When callback is invoked, if there is a ‘this’ reference; it will be ‘undefined’
• Handling ‘this’ in a callback is via JS methods of ‘apply(..)’ or ‘call(..)’ OR
• Have the ‘this’ stored in a variable called ‘self’ and use it.
7
Event Driven Programming – Blocking, Non-Blocking I/O
s1
s2
s3
s4
s5
Traditional I/O
Non-blocking I/O
var result = db.query(“select x,y from tableXY”);
doSomethingWithResult(result); //waits for the result!
doSomethingWithoutResult(); //execution is un-necessarily blocked!
db.query(“select x, y from tableXY”,
function (result){
// gets called once the result is ready!
doSomethingWithResult(result);
});
doSomethingWithoutResult(); //executes without any delay!
Callback on db query
completion event
8
Fundamentals – Modules, Sample Code
• Modules
• Referenced by file path or file name
• No Global Scope in NodeJS
• Modules are loaded only once
• Libraries in node are packages/modules
Module 1 Module
s5
s1
s2
s3
s4
s1
s2
Global
Scope
Scripts
within a
module
context
• Sample – Web Server in 3 lines
Classic Browser Runtime
Node Runtime & Scope
s3
s4
s5
Loads the ‘http’ module
Function that handles the incoming
requests. Executed by the main
thread of node.
Multi-Threaded HTTP Server – Blocking I/O
• On heavy load – we see more threads that leads to more context switching which in turn leads to
more CPU / Memory usage
• Classic discussion on threads vs. events is in Benjamin Erb’s Thesis
[Strongloop, 2014]
Node JS Architecture – Non-Blocking I/O
• On heavy load – we see more threads that leads to more context switching which in turn leads to
more CPU / Memory usage
• Classic discussion on threads vs. events is in Benjamin Erb’s Thesis
[Strongloop, 2014]
Node JS – Event Loop
• Node is single-threaded
• Follows an event-driven
functional programming
model
• Errors in the main thread
kills the server
• POSIX thread switching is
not costly
Million concurrent connections
http://blog.caustik.com/2012/08/19/node-js-w1m-concurrent-connections/
[www.udemy.com, 2014]
Node JS – Event Loop
Client
Event
loop
(main thread)
C++ Thread pool
(worker threads)
Clients send HTTP requests
to Node.js server
An Event-loop is woken up by OS,
passes request and response objects
to the thread-pool
Long-running jobs run
on worker threads
Response is sent
back to main thread
via callback
Event loop returns
result to client
• Node is single-threaded
• Follows an event-driven
functional programming
model
• Errors in the main thread
kills the server
Million concurrent connections
http://blog.caustik.com/2012/08/19/node-js-w1m-concurrent-connections/
Java vs. NodeJS –Performance [ Return data with constant sleep]
Java Stack & Description
• Java servlet returns ‘hello world’ with a
200ms sleep [ simulating a 200ms DB call]
• Executed in Apache Tomcat 6.0, JDK 6
• Tomcat runs in a multi-threaded mode &
in a blocking mode
Node v 0.10
• Returns a ‘hello world’ equivalent string
with a 200ms timeout set in call
• Node JS ran in the (defacto) non-blocking
mode
Not a comparison between Java vs. Node –
rather a comparison of blocking and non-
blocking I/O
Node JS – Run Sample Web Application
• Use cases we will see
• Get the list of players from NoSQL (MongoDB)
• Add a player to the list
• STEP 1 – setup
• Install Node
• Install Express
• Install Expres – Genertor
• Generate a node express project
• Install MongoDB
• STEP 2 – Package.json edit to suit your needs
• STEP 3 – Install dependencies
• STEP 4 – Run
d:nodejs> npm install express
d:nodejs> npm install express-generator
d:nodejs> express playerlist
d:nodejsplayerlist> npm install
d:nodejsplayerlist> npm start
Node JS – Project Structure
Jade HTML Preprocessor
Express Engine
Mongo DB
Monk
Node.js Server
d:nodejs> npm install express
d:nodejs> npm install express-generator
d:nodejs> express playerlist
V
M
C
Public images, CSS and JS files
URI routing; view attachment
View templates using Jade.
Multiple other options exists – ejs, jade
Mongo DB Data files
• Jade – Template engine. Very short syntax to create a HTML
• Monk – Small layer that enables MongoDB a super-easy task within NodeJS
Node JS – Code Parts – MVC
1) Import necessary modules
2) Initialize Express
3) Configure the express app
a. Logger
b. Views
c. Template engine
d. Static images directory
e. …
4) Configure the router
5) Router = Controller
a. Connects the model, jade view
b. Enables navigation across the URIs
Node JS – UI Template
• Jade is a server side templating engine – like Thymeleaf, JSP, ASP
• Short syntax to create HTML
Node JS – Code Parts contd.
• Router
• Database
View: Jade template name
View Model: “Model of the view”
JSON object passed to the view
1
2
3
Load ‘Mongo’, ‘Monk’ necessary to
connect to MongoDB
Put the Mongo DB reference handle
to the global request object
db.get - Monk APIs to fetch
db.insert,db.find({},fn)
are some of the other relevant APIs
Node JS – Deployment
• Simplistic – Newbie mode
• node server.js
• Command line execution. No restart; or no monitoring
• Dies with the command shell closing
• Little better
• node server.js &
• Running as a background application in *nix
• Will last than the shell that started it
• Script that loops & restarts the server
• Still limited the lifeline of the script that starts
• Improvised shell
• Cron based monitoring
• Log attached
• Auto start enabled
• External port monitoring enabled for load balancing
While :
do
// node server.js
// sleep x seconds
done
// description
// author
// specify port, Ethernet card
// attach a cron job – for every minute
// start in sudo mode
// ensure a log file is rolled
// attached the init.d in linux
20
Industry Adoption
Paypal’s Account Overview via NodeJS
• Timeline & Inventory
• Built twice as fast as the Java Application
• 33% fewer lines of code – compared to the same functionality in
Java /Spring
• 40% fewer files
• Performance
• Double the requests vs. Java Application
• 35% decrease in the average response time
• Essentially, page loading is faster than the Java App
• Stack
• NodeJS – Server
• KrakenJS – Secure and scalable layer that extends Express, which
provides convention
• Dust – Asynchronous templates
21
Pros & Cons
Pros
• Fast – Execution speed
• Faster to market – development speed
• Less lines of code
• Great community
• Proven with high volume systems
• Most suited for networking, I/O intensive applications
Cons
• Writing event driven code is complex compared to
synchronous code
• Writing a large business logic centric system is cumbersome
• Callback hell
• Exception handling is not straight forward
22
Suitability
Suitable Scenarios
• Most suited for networking, I/O intensive applications
• Applications that need high concurrency / Queued concurrent inputs
• Streaming Applications – like Chat servers
• Proxy Service
• Real time applications
• Monitoring Dashboards
• like Brokerage Dashboard (Node JS + Socket IO)
• Application Monitoring
• REST APIs
Not Suited For
• Large business logic centric systems
• Heavy server side computation is required
Next Session
• File handlers, Streams
• Event Emitters
• Error, Exception Handling
• Socket.IO
• Build & Deploy – using Grunt
• JS CoE – Seed project for node
Thank You
24
Reference
• Ryan Dhals original presentation in JS Conf
http://s3.amazonaws.com/four.livejournal/20091117/jsconf.pdf
• Expess framework
• http://expressjs.com/guide.htmld
• Node JS - www.nodejs.org
• Event Loop – www.udemy.com
• Strongloop – how nodejs is faster
http://strongloop.com/strongblog/node-js-is-faster-than-java/
Reference
26
THANK YOU
Appendix
27
Appendix
Why Node JS is faster [ Return data with constant sleep]
• Asynchronous Non-blocking I/O is the
root cause
• Not just I/O alone – all of node js 50k
modules are written in an async fashion
• Debuggers, monitors, loggers,
• Cluster manager
• File operation
• Java NIO alone is not enough

More Related Content

What's hot

What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
Edureka!
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
AMD Developer Central
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
Express JS
Express JSExpress JS
Express JS
Alok Guha
 
Node js
Node jsNode js
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
TheCreativedev Blog
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
Julio Bitencourt
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Rob O'Doherty
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
Kanika Gera
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
sanskriti agarwal
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
Fabien Vauchelles
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
Intro to React
Intro to ReactIntro to React
Intro to React
Justin Reock
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
David Ličen
 
Node.js
Node.jsNode.js
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
TheCreativedev Blog
 

What's hot (20)

What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
 
Express JS
Express JSExpress JS
Express JS
 
Node js
Node jsNode js
Node js
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
Express node js
Express node jsExpress node js
Express node js
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 
Node.js
Node.jsNode.js
Node.js
 
Javascript
JavascriptJavascript
Javascript
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 

Viewers also liked

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
AppDynamics
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
NodejsFoundation
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
David Boyer
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
Sergi Mansilla
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.js
Ryan Anklam
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
Felix Geisendörfer
 
Intro to node.js web apps
Intro to node.js web appsIntro to node.js web apps
Intro to node.js web apps
Thanos Polychronakis
 
Node.js – ask us anything!
Node.js – ask us anything! Node.js – ask us anything!
Node.js – ask us anything!
Dev_Events
 
Building A Web App In 100% JavaScript with Carl Bergenhem
 Building A Web App In 100% JavaScript with Carl Bergenhem Building A Web App In 100% JavaScript with Carl Bergenhem
Building A Web App In 100% JavaScript with Carl Bergenhem
FITC
 
Intro to node.js
Intro to node.jsIntro to node.js
Intro to node.js
Thanos Polychronakis
 
Business considerations for node.js applications
Business considerations for node.js applicationsBusiness considerations for node.js applications
Business considerations for node.js applications
Aspenware
 
Pengenalan Dasar NodeJS
Pengenalan Dasar NodeJSPengenalan Dasar NodeJS
Pengenalan Dasar NodeJS
alfi setyadi
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
Buzzcapture
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
Ganesh Kondal
 
Knonex
KnonexKnonex
Node js overview
Node js overviewNode js overview
Node js overview
Eyal Vardi
 

Viewers also liked (20)

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
Node js
Node jsNode js
Node js
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.js
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Intro to node.js web apps
Intro to node.js web appsIntro to node.js web apps
Intro to node.js web apps
 
Node.js – ask us anything!
Node.js – ask us anything! Node.js – ask us anything!
Node.js – ask us anything!
 
Building A Web App In 100% JavaScript with Carl Bergenhem
 Building A Web App In 100% JavaScript with Carl Bergenhem Building A Web App In 100% JavaScript with Carl Bergenhem
Building A Web App In 100% JavaScript with Carl Bergenhem
 
Intro to node.js
Intro to node.jsIntro to node.js
Intro to node.js
 
Business considerations for node.js applications
Business considerations for node.js applicationsBusiness considerations for node.js applications
Business considerations for node.js applications
 
Pengenalan Dasar NodeJS
Pengenalan Dasar NodeJSPengenalan Dasar NodeJS
Pengenalan Dasar NodeJS
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
 
Knonex
KnonexKnonex
Knonex
 
Node js overview
Node js overviewNode js overview
Node js overview
 

Similar to NodeJS - Server Side JS

Irfan maulana nodejs web development
Irfan maulana   nodejs web developmentIrfan maulana   nodejs web development
Irfan maulana nodejs web development
PHP Indonesia
 
PHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web DevelopmentPHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web Development
Irfan Maulana
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
Bareen Shaikh
 
A Journey Begin with Node.js
A Journey Begin with Node.jsA Journey Begin with Node.js
A Journey Begin with Node.js
Khalid Farhan
 
Oracle application container cloud back end integration using node final
Oracle application container cloud back end integration using node finalOracle application container cloud back end integration using node final
Oracle application container cloud back end integration using node final
Getting value from IoT, Integration and Data Analytics
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.js
Kasey McCurdy
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
Khaled Mosharraf
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
JITENDRA KUMAR PATEL
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystem
Yukti Kaura
 
Node js internal
Node js internalNode js internal
Node js internal
Chinh Ngo Nguyen
 
Developing and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST APIDeveloping and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST API
All Things Open
 
TDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDBTDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDB
Valeri Karpov
 
T4T Training day - NodeJS
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJSTim Sommer
 
Mini-Training: Node.js
Mini-Training: Node.jsMini-Training: Node.js
Mini-Training: Node.js
Betclic Everest Group Tech Team
 
node_js.pptx
node_js.pptxnode_js.pptx
node_js.pptx
dipen55
 
Node and Azure
Node and AzureNode and Azure
Node and Azure
Jason Gerard
 
Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)
Lucas Jellema
 
Going Offline with JS
Going Offline with JSGoing Offline with JS
Going Offline with JS
brendankowitz
 

Similar to NodeJS - Server Side JS (20)

Irfan maulana nodejs web development
Irfan maulana   nodejs web developmentIrfan maulana   nodejs web development
Irfan maulana nodejs web development
 
PHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web DevelopmentPHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web Development
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 
A Journey Begin with Node.js
A Journey Begin with Node.jsA Journey Begin with Node.js
A Journey Begin with Node.js
 
Oracle application container cloud back end integration using node final
Oracle application container cloud back end integration using node finalOracle application container cloud back end integration using node final
Oracle application container cloud back end integration using node final
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.js
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystem
 
Node js internal
Node js internalNode js internal
Node js internal
 
Developing and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST APIDeveloping and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST API
 
TDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDBTDD a REST API With Node.js and MongoDB
TDD a REST API With Node.js and MongoDB
 
T4T Training day - NodeJS
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJS
 
Mini-Training: Node.js
Mini-Training: Node.jsMini-Training: Node.js
Mini-Training: Node.js
 
node_js.pptx
node_js.pptxnode_js.pptx
node_js.pptx
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
 
Node and Azure
Node and AzureNode and Azure
Node and Azure
 
Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)
 
Going Offline with JS
Going Offline with JSGoing Offline with JS
Going Offline with JS
 

Recently uploaded

Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
abdulrafaychaudhry
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 

Recently uploaded (20)

Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 

NodeJS - Server Side JS

  • 1. Node.js – Server Side JavaScript GaneshKondal June 13, 2014
  • 2. Agenda • Intent • Node JS – Background & Overview • JS Basics • Pre-Cursors • Installation, Setup, IDE & NPM • JS Basics – callback, blocking & non-blocking I/O • NodeJS –Modules, simple server • Node JS Architecture • Blocking vs. Non-Blocking I/O – Comparison • Web Application with Express MVC • Project – Code Structure • App Development Sequence • Code Parts – UI Template, Router, Database invocation • Industry Adoption • Applicability – Suited / Not Suited for • Next Session – Topics
  • 3. Intent • To introduce listeners to the NodeJS platform; discuss the key aspect of non- blocking I/O; run through a sample web app developed using Express framework • An hour of glimpsing around NodeJS – Nothing else Follow-up Follow-up sessions will extend the sample application to work with files, show case a socket I/O based file explorer and integrate with NoSQL databases like MongoDB
  • 4. 4 Node JS – Background • Node.js runs on V8 Javascript Engine • V8 is Google’s open source engine; written in C++ for Chrome • Created by Ryan Dahl in 2009 and first published in 2011 • Runs on Linux and Windows • Development and Maintenance of NodeJS is done by Joyent • Written in C/C++ (80%) and JavaScript (20%) and it is open source. Overview • Node.js is ‘server-side JavaScript’; event-driven async I/O • Well optimized for high concurrency, high performance and network applications • Uses an event-driven, non-blocking I/O model. • Non-blocking I/O happens via JavaScript’s callbacks. • Programs for Node.js are written in JavaScript [not DOM manipulation like in jQuery] • Node JS executes in a single threaded fashion
  • 5. 5 Pre-Cursors • Installation • From website or • Homebrew (mac OS) or Synaptic (Ubuntu) • IDE – • JetBrains WebStorm 8.0.1 OR • Sublime Text OR • Eclipse with nodeclipse • NPM • Node Package Manager enables get third party modules • Two modes • Global - installs modules c:users356992appdata… • Local – in the same directory under node_modules • Works based on package.json in the root folder • Comes packaged with Node installation Open Source Node Repository
  • 6. 6 JavaScript – Basics s1 s2 s3 s4 s5 • Functions in JavaScript are objects – first class citizens • Essentially, you can pass a function as a variable to another function call • Closure Callbacks are – a Functional programming paradigm Callbacks a.k.a Higher- Order function Only the function definition is passed; function is not executed A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain • When callback is invoked, if there is a ‘this’ reference; it will be ‘undefined’ • Handling ‘this’ in a callback is via JS methods of ‘apply(..)’ or ‘call(..)’ OR • Have the ‘this’ stored in a variable called ‘self’ and use it.
  • 7. 7 Event Driven Programming – Blocking, Non-Blocking I/O s1 s2 s3 s4 s5 Traditional I/O Non-blocking I/O var result = db.query(“select x,y from tableXY”); doSomethingWithResult(result); //waits for the result! doSomethingWithoutResult(); //execution is un-necessarily blocked! db.query(“select x, y from tableXY”, function (result){ // gets called once the result is ready! doSomethingWithResult(result); }); doSomethingWithoutResult(); //executes without any delay! Callback on db query completion event
  • 8. 8 Fundamentals – Modules, Sample Code • Modules • Referenced by file path or file name • No Global Scope in NodeJS • Modules are loaded only once • Libraries in node are packages/modules Module 1 Module s5 s1 s2 s3 s4 s1 s2 Global Scope Scripts within a module context • Sample – Web Server in 3 lines Classic Browser Runtime Node Runtime & Scope s3 s4 s5 Loads the ‘http’ module Function that handles the incoming requests. Executed by the main thread of node.
  • 9. Multi-Threaded HTTP Server – Blocking I/O • On heavy load – we see more threads that leads to more context switching which in turn leads to more CPU / Memory usage • Classic discussion on threads vs. events is in Benjamin Erb’s Thesis [Strongloop, 2014]
  • 10. Node JS Architecture – Non-Blocking I/O • On heavy load – we see more threads that leads to more context switching which in turn leads to more CPU / Memory usage • Classic discussion on threads vs. events is in Benjamin Erb’s Thesis [Strongloop, 2014]
  • 11. Node JS – Event Loop • Node is single-threaded • Follows an event-driven functional programming model • Errors in the main thread kills the server • POSIX thread switching is not costly Million concurrent connections http://blog.caustik.com/2012/08/19/node-js-w1m-concurrent-connections/ [www.udemy.com, 2014]
  • 12. Node JS – Event Loop Client Event loop (main thread) C++ Thread pool (worker threads) Clients send HTTP requests to Node.js server An Event-loop is woken up by OS, passes request and response objects to the thread-pool Long-running jobs run on worker threads Response is sent back to main thread via callback Event loop returns result to client • Node is single-threaded • Follows an event-driven functional programming model • Errors in the main thread kills the server Million concurrent connections http://blog.caustik.com/2012/08/19/node-js-w1m-concurrent-connections/
  • 13. Java vs. NodeJS –Performance [ Return data with constant sleep] Java Stack & Description • Java servlet returns ‘hello world’ with a 200ms sleep [ simulating a 200ms DB call] • Executed in Apache Tomcat 6.0, JDK 6 • Tomcat runs in a multi-threaded mode & in a blocking mode Node v 0.10 • Returns a ‘hello world’ equivalent string with a 200ms timeout set in call • Node JS ran in the (defacto) non-blocking mode Not a comparison between Java vs. Node – rather a comparison of blocking and non- blocking I/O
  • 14. Node JS – Run Sample Web Application • Use cases we will see • Get the list of players from NoSQL (MongoDB) • Add a player to the list • STEP 1 – setup • Install Node • Install Express • Install Expres – Genertor • Generate a node express project • Install MongoDB • STEP 2 – Package.json edit to suit your needs • STEP 3 – Install dependencies • STEP 4 – Run d:nodejs> npm install express d:nodejs> npm install express-generator d:nodejs> express playerlist d:nodejsplayerlist> npm install d:nodejsplayerlist> npm start
  • 15. Node JS – Project Structure Jade HTML Preprocessor Express Engine Mongo DB Monk Node.js Server d:nodejs> npm install express d:nodejs> npm install express-generator d:nodejs> express playerlist V M C Public images, CSS and JS files URI routing; view attachment View templates using Jade. Multiple other options exists – ejs, jade Mongo DB Data files • Jade – Template engine. Very short syntax to create a HTML • Monk – Small layer that enables MongoDB a super-easy task within NodeJS
  • 16. Node JS – Code Parts – MVC 1) Import necessary modules 2) Initialize Express 3) Configure the express app a. Logger b. Views c. Template engine d. Static images directory e. … 4) Configure the router 5) Router = Controller a. Connects the model, jade view b. Enables navigation across the URIs
  • 17. Node JS – UI Template • Jade is a server side templating engine – like Thymeleaf, JSP, ASP • Short syntax to create HTML
  • 18. Node JS – Code Parts contd. • Router • Database View: Jade template name View Model: “Model of the view” JSON object passed to the view 1 2 3 Load ‘Mongo’, ‘Monk’ necessary to connect to MongoDB Put the Mongo DB reference handle to the global request object db.get - Monk APIs to fetch db.insert,db.find({},fn) are some of the other relevant APIs
  • 19. Node JS – Deployment • Simplistic – Newbie mode • node server.js • Command line execution. No restart; or no monitoring • Dies with the command shell closing • Little better • node server.js & • Running as a background application in *nix • Will last than the shell that started it • Script that loops & restarts the server • Still limited the lifeline of the script that starts • Improvised shell • Cron based monitoring • Log attached • Auto start enabled • External port monitoring enabled for load balancing While : do // node server.js // sleep x seconds done // description // author // specify port, Ethernet card // attach a cron job – for every minute // start in sudo mode // ensure a log file is rolled // attached the init.d in linux
  • 20. 20 Industry Adoption Paypal’s Account Overview via NodeJS • Timeline & Inventory • Built twice as fast as the Java Application • 33% fewer lines of code – compared to the same functionality in Java /Spring • 40% fewer files • Performance • Double the requests vs. Java Application • 35% decrease in the average response time • Essentially, page loading is faster than the Java App • Stack • NodeJS – Server • KrakenJS – Secure and scalable layer that extends Express, which provides convention • Dust – Asynchronous templates
  • 21. 21 Pros & Cons Pros • Fast – Execution speed • Faster to market – development speed • Less lines of code • Great community • Proven with high volume systems • Most suited for networking, I/O intensive applications Cons • Writing event driven code is complex compared to synchronous code • Writing a large business logic centric system is cumbersome • Callback hell • Exception handling is not straight forward
  • 22. 22 Suitability Suitable Scenarios • Most suited for networking, I/O intensive applications • Applications that need high concurrency / Queued concurrent inputs • Streaming Applications – like Chat servers • Proxy Service • Real time applications • Monitoring Dashboards • like Brokerage Dashboard (Node JS + Socket IO) • Application Monitoring • REST APIs Not Suited For • Large business logic centric systems • Heavy server side computation is required
  • 23. Next Session • File handlers, Streams • Event Emitters • Error, Exception Handling • Socket.IO • Build & Deploy – using Grunt • JS CoE – Seed project for node
  • 25. Reference • Ryan Dhals original presentation in JS Conf http://s3.amazonaws.com/four.livejournal/20091117/jsconf.pdf • Expess framework • http://expressjs.com/guide.htmld • Node JS - www.nodejs.org • Event Loop – www.udemy.com • Strongloop – how nodejs is faster http://strongloop.com/strongblog/node-js-is-faster-than-java/
  • 28. Why Node JS is faster [ Return data with constant sleep] • Asynchronous Non-blocking I/O is the root cause • Not just I/O alone – all of node js 50k modules are written in an async fashion • Debuggers, monitors, loggers, • Cluster manager • File operation • Java NIO alone is not enough