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
Ad

More Related Content

What's hot (20)

Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
Erik van Appeldoorn
 
Node ppt
Node pptNode ppt
Node ppt
Tamil Selvan R S
 
Node js
Node jsNode js
Node js
Fatih Şimşek
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)
iFour Technolab Pvt. Ltd.
 
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!
 
Nodejs vatsal shah
Nodejs vatsal shahNodejs vatsal shah
Nodejs vatsal shah
Vatsal N Shah
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
Nodejs Session01
Nodejs Session01Nodejs Session01
Nodejs Session01
Jainul Musani
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
AMD Developer Central
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Rob O'Doherty
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
Arvind Devaraj
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
monikadeshmane
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
Simplilearn
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
Chris Cowan
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
Enoch Joshua
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
Arjun Sreekumar
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
Rafael Casuso Romate
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)
iFour Technolab Pvt. Ltd.
 
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!
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Rob O'Doherty
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
monikadeshmane
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
Simplilearn
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
Chris Cowan
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
Enoch Joshua
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
Rafael Casuso Romate
 

Viewers also liked (20)

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
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
NodejsFoundation
 
Node js
Node jsNode js
Node js
Rohan Chandane
 
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
Knonex
knonex software development
 
Node js overview
Node js overviewNode js overview
Node js overview
Eyal Vardi
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
Mohammad Qureshi
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
christkv
 
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
 
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 – 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
 
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
 
Node js overview
Node js overviewNode js overview
Node js overview
Eyal Vardi
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
Mohammad Qureshi
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
christkv
 
Ad

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
 
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 - NodeJS
Tim 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
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
Richard Rodger
 
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
 
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
 
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
 
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
 
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 - NodeJS
Tim Sommer
 
node_js.pptx
node_js.pptxnode_js.pptx
node_js.pptx
dipen55
 
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
 
Ad

Recently uploaded (20)

Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Adobe Photoshop CC 2025 Crack Full Serial Key With Latest
Adobe Photoshop CC 2025 Crack Full Serial Key  With LatestAdobe Photoshop CC 2025 Crack Full Serial Key  With Latest
Adobe Photoshop CC 2025 Crack Full Serial Key With Latest
usmanhidray
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Salesforce Aged Complex Org Revitalization Process .pdf
Salesforce Aged Complex Org Revitalization Process .pdfSalesforce Aged Complex Org Revitalization Process .pdf
Salesforce Aged Complex Org Revitalization Process .pdf
SRINIVASARAO PUSULURI
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Sales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptxSales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptx
EliandoLawnote
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Mastering OOP: Understanding the Four Core Pillars
Mastering OOP: Understanding the Four Core PillarsMastering OOP: Understanding the Four Core Pillars
Mastering OOP: Understanding the Four Core Pillars
Marcel David
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Adobe Photoshop CC 2025 Crack Full Serial Key With Latest
Adobe Photoshop CC 2025 Crack Full Serial Key  With LatestAdobe Photoshop CC 2025 Crack Full Serial Key  With Latest
Adobe Photoshop CC 2025 Crack Full Serial Key With Latest
usmanhidray
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Salesforce Aged Complex Org Revitalization Process .pdf
Salesforce Aged Complex Org Revitalization Process .pdfSalesforce Aged Complex Org Revitalization Process .pdf
Salesforce Aged Complex Org Revitalization Process .pdf
SRINIVASARAO PUSULURI
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Sales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptxSales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptx
EliandoLawnote
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Mastering OOP: Understanding the Four Core Pillars
Mastering OOP: Understanding the Four Core PillarsMastering OOP: Understanding the Four Core Pillars
Mastering OOP: Understanding the Four Core Pillars
Marcel David
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 

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