SlideShare a Scribd company logo
1 of 32
Exploring Node.JS 
Dr. Jayaraj Poroor 
DependSoft Consulting 
http://dependsoft.com
About DependSoft
My ongoing R&D work: IntegralJ 
http://integralj.org (open source)
My recent products 
● Virtual Private Transport 
o Keyhole approach to secure remote service access. 
o http://shelloid.com 
o Node.js, Netty, Redis, MySQL, Google protobuf. 
o Basic engine open sourced. 
● Sensoid IoT platform 
o Distributed stream query platform. 
o Node.js, Redis, InfluxDB, ElasticSearch, MySQL.
Server-side technology requirements 
● Performance 
o Need optimized execution 
● Concurrency 
o Need to support many concurrent client requests 
● Library support 
o e.g., database interfacing. 
● Framework support 
o For rapid application development.
Node.JS 
● Performance 
o Google’s V8 VM with native JIT compilation 
● Concurrency 
o Asynchronous I/O (libuv) + clustering 
● Library support 
o 39K projects in Github 
● Framework support 
o e.g., Express.JS
Synchronous vs Asynchronous I/O 
● Synchronous I/O 
o Thread blocks till I/O request is complete. 
o e.g., $result = mysql_query(“....”); //PHP 
● Asynchronous I/O 
o Thread does not block 
o Uses callback mechanism to notify completion 
o e.g., conn.query(“...”, function(err, rows) 
{ } );
Node.JS Threading model 
1. Single computational thread 
o Non-blocking, interleaved request processing 
o Background worker threads for I/O processing 
1. Clustering to utilize multi-core machines 
2. No shared memory between cluster processes.
Node.JS : When to use 
● Great for 
o I/O-centric applications 
 e.g., DB queries, File I/O , network I/O, invocation of 
other web services. 
o Real-time communication 
 WebSockets, HTTP long polling 
● Not so great for 
o Compute-centric applications 
 e.g., High-end machine learning backend
Event Loop Illustrated 
http://www.geekgirl.io/understanding-the-event-loop-in-nodejs/
Anatomy of a “hello world” Node.js 
var http = require('http'); 
var server = 
http.createServer(function (req, res) { 
res.writeHead(200, 
{'Content-Type': 'text/html'}); 
res.end('<h1>Hello World</h1>'); 
}); 
server.listen(3000); 
No separate HTTP 
engine like Apache 
required. 
Command: 
node app.js
Serving a file 
Buffers the entire file in memory. 
●Inefficient for large files. 
●Client needs to wait till entire file is 
read. 
Code source: https://github.com/substack/stream-handbook
Node.js Streams 
● Data served in 
chunks. 
● Data event fires 
whenever a new 
chunk is ready. 
Code source: Node.js in Action
Streams can be piped! 
File stream (input) is piped to the 
response stream (output). 
The response will employ 
chunked Transfer-Encoding. 
Code source: https://github.com/substack/stream-handbook
Package management 
● npm (Node Package Manager) 
o Provides simple & powerful package management. 
o Reads module dependencies from package.json 
o Typical usage: npm install or npm update. 
o Can store all dependent modules locally or globally
A sample package.json 
{ 
"name": "SomeApp", 
"description": "SomeApp Web Application", 
"version": "0.0.1", 
"private": true, 
"dependencies": { 
"express": "3.6.0", 
"connect": "2.15.0", 
"mysql": "*", 
} 
}
Secure HTTP with Node.js 
Code source: Node.js in Action 
Key and certificate files 
provided. 
Use gpg, openssl etc. to 
generate key and CSR.
Connect framework: Modular web apps 
Source: Node.js in Action 
Install: 
npm install connect
Connect: usage 
Create a Connect ‘app’. 
●Will store all middleware. 
●Itself just a function. 
Create a middleware ‘stack’. 
Requests will execute 
middleware functions till 
‘next()’ is not called or end of 
stack is reached. 
Code source: https://www.npmjs.org/package/connect
Connect: usage (2) 
● Middleware can be 
mounted on specific URL 
endpoints. 
● Does basic routing. 
● Error handler 
middleware. 
OR 
Create Connect-enabled 
server. 
Code source: https://www.npmjs.org/package/connect
Example Connect middlewares
Serving static files 
Static middleware 
configured with the 
folder from which 
files are served.
Express: Lightweight web framework 
Routing 
Code Source: https://www.npmjs.org/package/express
Bootstrapping Express application 
express – e output
Rendering views with Express 
Code Source: Node.js in Action 
Express configured 
with the views 
folder. 
View engine set as 
ejs. 
Looks up index.ejs 
in the views folder.
View lookup 
Source: Node.js in Action 
Source: Node.js in Action
Passing data to views 
Data passed to the 
view. 
photos is an array.
An example view 
title 
variable 
accessed. 
photos array 
accessed here.
Database connectivity 
npm install mysql 
var mysql = require('mysql'); 
var connection = mysql.createConnection({ 
host : 'localhost', 
user : 'me', 
password : 'secret' 
}); 
connection.connect(); 
connection.query('...', function(err, rows, fields) { 
if (err) throw err; 
connection.end(); 
}); 
https://github.com/felixge/node-mysql 
npms 
available for 
virtually any 
SQL/NoSQL 
database! 
Query completes 
only when the 
callback is invoked!
Authentication 
● passport.js 
npm install passport 
o Authentication middleware for node.js. 
o 140+ authentication strategies. 
o Supports OpenID and OAuth 
o http://passportjs.org 
o Session data can be serialized into a store like Redis.
Read more 
● Node.js in Action 
● http://expressjs.com 
● http://www.nodebeginner.org/
Thank You 
Dr. Jayaraj Poroor 
Founder, DependSoft Consulting 
Peace of mind with dependable software. 
jayaraj@dependsoft.com 
http://dependsoft.com

