SlideShare une entreprise Scribd logo
1  sur  28
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

Contenu connexe

Tendances (20)

Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Node.js
Node.jsNode.js
Node.js
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node js
Node jsNode js
Node js
 
Node js introduction
Node js introductionNode js introduction
Node js 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
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Presentation of framework Angular
Presentation of framework AngularPresentation of framework Angular
Presentation of framework Angular
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Node.js Basics
Node.js Basics Node.js Basics
Node.js Basics
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
 
Vue.js
Vue.jsVue.js
Vue.js
 
MongoDB and Node.js
MongoDB and Node.jsMongoDB and Node.js
MongoDB and Node.js
 
Swagger
SwaggerSwagger
Swagger
 

En vedette

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 20160907NodejsFoundation
 
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 azureColin Mackay
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applicationsSergi Mansilla
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.jsRyan 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 BergenhemFITC
 
Business considerations for node.js applications
Business considerations for node.js applicationsBusiness considerations for node.js applications
Business considerations for node.js applicationsAspenware
 
Pengenalan Dasar NodeJS
Pengenalan Dasar NodeJSPengenalan Dasar NodeJS
Pengenalan Dasar NodeJSalfi 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/OBuzzcapture
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0Ganesh Kondal
 
Node js overview
Node js overviewNode js overview
Node js overviewEyal Vardi
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriverchristkv
 

En vedette (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
 
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
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
 

Similaire à Node.js Server Side JavaScript Overview

PHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web DevelopmentPHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web DevelopmentIrfan Maulana
 
Irfan maulana nodejs web development
Irfan maulana   nodejs web developmentIrfan maulana   nodejs web development
Irfan maulana nodejs web developmentPHP Indonesia
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdfBareen Shaikh
 
A Journey Begin with Node.js
A Journey Begin with Node.jsA Journey Begin with Node.js
A Journey Begin with Node.jsKhalid Farhan
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.jsKasey McCurdy
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Ganesh Kondal
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJSJITENDRA KUMAR PATEL
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystemYukti Kaura
 
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 MongoDBValeri Karpov
 
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 APIAll Things Open
 
T4T Training day - NodeJS
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJSTim Sommer
 
node_js.pptx
node_js.pptxnode_js.pptx
node_js.pptxdipen55
 
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 JSbrendankowitz
 

Similaire à Node.js Server Side JavaScript Overview (20)

PHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web DevelopmentPHP Indonesia - Nodejs Web Development
PHP Indonesia - Nodejs Web Development
 
Irfan maulana nodejs web development
Irfan maulana   nodejs web developmentIrfan maulana   nodejs web development
Irfan maulana 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
 
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
 
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
 
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
 

Dernier

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 

Dernier (20)

Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 

Node.js Server Side JavaScript Overview

  • 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