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 (20)

PPTX
Express js
Manav Prasad
 
PDF
Express node js
Yashprit Singh
 
PPTX
Introduction to Node.js
Vikash Singh
 
PDF
Introduction to Node.js
Rob O'Doherty
 
PPTX
Introduction Node.js
Erik van Appeldoorn
 
PPTX
Intro to Node.js (v1)
Chris Cowan
 
PPTX
[Final] ReactJS presentation
洪 鹏发
 
PPTX
What Is Express JS?
Simplilearn
 
PPTX
Rest api with node js and express
GirlsInTechnology Nepal
 
PPTX
Node js introduction
Joseph de Castelnau
 
PPTX
jQuery
Jay Poojara
 
PPTX
React workshop presentation
Bojan Golubović
 
PPTX
NodeJS guide for beginners
Enoch Joshua
 
PPT
React native
Mohammed El Rafie Tarabay
 
PDF
Fundamental of Node.JS - Internship Presentation - Week7
Devang Garach
 
PPTX
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
PPTX
Introduction to Node.js
AMD Developer Central
 
PDF
Arquitetura Node com NestJS
Vanessa Me Tonini
 
PPTX
Node.js Express
Eyal Vardi
 
PPTX
React state
Ducat
 
Express js
Manav Prasad
 
Express node js
Yashprit Singh
 
Introduction to Node.js
Vikash Singh
 
Introduction to Node.js
Rob O'Doherty
 
Introduction Node.js
Erik van Appeldoorn
 
Intro to Node.js (v1)
Chris Cowan
 
[Final] ReactJS presentation
洪 鹏发
 
What Is Express JS?
Simplilearn
 
Rest api with node js and express
GirlsInTechnology Nepal
 
Node js introduction
Joseph de Castelnau
 
jQuery
Jay Poojara
 
React workshop presentation
Bojan Golubović
 
NodeJS guide for beginners
Enoch Joshua
 
Fundamental of Node.JS - Internship Presentation - Week7
Devang Garach
 
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
Introduction to Node.js
AMD Developer Central
 
Arquitetura Node com NestJS
Vanessa Me Tonini
 
Node.js Express
Eyal Vardi
 
React state
Ducat
 

Viewers also liked (20)

PDF
Anatomy of a Modern Node.js Application Architecture
AppDynamics
 
PDF
Node Foundation Membership Overview 20160907
NodejsFoundation
 
PDF
Node js
Rohan Chandane
 
PDF
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
PDF
All aboard the NodeJS Express
David Boyer
 
PDF
Architecting large Node.js applications
Sergi Mansilla
 
PDF
Modern UI Development With Node.js
Ryan Anklam
 
KEY
Node.js - Best practices
Felix Geisendörfer
 
PDF
Intro to node.js web apps
Thanos Polychronakis
 
PDF
Node.js – ask us anything!
Dev_Events
 
PDF
Building A Web App In 100% JavaScript with Carl Bergenhem
FITC
 
PDF
Intro to node.js
Thanos Polychronakis
 
PDF
Business considerations for node.js applications
Aspenware
 
PPTX
Pengenalan Dasar NodeJS
alfi setyadi
 
PDF
Python meetup: coroutines, event loops, and non-blocking I/O
Buzzcapture
 
PPTX
Test driven development v1.0
Ganesh Kondal
 
PPTX
Node js overview
Eyal Vardi
 
PPTX
Intro to node and mongodb 1
Mohammad Qureshi
 
KEY
Node js mongodriver
christkv
 
Anatomy of a Modern Node.js Application Architecture
AppDynamics
 
Node Foundation Membership Overview 20160907
NodejsFoundation
 
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
All aboard the NodeJS Express
David Boyer
 
Architecting large Node.js applications
Sergi Mansilla
 
Modern UI Development With Node.js
Ryan Anklam
 
Node.js - Best practices
Felix Geisendörfer
 
Intro to node.js web apps
Thanos Polychronakis
 
Node.js – ask us anything!
Dev_Events
 
Building A Web App In 100% JavaScript with Carl Bergenhem
FITC
 
Intro to node.js
Thanos Polychronakis
 
Business considerations for node.js applications
Aspenware
 
Pengenalan Dasar NodeJS
alfi setyadi
 
Python meetup: coroutines, event loops, and non-blocking I/O
Buzzcapture
 
Test driven development v1.0
Ganesh Kondal
 
Node js overview
Eyal Vardi
 
Intro to node and mongodb 1
Mohammad Qureshi
 
Node js mongodriver
christkv
 
Ad

Similar to NodeJS - Server Side JS (20)

PPTX
Nodejs
Vinod Kumar Marupu
 
PPTX
An overview of node.js
valuebound
 
PPTX
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
ODP
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
PPT
Introduction to node.js aka NodeJS
JITENDRA KUMAR PATEL
 
PPTX
Introduction to node.js by jiban
Jibanananda Sana
 
PPTX
Proposal
Constantine Priemski
 
PPTX
Beginners Node.js
Khaled Mosharraf
 
PPT
18_Node.js.ppt
KhalilSalhi7
 
PDF
Introduction to Node.js
Aaron Rosenberg
 
PDF
Node.js for beginner
Sarunyhot Suwannachoti
 
PPT
18_Node.js.ppt
MaulikShah516542
 
PDF
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
PPTX
Node js
Fatih Şimşek
 
PPT
Node.js
Neethu Dasan
 
PPTX
Introduction to node.js GDD
Sudar Muthu
 
PDF
Node.js Web Development .pdf
Abanti Aazmin
 
PPTX
Node.js & Express.js Unleashed
Elewayte
 
PPTX
Nodejs intro
Ndjido Ardo BAR
 
PPTX
Web with Nodejs
Naman Gupta
 
An overview of node.js
valuebound
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Introduction to node.js aka NodeJS
JITENDRA KUMAR PATEL
 
Introduction to node.js by jiban
Jibanananda Sana
 
Beginners Node.js
Khaled Mosharraf
 
18_Node.js.ppt
KhalilSalhi7
 
Introduction to Node.js
Aaron Rosenberg
 
Node.js for beginner
Sarunyhot Suwannachoti
 
18_Node.js.ppt
MaulikShah516542
 
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
Node.js
Neethu Dasan
 
Introduction to node.js GDD
Sudar Muthu
 
Node.js Web Development .pdf
Abanti Aazmin
 
Node.js & Express.js Unleashed
Elewayte
 
Nodejs intro
Ndjido Ardo BAR
 
Web with Nodejs
Naman Gupta
 
Ad

Recently uploaded (20)

PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Executive Business Intelligence Dashboards
vandeslie24
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 

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