(Go: >> BACK << -|- >> HOME <<)

SlideShare a Scribd company logo
A K S H A Y M A T H U R
@AKSHAYMATHU
Getting Started with
Ground Rules
@akshaymathu
2
 Post on FB and Tweet now
 Disturb Everyone during the
session
 Not by phone rings
 Not by local talks
 By more information and
questions
Let’s Know Each Other
@akshaymathu
3
 Do you code?
 OS?
 Node?
 JavaScript, JSON?
 Web Development?
 CoffeeScript
 Other Programing Language?
 Why are you attending?
Akshay Mathur
@akshaymathu
4
 Founding Team Member of
 ShopSocially (Enabling “social” for retailers)
 AirTight Neworks (Global leader of WIPS)
 15+ years in IT industry
 Currently Principal Architect at ShopSocially
 Mostly worked with Startups
 From Conceptualization to Stabilization
 At different functions i.e. development, testing, release
 With multiple technologies
JavaScript
@akshaymathu
5
 Born in 1995 at Netscape
 Not at all related to Java
 Syntax influenced by C
 Interpreted ECMA scripting language
 Dynamically typed
 Object Oriented as well as Functional
 Prototype based
Typical Usage
@akshaymathu
6
 Web programing
 Client side
 Web pages
 Browser plugins
 Server side
 SSJS (not in use)
 NodeJS
 PDF documents
 Desktop Widgets
 MongoDB
NodeJS
 JavaScript Runtime at command line
 Allows us to write JS programs outside browser
 Built on V8 JS engine
 V8 is open source JS engine developed by Google
 It also powers Google Chrome
 Written in C++
 Compiles JS code to native before execution
@akshaymathu
7
Good for
 For IO heavy apps
 Web socket (chat) server
 Real time collaborative editor
 Fast file uploads
 Ad server
 Any other real time data app (e.g. streaming server)
 Crawler
 Asynchronous chaining of tasks
 NOT good for CPU heavy apps
 Weather prediction
 May not be good for big projects
@akshaymathu
8
NodeJS is NOT
 A web framework
 Provides tools to create a web server
 Multi threaded
 Is Single threaded, event driven, asynchronous, non-blocking
 For beginners
 Needs programing at very low level
 You start with writing a web server
@akshaymathu
9
Possible Issues
@akshaymathu
10
 Can not utilize multicore processer because of single
thread
 Managing multiple processes from outside may be even bigger
problem
 Any CPU intensive task delays all the requests
 Requires constant attention (non-traditional thinking)
for not having blocking code
 In case of big products the code/logic gets distributed in
multiple callback functions
 If data needs to collected from different places and
correlated, synchronizing all callbacks becomes tough
 Garbage collection may also be an issue
S I N G L E T H R E A D E D
E V E N T D R I V E N
A S Y N C H R O N O U S
N O N - B L O C K I N G
What Jargons Mean
Single Threaded
 New Node process does not start for every request
 Only one code executes at a time
 Everything else remains in the queue
 No worry about different portions of code accessing the same
data structures at the same time
 Delay at one place delays everything after that
 Can not take advantage of multi-core CPU
 Then how NodeJS is fast?
@akshaymathu
12
Non-blocking
 There is only one process that is executing
 If the process waits for something to complete, everything else
gets delayed
 So the code has to be structured in a way that wait