More Related Content

What's hot

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
HTML5 Programming
HTML5 ProgrammingHTML5 Programming
HTML5 Programming
hotrannam
 

What's hot (20)

Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Node js crash course session 2
Node js crash course   session 2Node js crash course   session 2
Node js crash course session 2
 
Node.js
Node.jsNode.js
Node.js
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
Getting started with developing Nodejs
Getting started with developing NodejsGetting started with developing Nodejs
Getting started with developing Nodejs
 
How to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita GalkinHow to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita Galkin
 
A slightly advanced introduction to node.js
A slightly advanced introduction to node.jsA slightly advanced introduction to node.js
A slightly advanced introduction to node.js
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
HTML5 Programming
HTML5 ProgrammingHTML5 Programming
HTML5 Programming
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Node.js
Node.jsNode.js
Node.js
 
PostgreSQL Sharding and HA: Theory and Practice (PGConf.ASIA 2017)
PostgreSQL Sharding and HA: Theory and Practice (PGConf.ASIA 2017)PostgreSQL Sharding and HA: Theory and Practice (PGConf.ASIA 2017)
PostgreSQL Sharding and HA: Theory and Practice (PGConf.ASIA 2017)
 
OpenStack API's and WSGI
OpenStack API's and WSGIOpenStack API's and WSGI
OpenStack API's and WSGI
 
Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.
 
Node Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js TutorialNode Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js Tutorial
 
NodeJS Concurrency
NodeJS ConcurrencyNodeJS Concurrency
NodeJS Concurrency
 
MongoDB WiredTiger Internals
MongoDB WiredTiger InternalsMongoDB WiredTiger Internals
MongoDB WiredTiger Internals
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
 

Viewers also liked

Getting ready for the cloud iaa s
Getting ready for the cloud iaa sGetting ready for the cloud iaa s
Getting ready for the cloud iaa s
Deepu S Nath
 
Security testing addons
Security testing addonsSecurity testing addons
Security testing addons
Deepu S Nath
 

Viewers also liked (14)

Getting ready for the cloud iaa s
Getting ready for the cloud iaa sGetting ready for the cloud iaa s
Getting ready for the cloud iaa s
 
Coffee@DBG - Evolution of html
Coffee@DBG - Evolution of htmlCoffee@DBG - Evolution of html
Coffee@DBG - Evolution of html
 
Cross Device UI Designing
Cross Device UI DesigningCross Device UI Designing
Cross Device UI Designing
 
Coffee@DBG - TechBites Sept 2015
Coffee@DBG - TechBites Sept 2015Coffee@DBG - TechBites Sept 2015
Coffee@DBG - TechBites Sept 2015
 
Tech bites
Tech bitesTech bites
Tech bites
 
Security testing addons
Security testing addonsSecurity testing addons
Security testing addons
 
Saa s
Saa sSaa s
Saa s
 
Front end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen VijayanFront end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen Vijayan
 
SEO For Developers
SEO For DevelopersSEO For Developers
SEO For Developers
 
Coffee@DBG - TechBites March 2016
Coffee@DBG - TechBites March 2016Coffee@DBG - TechBites March 2016
Coffee@DBG - TechBites March 2016
 
Advanced visualization
Advanced visualizationAdvanced visualization
Advanced visualization
 
Coffee@DBG - New CSS3 properties
Coffee@DBG  - New CSS3 propertiesCoffee@DBG  - New CSS3 properties
Coffee@DBG - New CSS3 properties
 
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
 
Microsoft ALM Support - Testing Perspective
Microsoft ALM Support - Testing PerspectiveMicrosoft ALM Support - Testing Perspective
Microsoft ALM Support - Testing Perspective
 