for IO happens outside the main execution
@akshaymathu
13
Blocking Vs. Non-blocking
@akshaymathu
14
var a = db.query('SELECT * from huge_table’);
console.log('result a:’, a);
console.log(‘Doing something else’);
 Blocking I/O
 Non-Blocking I/O
db.query('SELECT * from huge_table’, function(res) {
console.log('result a:’, res);
});
console.log(‘Doing something else’);
Asynchronous
 Not all code is executed in the same order it is
written
 Node (and you) divide the code into small pieces and
fire them in parallel
 Typically the code announces its state of execution
(or completion) via events
@akshaymathu
15
Event Driven
 A code block gets into the queue of execution when
an event happens
 It gets executed on its turn
 Anyone can raise (or listen to) an event
 System
 Some library (module)
 Your code
 You have the choice (and ways) to attach a code
block to an event
 Also known as event callbacks
@akshaymathu
16
The Event Queue
@akshaymathu
17
‘King and Servants’ Analogy… by Felix Geisendörfer
everything runs in parallel, except your code. To understand that,
imagine your code is the king, and node is his army of servants.
The day starts by one servant waking up the king and asking him if he
needs anything. The king gives the servant a list of tasks and goes back
to sleep a little longer. The servant now distributes those tasks among
his colleagues and they get to work.
Once a servant finishes a task, he lines up outside the kings quarter to
report. The king lets one servant in at a time, and listens to things he
reports. Sometimes the king will give the servant more tasks on the
way out.
Life is good, for the king's servants carry out all of his tasks in parallel,
but only report with one result at a time, so the king can focus.
@akshaymathu
18
@akshaymathu
D O T H E Y O C C U R O N S E R V E R A S W E L L ?
Events
Events we know…
@akshaymathu
21
 The event familiar to us are
 Click
 Focus
 Blur
 Hover
 These events are raised when user interacts with
DOM elements
 But the DOM is not being rendered in NodeJS
 Then what events are we talking about in NodeJS?
Node Events
@akshaymathu
22
 The most common event that a web server uses is
request
 Raised when a web request (url) hits the server
 Other events:
 When chunk of multipart data (file) is received
 When all chunks of file are received
 When system finishes reading a file
 When data set is returned by a database query
 …
 You can define your own events using event emitter
Let’s Revise: JS Function Facts
@akshaymathu
23
 Function is a block of a code that gets executed when
called
 JS function may not have a name
 Anonymous functions can be used
 JS function accept any data type as argument
 Function is a valid data type in JS
 A function can be assigned to a variable
 A function can be passed as an argument to another
function
 A function can be defined inside another function
Event Callback
@akshaymathu
24
 Because the system is single threaded
 And we do not want to block it for I/O
 We use asynchronous functions for getting work done
 We depend on the events to tell when some work is
finished
 And we want some code to execute when the event occurs
 Asynchronous functions take a function as an
additional argument and call the function when the
event occurs
 This function is known as callback function
Callback in Action
@akshaymathu
25
callback = function(res) {
console.log('result a:’, res);
};
db.query('SELECT * from huge_table’, callback);
Or
db.query('SELECT * from huge_table’, function(res) {
console.log('result a:’, res);
});
@akshaymathu 26
N O T H I N G B U T L I B R A R I E S
Node Modules
Available Modules
@akshaymathu
28
 Modules are nothing but collections of useful
functions
 Otherwise we call them libraries
 Built-in modules come with NodeJS installation
 http, tcp, url, dns, buffer, udp etc.
 People create more modules, package and publish
them for others to use
 less, coffee, express etc.
 1000+ modules are available via npm
 You can write your own custom module for
organizing your code better
Creating Custom Module
@akshaymathu
29
 Write some useful code in a file
 Some function(s) achieving a goal
 Decide what should be available outside for others to
use
 Public API of your module
 Make the APIs available outside using exports object
my_api = function(){…};
exports.myApi = my_api;
Using Modules
@akshaymathu
30
 ‘require’ functions loads a module
 Whatever has been exported becomes available with
‘require’ and can be assigned to a variable for later
use
var http = require(‘http’);
var custom = require(‘./my_api’);
custom.myApi();
@akshaymathu 31
A S I M P L E W E B S E R V E R
@akshaymathu
32
Let’s Program
Hello World
@akshaymathu
33
 Just one line is needed to write to STDOUT
console.log(‘Hello World’)
 Running the file with Node just works
node hello_world.js
Minimalistic HTTP Server
@akshaymathu
34
var http = require("http");
on_request = function(request, response) {
response.writeHead(200,
{"Content-Type":
"text/plain"});
response.write("Hello World");
response.end();
};
http.createServer(on_request).listen(8888);
Console.log(‘Server Started’);
Improving the Server
@akshaymathu
35
 Running this server with Node starts the server
node server.js
 The server always returns same string
 Try any url, browser always says “Hello World”
 Actually the server should respond content based on
URL
 It should route the request to proper handler
 Handler should return proper content
Organizing Code
@akshaymathu
36
 Rather than writing everything in single file, it is a
good idea to divide the code into logical modules
 Main startup file: index.js
 Web server: server.js
 URL Router: routes.js
 Request Handler: requestHandlers.js
 …
 More files and directories will come as the code
grows
Initial Server Module
@akshaymathu
37
var http = require("http");
function start() {
function onRequest(request, response){
console.log("Request received.");
response.writeHead(200,
{"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
Initial Startup File
@akshaymathu
38
 As server became a module and exposes a start
function, we need to
 load server module
 Call start function to start the server
var server = require("./server");
server.start();
 Running the main file with now starts the server
node index.js
 But it still returns ‘Hello world’ for all URLs
Let’s Revise: Parts of URL
https://sub.domain.com:8086/a/folder/file.html?key
=val&key=val2#some_place
 Protocol
 Sub-domain, Domain and TLD
 Port
 Path
 File
 Query string
 Fragment
@akshaymathu
39
Server – Router Interaction
@akshaymathu
40
 For routing the requests based on URL, the router
must know pathname of the requested URL
 The URL can be read from the ‘request’ object available in
server module
 So what should we pass to the router?
 Request object
 URL (Extract URL from request in server)
 Pathname (Extract and parse URL in server)
 ??
 If server need to call router, how router becomes
available to server?
Initial Router
@akshaymathu
41
function route(pathname) {
console.log("About to route a
request for " + pathname);
}
exports.route = route;
Router Aware Server
@akshaymathu
42
var http = require("http");
var url = require("url");
function start(route) {
function onRequest(request, response){
var pathname =
url.parse(request.url).pathname;
route(pathname);
response.writeHead(200, "Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
}
exports.start = start;
Making Router Available to Server
@akshaymathu
43
 Router is made available as an argument (dependency) to
server’s ‘start’ function
 This is also known as dependency injection
var server = require("./server");
var router = require("./router");
server.start(router.route);
 Router module is loaded in startup file and the route
function is passed at the time of starting server
 Server then calls route function of the router with the
pathname
Adding Request Handlers
@akshaymathu
44
 The actual work of creating response for a request
will be done by Request Handlers
 We need to add these handlers to the server
 The requestHandlers module will consist of a
function corresponding to each expected URL
 At some place, we also need mapping between URL
and the request handler function
Initial Request Handlers
@akshaymathu
45
function start() {
console.log("Request for 'start’.");
return "Hello Start";
}
function upload() {
console.log("Request for 'upload.");
return "Hello Upload";
}
exports.start = start;
exports.upload = upload;
Including Handlers
@akshaymathu
46
var server = require("./server");
var router = require("./router");
var requestHandlers =
require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
Change in Server
@akshaymathu
47
function start(route, handle) {
function onRequest(request, response) {
var pathname =
url.parse(request.url).pathname;
content = route(handle, pathname);
response.writeHead(200, {"Content-Type":
"text/plain"});
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
Real Routing
@akshaymathu
48
function route(handle, pathname) {
console.log(”Routing request for " + pathname);
if (typeof handle[pathname] === 'function') {
return handle[pathname]();
} else {
console.log("No request handler found
for " + pathname);
}
}
exports.route = route;
@akshaymathu 49
 Done 
@akshaymathu
50
Did we do everything Correct?
 Nop 
What is wrong?
@akshaymathu
51
function start(route, handle) {
function onRequest(request, response) {
var pathname =
url.parse(request.url).pathname;
content = route(handle, pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
Blocking
Code
What are the problems?
@akshaymathu
52
 The way ‘content’ is being collected and being
written to response, it forces to write blocking
synchronous code in handlers
 Because handler has to return content when called
 If you write asynchronous code in handler, the server
will always return response with no content
 Because handler will return nothing and when callback will
return with the content, there will be no one to collect the
output
The Right Way
@akshaymathu
53
 The content should be written into response object
when the content becomes available
 So the response object should be made available to
request handlers
 Response object is available in server
 Server is not directly calling request handlers
 So first, Response object will be passed to router
 And then, Router will pass it to request handlers
Corrected Server
@akshaymathu
54
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname =
url.parse(request.url).pathname;
console.log("Request for " + pathname);
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
Corrected Router
@akshaymathu
55
function route(handle, pathname, response) {
console.log(”Routing request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log("No handler found for " +
pathname);
response.writeHead(404, {"Content-Type":
"text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
Corrected Handlers
@akshaymathu
56
function start(response) {
db.query(”select * from huge_table”,
function (error, stdout, stderr) {
response.writeHead(200,
{"Content-Type": "text/plain"});
response.write(stdout);
response.end();
});
}
exports.start = start;
 Done 
@akshaymathu
57
Did we do everything Correct?
 Yep 
@akshaymathu 58
Summary
 Node will require extra work and different thought
process
 But it will pay off for it
 Choose Node carefully only for the type of app it is
best suited
 You may not need to write code at the lowest level we
discussed here
 You may want to choose framework
@akshaymathu
59
MVC in Node
 Express (Controller)
 Mongoose (Model)
 Jade (View)
 More …
@akshaymathu
60
Thanks
@akshaymathu
61
@akshaymathu

More Related Content

What's hot

Express js
Express jsExpress js
Express js
Manav Prasad
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
Yao Nien Chung
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
sanskriti agarwal
 
Node.js Basics
Node.js Basics Node.js Basics
Node.js Basics
TheCreativedev Blog
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
Thanh Tuong
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
NestJS
NestJSNestJS
NestJS
Wilson Su
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
Reactjs
ReactjsReactjs
WEB DEVELOPMENT USING REACT JS
 WEB DEVELOPMENT USING REACT JS WEB DEVELOPMENT USING REACT JS
WEB DEVELOPMENT USING REACT JS
MuthuKumaran Singaravelu
 
Reactjs
Reactjs Reactjs
Reactjs
Neha Sharma
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
Fabien Vauchelles
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
Sunil Yadav
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Joseph de Castelnau
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Rob O'Doherty
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
MicroPyramid .
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
Nir Kaufman
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
Emanuele DelBono
 

What's hot (20)

Express js
Express jsExpress js
Express js
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
 
Node.js Basics
Node.js Basics Node.js Basics
Node.js Basics
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
NestJS
NestJSNestJS
NestJS
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
Reactjs
ReactjsReactjs
Reactjs
 
WEB DEVELOPMENT USING REACT JS
 WEB DEVELOPMENT USING REACT JS WEB DEVELOPMENT USING REACT JS
WEB DEVELOPMENT USING REACT JS
 
Reactjs
Reactjs Reactjs
Reactjs
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
 
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
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 

Similar to Introduction to Node js

Proposal
ProposalProposal
Node
NodeNode
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
David Padbury
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
GWT = easy AJAX
GWT = easy AJAXGWT = easy AJAX
GWT = easy AJAX
Olivier Gérardin
 
NodeJS
NodeJSNodeJS
NodeJS
LinkMe Srl
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
Sudar Muthu
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
Nathan Van Gheem
 
My Saminar On Php
My Saminar On PhpMy Saminar On Php
My Saminar On Php
Arjun Kumawat
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to Node.JS
Collaboration Technologies
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
Nodejs
NodejsNodejs
Possibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented ProgrammingPossibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented Programming
kozossakai
 
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
CODE BLUE
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
Budh Ram Gurung
 
Real time web
Real time webReal time web
Real time web
Medhat Dawoud
 
node.js - Fast event based web application development
node.js - Fast event based web application developmentnode.js - Fast event based web application development
node.js - Fast event based web application development
openForce Information Technology GesmbH
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso
 

Similar to Introduction to Node js (20)

Proposal
ProposalProposal
Proposal
 
Node
NodeNode
Node
 
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
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
GWT = easy AJAX
GWT = easy AJAXGWT = easy AJAX
GWT = easy AJAX
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
 
My Saminar On Php
My Saminar On PhpMy Saminar On Php
My Saminar On Php
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to Node.JS
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
 
Nodejs
NodejsNodejs
Nodejs
 
Possibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented ProgrammingPossibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented Programming
 
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
Possibility of arbitrary code execution by Step-Oriented Programming by Hiroa...
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
Real time web
Real time webReal time web
Real time web
 
node.js - Fast event based web application development
node.js - Fast event based web application developmentnode.js - Fast event based web application development
node.js - Fast event based web application development
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 

More from Akshay Mathur

Documentation with Sphinx
Documentation with SphinxDocumentation with Sphinx
Documentation with Sphinx
Akshay Mathur
 
Kubernetes Journey of a Large FinTech
Kubernetes Journey of a Large FinTechKubernetes Journey of a Large FinTech
Kubernetes Journey of a Large FinTech
Akshay Mathur
 
Security and Observability of Application Traffic in Kubernetes
Security and Observability of Application Traffic in KubernetesSecurity and Observability of Application Traffic in Kubernetes
Security and Observability of Application Traffic in Kubernetes
Akshay Mathur
 
Enhanced Security and Visibility for Microservices Applications
Enhanced Security and Visibility for Microservices ApplicationsEnhanced Security and Visibility for Microservices Applications
Enhanced Security and Visibility for Microservices Applications
Akshay Mathur
 
Considerations for East-West Traffic Security and Analytics for Kubernetes En...
Considerations for East-West Traffic Security and Analytics for Kubernetes En...Considerations for East-West Traffic Security and Analytics for Kubernetes En...
Considerations for East-West Traffic Security and Analytics for Kubernetes En...
Akshay Mathur
 
Kubernetes as Orchestrator for A10 Lightning Controller
Kubernetes as Orchestrator for A10 Lightning ControllerKubernetes as Orchestrator for A10 Lightning Controller
Kubernetes as Orchestrator for A10 Lightning Controller
Akshay Mathur
 
Cloud Bursting with A10 Lightning ADS
Cloud Bursting with A10 Lightning ADSCloud Bursting with A10 Lightning ADS
Cloud Bursting with A10 Lightning ADS
Akshay Mathur
 
Shared Security Responsibility Model of AWS
Shared Security Responsibility Model of AWSShared Security Responsibility Model of AWS
Shared Security Responsibility Model of AWS
Akshay Mathur
 
Techniques for scaling application with security and visibility in cloud
Techniques for scaling application with security and visibility in cloudTechniques for scaling application with security and visibility in cloud
Techniques for scaling application with security and visibility in cloud
Akshay Mathur
 
Object Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptObject Oriented Programing in JavaScript
Object Oriented Programing in JavaScript
Akshay Mathur
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JS
Akshay Mathur
 
Releasing Software Without Testing Team
Releasing Software Without Testing TeamReleasing Software Without Testing Team
Releasing Software Without Testing Team
Akshay Mathur
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
Akshay Mathur
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Akshay Mathur
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
Akshay Mathur
 
Getting Started with Web
Getting Started with WebGetting Started with Web
Getting Started with Web
Akshay Mathur
 
Getting Started with Javascript
Getting Started with JavascriptGetting Started with Javascript
Getting Started with Javascript
Akshay Mathur
 
Using Google App Engine Python
Using Google App Engine PythonUsing Google App Engine Python
Using Google App Engine Python
Akshay Mathur
 
Working with GIT
Working with GITWorking with GIT
Working with GIT
Akshay Mathur
 
Testing Single Page Webapp
Testing Single Page WebappTesting Single Page Webapp
Testing Single Page Webapp
Akshay Mathur
 

More from Akshay Mathur (20)

Documentation with Sphinx
Documentation with SphinxDocumentation with Sphinx
Documentation with Sphinx
 
Kubernetes Journey of a Large FinTech
Kubernetes Journey of a Large FinTechKubernetes Journey of a Large FinTech
Kubernetes Journey of a Large FinTech
 
Security and Observability of Application Traffic in Kubernetes
Security and Observability of Application Traffic in KubernetesSecurity and Observability of Application Traffic in Kubernetes
Security and Observability of Application Traffic in Kubernetes
 
Enhanced Security and Visibility for Microservices Applications
Enhanced Security and Visibility for Microservices ApplicationsEnhanced Security and Visibility for Microservices Applications
Enhanced Security and Visibility for Microservices Applications
 
Considerations for East-West Traffic Security and Analytics for Kubernetes En...
Considerations for East-West Traffic Security and Analytics for Kubernetes En...Considerations for East-West Traffic Security and Analytics for Kubernetes En...
Considerations for East-West Traffic Security and Analytics for Kubernetes En...
 
Kubernetes as Orchestrator for A10 Lightning Controller
Kubernetes as Orchestrator for A10 Lightning ControllerKubernetes as Orchestrator for A10 Lightning Controller
Kubernetes as Orchestrator for A10 Lightning Controller
 
Cloud Bursting with A10 Lightning ADS
Cloud Bursting with A10 Lightning ADSCloud Bursting with A10 Lightning ADS
Cloud Bursting with A10 Lightning ADS
 
Shared Security Responsibility Model of AWS
Shared Security Responsibility Model of AWSShared Security Responsibility Model of AWS
Shared Security Responsibility Model of AWS
 
Techniques for scaling application with security and visibility in cloud
Techniques for scaling application with security and visibility in cloudTechniques for scaling application with security and visibility in cloud
Techniques for scaling application with security and visibility in cloud
 
Object Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptObject Oriented Programing in JavaScript
Object Oriented Programing in JavaScript
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JS
 
Releasing Software Without Testing Team
Releasing Software Without Testing TeamReleasing Software Without Testing Team
Releasing Software Without Testing Team
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
 
Getting Started with Web
Getting Started with WebGetting Started with Web
Getting Started with Web
 
Getting Started with Javascript
Getting Started with JavascriptGetting Started with Javascript
Getting Started with Javascript
 
Using Google App Engine Python
Using Google App Engine PythonUsing Google App Engine Python
Using Google App Engine Python
 
Working with GIT
Working with GITWorking with GIT
Working with GIT
 
Testing Single Page Webapp
Testing Single Page WebappTesting Single Page Webapp
Testing Single Page Webapp
 

Recently uploaded

K2G - Insurtech Innovation EMEA Award 2024
K2G - Insurtech Innovation EMEA Award 2024K2G - Insurtech Innovation EMEA Award 2024
K2G - Insurtech Innovation EMEA Award 2024
The Digital Insurer
 
5G bootcamp Sep 2020 (NPI initiative).pptx
5G bootcamp Sep 2020 (NPI initiative).pptx5G bootcamp Sep 2020 (NPI initiative).pptx
5G bootcamp Sep 2020 (NPI initiative).pptx
SATYENDRA100
 
How to Avoid Learning the Linux-Kernel Memory Model
How to Avoid Learning the Linux-Kernel Memory ModelHow to Avoid Learning the Linux-Kernel Memory Model
How to Avoid Learning the Linux-Kernel Memory Model
ScyllaDB
 
AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)
apoorva2579
 
Performance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy EvertsPerformance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy Everts
ScyllaDB
 
Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024
The Digital Insurer
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
Interaction Latency: Square's User-Centric Mobile Performance Metric
Interaction Latency: Square's User-Centric Mobile Performance MetricInteraction Latency: Square's User-Centric Mobile Performance Metric
Interaction Latency: Square's User-Centric Mobile Performance Metric
ScyllaDB
 
Running a Go App in Kubernetes: CPU Impacts
Running a Go App in Kubernetes: CPU ImpactsRunning a Go App in Kubernetes: CPU Impacts
Running a Go App in Kubernetes: CPU Impacts
ScyllaDB
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
BookNet Canada
 
How Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global ScaleHow Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global Scale
ScyllaDB
 
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
amitchopra0215
 
STKI Israeli Market Study 2024 final v1
STKI Israeli Market Study 2024 final  v1STKI Israeli Market Study 2024 final  v1
STKI Israeli Market Study 2024 final v1
Dr. Jimmy Schwarzkopf
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 
HTTP Adaptive Streaming – Quo Vadis (2024)
HTTP Adaptive Streaming – Quo Vadis (2024)HTTP Adaptive Streaming – Quo Vadis (2024)
HTTP Adaptive Streaming – Quo Vadis (2024)
Alpen-Adria-Universität
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
Stephanie Beckett
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & SolutionsMYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
Linda Zhang
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 

Recently uploaded (20)

K2G - Insurtech Innovation EMEA Award 2024
K2G - Insurtech Innovation EMEA Award 2024K2G - Insurtech Innovation EMEA Award 2024
K2G - Insurtech Innovation EMEA Award 2024
 
5G bootcamp Sep 2020 (NPI initiative).pptx
5G bootcamp Sep 2020 (NPI initiative).pptx5G bootcamp Sep 2020 (NPI initiative).pptx
5G bootcamp Sep 2020 (NPI initiative).pptx
 
How to Avoid Learning the Linux-Kernel Memory Model
How to Avoid Learning the Linux-Kernel Memory ModelHow to Avoid Learning the Linux-Kernel Memory Model
How to Avoid Learning the Linux-Kernel Memory Model
 
AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)
 
Performance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy EvertsPerformance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy Everts
 
Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
Interaction Latency: Square's User-Centric Mobile Performance Metric
Interaction Latency: Square's User-Centric Mobile Performance MetricInteraction Latency: Square's User-Centric Mobile Performance Metric
Interaction Latency: Square's User-Centric Mobile Performance Metric
 
Running a Go App in Kubernetes: CPU Impacts
Running a Go App in Kubernetes: CPU ImpactsRunning a Go App in Kubernetes: CPU Impacts
Running a Go App in Kubernetes: CPU Impacts
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
 
How Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global ScaleHow Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global Scale
 
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
 
STKI Israeli Market Study 2024 final v1
STKI Israeli Market Study 2024 final  v1STKI Israeli Market Study 2024 final  v1
STKI Israeli Market Study 2024 final v1
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 
HTTP Adaptive Streaming – Quo Vadis (2024)
HTTP Adaptive Streaming – Quo Vadis (2024)HTTP Adaptive Streaming – Quo Vadis (2024)
HTTP Adaptive Streaming – Quo Vadis (2024)
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & SolutionsMYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 

Introduction to Node js

  • 1. A K S H A Y M A T H U R @AKSHAYMATHU Getting Started with
  • 2. Ground Rules @akshaymathu 2  Post on FB and Tweet now  Disturb Everyone during the session  Not by phone rings  Not by local talks  By more information and questions
  • 3. Let’s Know Each Other @akshaymathu 3  Do you code?  OS?  Node?  JavaScript, JSON?  Web Development?  CoffeeScript  Other Programing Language?  Why are you attending?
  • 4. Akshay Mathur @akshaymathu 4  Founding Team Member of  ShopSocially (Enabling “social” for retailers)  AirTight Neworks (Global leader of WIPS)  15+ years in IT industry  Currently Principal Architect at ShopSocially  Mostly worked with Startups  From Conceptualization to Stabilization  At different functions i.e. development, testing, release  With multiple technologies
  • 5. JavaScript @akshaymathu 5  Born in 1995 at Netscape  Not at all related to Java  Syntax influenced by C  Interpreted ECMA scripting language  Dynamically typed  Object Oriented as well as Functional  Prototype based
  • 6. Typical Usage @akshaymathu 6  Web programing  Client side  Web pages  Browser plugins  Server side  SSJS (not in use)  NodeJS  PDF documents  Desktop Widgets  MongoDB
  • 7. NodeJS  JavaScript Runtime at command line  Allows us to write JS programs outside browser  Built on V8 JS engine  V8 is open source JS engine developed by Google  It also powers Google Chrome  Written in C++  Compiles JS code to native before execution @akshaymathu 7
  • 8. Good for  For IO heavy apps  Web socket (chat) server  Real time collaborative editor  Fast file uploads  Ad server  Any other real time data app (e.g. streaming server)  Crawler  Asynchronous chaining of tasks  NOT good for CPU heavy apps  Weather prediction  May not be good for big projects @akshaymathu 8
  • 9. NodeJS is NOT  A web framework  Provides tools to create a web server  Multi threaded  Is Single threaded, event driven, asynchronous, non-blocking  For beginners  Needs programing at very low level  You start with writing a web server @akshaymathu 9
  • 10. Possible Issues @akshaymathu 10  Can not utilize multicore processer because of single thread  Managing multiple processes from outside may be even bigger problem  Any CPU intensive task delays all the requests  Requires constant attention (non-traditional thinking) for not having blocking code  In case of big products the code/logic gets distributed in multiple callback functions  If data needs to collected from different places and correlated, synchronizing all callbacks becomes tough  Garbage collection may also be an issue
  • 11. S I N G L E T H R E A D E D E V E N T D R I V E N A S Y N C H R O N O U S N O N - B L O C K I N G What Jargons Mean
  • 12. Single Threaded  New Node process does not start for every request  Only one code executes at a time  Everything else remains in the queue  No worry about different portions of code accessing the same data structures at the same time  Delay at one place delays everything after that  Can not take advantage of multi-core CPU  Then how NodeJS is fast? @akshaymathu 12
  • 13. Non-blocking  There is only one process that is executing  If the process waits for something to complete, everything else gets delayed  So the code has to be structured in a way that wait for IO happens outside the main execution @akshaymathu 13
  • 14. Blocking Vs. Non-blocking @akshaymathu 14 var a = db.query('SELECT * from huge_table’); console.log('result a:’, a); console.log(‘Doing something else’);  Blocking I/O  Non-Blocking I/O db.query('SELECT * from huge_table’, function(res) { console.log('result a:’, res); }); console.log(‘Doing something else’);
  • 15. Asynchronous  Not all code is executed in the same order it is written  Node (and you) divide the code into small pieces and fire them in parallel  Typically the code announces its state of execution (or completion) via events @akshaymathu 15
  • 16. Event Driven  A code block gets into the queue of execution when an event happens  It gets executed on its turn  Anyone can raise (or listen to) an event  System  Some library (module)  Your code  You have the choice (and ways) to attach a code block to an event  Also known as event callbacks @akshaymathu 16
  • 18. ‘King and Servants’ Analogy… by Felix Geisendörfer everything runs in parallel, except your code. To understand that, imagine your code is the king, and node is his army of servants. The day starts by one servant waking up the king and asking him if he needs anything. The king gives the servant a list of tasks and goes back to sleep a little longer. The servant now distributes those tasks among his colleagues and they get to work. Once a servant finishes a task, he lines up outside the kings quarter to report. The king lets one servant in at a time, and listens to things he reports. Sometimes the king will give the servant more tasks on the way out. Life is good, for the king's servants carry out all of his tasks in parallel, but only report with one result at a time, so the king can focus. @akshaymathu 18
  • 20. D O T H E Y O C C U R O N S E R V E R A S W E L L ? Events
  • 21. Events we know… @akshaymathu 21  The event familiar to us are  Click  Focus  Blur  Hover  These events are raised when user interacts with DOM elements  But the DOM is not being rendered in NodeJS  Then what events are we talking about in NodeJS?
  • 22. Node Events @akshaymathu 22  The most common event that a web server uses is request  Raised when a web request (url) hits the server  Other events:  When chunk of multipart data (file) is received  When all chunks of file are received  When system finishes reading a file  When data set is returned by a database query  …  You can define your own events using event emitter
  • 23. Let’s Revise: JS Function Facts @akshaymathu 23  Function is a block of a code that gets executed when called  JS function may not have a name  Anonymous functions can be used  JS function accept any data type as argument  Function is a valid data type in JS  A function can be assigned to a variable  A function can be passed as an argument to another function  A function can be defined inside another function
  • 24. Event Callback @akshaymathu 24  Because the system is single threaded  And we do not want to block it for I/O  We use asynchronous functions for getting work done  We depend on the events to tell when some work is finished  And we want some code to execute when the event occurs  Asynchronous functions take a function as an additional argument and call the function when the event occurs  This function is known as callback function
  • 25. Callback in Action @akshaymathu 25 callback = function(res) { console.log('result a:’, res); }; db.query('SELECT * from huge_table’, callback); Or db.query('SELECT * from huge_table’, function(res) { console.log('result a:’, res); });
  • 27. N O T H I N G B U T L I B R A R I E S Node Modules
  • 28. Available Modules @akshaymathu 28  Modules are nothing but collections of useful functions  Otherwise we call them libraries  Built-in modules come with NodeJS installation  http, tcp, url, dns, buffer, udp etc.  People create more modules, package and publish them for others to use  less, coffee, express etc.  1000+ modules are available via npm  You can write your own custom module for organizing your code better
  • 29. Creating Custom Module @akshaymathu 29  Write some useful code in a file  Some function(s) achieving a goal  Decide what should be available outside for others to use  Public API of your module  Make the APIs available outside using exports object my_api = function(){…}; exports.myApi = my_api;
  • 30. Using Modules @akshaymathu 30  ‘require’ functions loads a module  Whatever has been exported becomes available with ‘require’ and can be assigned to a variable for later use var http = require(‘http’); var custom = require(‘./my_api’); custom.myApi();
  • 32. A S I M P L E W E B S E R V E R @akshaymathu 32 Let’s Program
  • 33. Hello World @akshaymathu 33  Just one line is needed to write to STDOUT console.log(‘Hello World’)  Running the file with Node just works node hello_world.js
  • 34. Minimalistic HTTP Server @akshaymathu 34 var http = require("http"); on_request = function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }; http.createServer(on_request).listen(8888); Console.log(‘Server Started’);
  • 35. Improving the Server @akshaymathu 35  Running this server with Node starts the server node server.js  The server always returns same string  Try any url, browser always says “Hello World”  Actually the server should respond content based on URL  It should route the request to proper handler  Handler should return proper content
  • 36. Organizing Code @akshaymathu 36  Rather than writing everything in single file, it is a good idea to divide the code into logical modules  Main startup file: index.js  Web server: server.js  URL Router: routes.js  Request Handler: requestHandlers.js  …  More files and directories will come as the code grows
  • 37. Initial Server Module @akshaymathu 37 var http = require("http"); function start() { function onRequest(request, response){ console.log("Request received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
  • 38. Initial Startup File @akshaymathu 38  As server became a module and exposes a start function, we need to  load server module  Call start function to start the server var server = require("./server"); server.start();  Running the main file with now starts the server node index.js  But it still returns ‘Hello world’ for all URLs
  • 39. Let’s Revise: Parts of URL https://sub.domain.com:8086/a/folder/file.html?key =val&key=val2#some_place  Protocol  Sub-domain, Domain and TLD  Port  Path  File  Query string  Fragment @akshaymathu 39
  • 40. Server – Router Interaction @akshaymathu 40  For routing the requests based on URL, the router must know pathname of the requested URL  The URL can be read from the ‘request’ object available in server module  So what should we pass to the router?  Request object  URL (Extract URL from request in server)  Pathname (Extract and parse URL in server)  ??  If server need to call router, how router becomes available to server?
  • 41. Initial Router @akshaymathu 41 function route(pathname) { console.log("About to route a request for " + pathname); } exports.route = route;
  • 42. Router Aware Server @akshaymathu 42 var http = require("http"); var url = require("url"); function start(route) { function onRequest(request, response){ var pathname = url.parse(request.url).pathname; route(pathname); response.writeHead(200, "Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); } exports.start = start;
  • 43. Making Router Available to Server @akshaymathu 43  Router is made available as an argument (dependency) to server’s ‘start’ function  This is also known as dependency injection var server = require("./server"); var router = require("./router"); server.start(router.route);  Router module is loaded in startup file and the route function is passed at the time of starting server  Server then calls route function of the router with the pathname
  • 44. Adding Request Handlers @akshaymathu 44  The actual work of creating response for a request will be done by Request Handlers  We need to add these handlers to the server  The requestHandlers module will consist of a function corresponding to each expected URL  At some place, we also need mapping between URL and the request handler function
  • 45. Initial Request Handlers @akshaymathu 45 function start() { console.log("Request for 'start’."); return "Hello Start"; } function upload() { console.log("Request for 'upload."); return "Hello Upload"; } exports.start = start; exports.upload = upload;
  • 46. Including Handlers @akshaymathu 46 var server = require("./server"); var router = require("./router"); var requestHandlers = require("./requestHandlers"); var handle = {} handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/upload"] = requestHandlers.upload; server.start(router.route, handle);
  • 47. Change in Server @akshaymathu 47 function start(route, handle) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; content = route(handle, pathname); response.writeHead(200, {"Content-Type": "text/plain"}); response.write(content); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
  • 48. Real Routing @akshaymathu 48 function route(handle, pathname) { console.log(”Routing request for " + pathname); if (typeof handle[pathname] === 'function') { return handle[pathname](); } else { console.log("No request handler found for " + pathname); } } exports.route = route;
  • 50.  Done  @akshaymathu 50 Did we do everything Correct?  Nop 
  • 51. What is wrong? @akshaymathu 51 function start(route, handle) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; content = route(handle, pathname); response.writeHead(200, {"Content-Type": "text/plain"}); response.write(content); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start; Blocking Code
  • 52. What are the problems? @akshaymathu 52  The way ‘content’ is being collected and being written to response, it forces to write blocking synchronous code in handlers  Because handler has to return content when called  If you write asynchronous code in handler, the server will always return response with no content  Because handler will return nothing and when callback will return with the content, there will be no one to collect the output
  • 53. The Right Way @akshaymathu 53  The content should be written into response object when the content becomes available  So the response object should be made available to request handlers  Response object is available in server  Server is not directly calling request handlers  So first, Response object will be passed to router  And then, Router will pass it to request handlers
  • 54. Corrected Server @akshaymathu 54 var http = require("http"); var url = require("url"); function start(route, handle) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname); route(handle, pathname, response); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
  • 55. Corrected Router @akshaymathu 55 function route(handle, pathname, response) { console.log(”Routing request for " + pathname); if (typeof handle[pathname] === 'function') { handle[pathname](response); } else { console.log("No handler found for " + pathname); response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not found"); response.end(); } } exports.route = route;
  • 56. Corrected Handlers @akshaymathu 56 function start(response) { db.query(”select * from huge_table”, function (error, stdout, stderr) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write(stdout); response.end(); }); } exports.start = start;
  • 57.  Done  @akshaymathu 57 Did we do everything Correct?  Yep 
  • 59. Summary  Node will require extra work and different thought process  But it will pay off for it  Choose Node carefully only for the type of app it is best suited  You may not need to write code at the lowest level we discussed here  You may want to choose framework @akshaymathu 59
  • 60. MVC in Node  Express (Controller)  Mongoose (Model)  Jade (View)  More … @akshaymathu 60

Editor's Notes

  1. After first session add lines