Similar to Exploring Node.jS

Similar to Exploring Node.jS (20)

An introduction to Node.js application development
An introduction to Node.js application developmentAn introduction to Node.js application development
An introduction to Node.js application development
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Introduction to node.js By Ahmed Assaf
Introduction to node.js  By Ahmed AssafIntroduction to node.js  By Ahmed Assaf
Introduction to node.js By Ahmed Assaf
 
BaseX user-group-talk XML Prague 2013
BaseX user-group-talk XML Prague 2013BaseX user-group-talk XML Prague 2013
BaseX user-group-talk XML Prague 2013
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Nodejs
NodejsNodejs
Nodejs
 
Building Applications With the MEAN Stack
Building Applications With the MEAN StackBuilding Applications With the MEAN Stack
Building Applications With the MEAN Stack
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questions
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Nodejs
NodejsNodejs
Nodejs
 
Kubernetes for the PHP developer
Kubernetes for the PHP developerKubernetes for the PHP developer
Kubernetes for the PHP developer
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to Node.JS
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 

More from Deepu S Nath

Greetings & Response - English Communication Training
Greetings & Response - English Communication TrainingGreetings & Response - English Communication Training
Greetings & Response - English Communication Training
Deepu S Nath
 

More from Deepu S Nath (20)

Design Thinking, Critical Thinking & Innovation Design
Design Thinking, Critical Thinking & Innovation DesignDesign Thinking, Critical Thinking & Innovation Design
Design Thinking, Critical Thinking & Innovation Design
 
GTECH ATFG µLearn Framework Intro
GTECH ATFG µLearn Framework IntroGTECH ATFG µLearn Framework Intro
GTECH ATFG µLearn Framework Intro
 
Future of learning - Technology Disruption
Future of learning  - Technology DisruptionFuture of learning  - Technology Disruption
Future of learning - Technology Disruption
 
Decentralized Applications using Ethereum
Decentralized Applications using EthereumDecentralized Applications using Ethereum
Decentralized Applications using Ethereum
 
How machines can take decisions
How machines can take decisionsHow machines can take decisions
How machines can take decisions
 
Artificial Intelligence: An Introduction
 Artificial Intelligence: An Introduction Artificial Intelligence: An Introduction
Artificial Intelligence: An Introduction
 
FAYA PORT 80 Introduction
FAYA PORT 80 IntroductionFAYA PORT 80 Introduction
FAYA PORT 80 Introduction
 
How machines can take decisions
How machines can take decisionsHow machines can take decisions
How machines can take decisions
 
Simplified Introduction to AI
Simplified Introduction to AISimplified Introduction to AI
Simplified Introduction to AI
 
Mining Opportunities of Block Chain and BitCoin
Mining Opportunities of Block Chain and BitCoinMining Opportunities of Block Chain and BitCoin
Mining Opportunities of Block Chain and BitCoin
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOps
 
REACT.JS : Rethinking UI Development Using JavaScript
REACT.JS : Rethinking UI Development Using JavaScriptREACT.JS : Rethinking UI Development Using JavaScript
REACT.JS : Rethinking UI Development Using JavaScript
 
Life Cycle of an App - From Idea to Monetization
Life Cycle of an App - From Idea to Monetization  Life Cycle of an App - From Idea to Monetization
Life Cycle of an App - From Idea to Monetization
 
Uncommon Python - What is special in Python
Uncommon Python -  What is special in PythonUncommon Python -  What is special in Python
Uncommon Python - What is special in Python
 
Techbites July 2015
Techbites July 2015Techbites July 2015
Techbites July 2015
 
Apple Watch - Start Your Developer Engine
Apple Watch -  Start Your Developer EngineApple Watch -  Start Your Developer Engine
Apple Watch - Start Your Developer Engine
 
Greetings & Response - English Communication Training
Greetings & Response - English Communication TrainingGreetings & Response - English Communication Training
Greetings & Response - English Communication Training
 
Hybrid Mobile App Development - Xamarin
Hybrid Mobile App Development - XamarinHybrid Mobile App Development - Xamarin
Hybrid Mobile App Development - Xamarin
 
Internet of Things - The new Paradigmn
Internet of Things - The new ParadigmnInternet of Things - The new Paradigmn
Internet of Things - The new Paradigmn
 
Comparing Swift features with Objective C
Comparing Swift features with Objective CComparing Swift features with Objective C
Comparing Swift features with Objective C
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Exploring Node.jS

  • 1. Exploring Node.JS Dr. Jayaraj Poroor DependSoft Consulting http://dependsoft.com
  • 3. My ongoing R&D work: IntegralJ http://integralj.org (open source)
  • 4. My recent products ● Virtual Private Transport o Keyhole approach to secure remote service access. o http://shelloid.com o Node.js, Netty, Redis, MySQL, Google protobuf. o Basic engine open sourced. ● Sensoid IoT platform o Distributed stream query platform. o Node.js, Redis, InfluxDB, ElasticSearch, MySQL.
  • 5. Server-side technology requirements ● Performance o Need optimized execution ● Concurrency o Need to support many concurrent client requests ● Library support o e.g., database interfacing. ● Framework support o For rapid application development.
  • 6. Node.JS ● Performance o Google’s V8 VM with native JIT compilation ● Concurrency o Asynchronous I/O (libuv) + clustering ● Library support o 39K projects in Github ● Framework support o e.g., Express.JS
  • 7. Synchronous vs Asynchronous I/O ● Synchronous I/O o Thread blocks till I/O request is complete. o e.g., $result = mysql_query(“....”); //PHP ● Asynchronous I/O o Thread does not block o Uses callback mechanism to notify completion o e.g., conn.query(“...”, function(err, rows) { } );
  • 8. Node.JS Threading model 1. Single computational thread o Non-blocking, interleaved request processing o Background worker threads for I/O processing 1. Clustering to utilize multi-core machines 2. No shared memory between cluster processes.
  • 9. Node.JS : When to use ● Great for o I/O-centric applications  e.g., DB queries, File I/O , network I/O, invocation of other web services. o Real-time communication  WebSockets, HTTP long polling ● Not so great for o Compute-centric applications  e.g., High-end machine learning backend
  • 10. Event Loop Illustrated http://www.geekgirl.io/understanding-the-event-loop-in-nodejs/
  • 11. Anatomy of a “hello world” Node.js var http = require('http'); var server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('<h1>Hello World</h1>'); }); server.listen(3000); No separate HTTP engine like Apache required. Command: node app.js
  • 12. Serving a file Buffers the entire file in memory. ●Inefficient for large files. ●Client needs to wait till entire file is read. Code source: https://github.com/substack/stream-handbook
  • 13. Node.js Streams ● Data served in chunks. ● Data event fires whenever a new chunk is ready. Code source: Node.js in Action
  • 14. Streams can be piped! File stream (input) is piped to the response stream (output). The response will employ chunked Transfer-Encoding. Code source: https://github.com/substack/stream-handbook
  • 15. Package management ● npm (Node Package Manager) o Provides simple & powerful package management. o Reads module dependencies from package.json o Typical usage: npm install or npm update. o Can store all dependent modules locally or globally
  • 16. A sample package.json { "name": "SomeApp", "description": "SomeApp Web Application", "version": "0.0.1", "private": true, "dependencies": { "express": "3.6.0", "connect": "2.15.0", "mysql": "*", } }
  • 17. Secure HTTP with Node.js Code source: Node.js in Action Key and certificate files provided. Use gpg, openssl etc. to generate key and CSR.
  • 18. Connect framework: Modular web apps Source: Node.js in Action Install: npm install connect
  • 19. Connect: usage Create a Connect ‘app’. ●Will store all middleware. ●Itself just a function. Create a middleware ‘stack’. Requests will execute middleware functions till ‘next()’ is not called or end of stack is reached. Code source: https://www.npmjs.org/package/connect
  • 20. Connect: usage (2) ● Middleware can be mounted on specific URL endpoints. ● Does basic routing. ● Error handler middleware. OR Create Connect-enabled server. Code source: https://www.npmjs.org/package/connect
  • 22. Serving static files Static middleware configured with the folder from which files are served.
  • 23. Express: Lightweight web framework Routing Code Source: https://www.npmjs.org/package/express
  • 24. Bootstrapping Express application express – e output
  • 25. Rendering views with Express Code Source: Node.js in Action Express configured with the views folder. View engine set as ejs. Looks up index.ejs in the views folder.
  • 26. View lookup Source: Node.js in Action Source: Node.js in Action
  • 27. Passing data to views Data passed to the view. photos is an array.
  • 28. An example view title variable accessed. photos array accessed here.
  • 29. Database connectivity npm install mysql var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret' }); connection.connect(); connection.query('...', function(err, rows, fields) { if (err) throw err; connection.end(); }); https://github.com/felixge/node-mysql npms available for virtually any SQL/NoSQL database! Query completes only when the callback is invoked!
  • 30. Authentication ● passport.js npm install passport o Authentication middleware for node.js. o 140+ authentication strategies. o Supports OpenID and OAuth o http://passportjs.org o Session data can be serialized into a store like Redis.
  • 31. Read more ● Node.js in Action ● http://expressjs.com ● http://www.nodebeginner.org/
  • 32. Thank You Dr. Jayaraj Poroor Founder, DependSoft Consulting Peace of mind with dependable software. jayaraj@dependsoft.com http://dependsoft.com