SlideShare une entreprise Scribd logo
1  sur  98
© Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com
SELA DEVELOPER PRACTICE
MAY 31 – JUNE 4, 2015
Nir Noy
Consultant, Web, Sela
@noynir
Node.js
Agenda
Introduction - What is Node.js.
File system.
Building servers.
Building APIs using modules, events and
packages.
Express Web framework.
Introduction – What is Node.js ?
What is Node.js
A JavaScript runtime that is designed for
asynchronous IO operations
Very lightweight and fast
Being used by a growing number of companies:
The Node.js ecosystem
Node.js has a rapidly growing ecosystem:
Web frameworks:
Express
Socket.io
Database support
Sql Databases
NoSql Databases
Hosting and Cloud environments
IIS, Azure
Heroku
Joyent
Synchronous server operations
// GET api/countries
public string Get()
{
var client = WebRequest.Create("http://.../");
var response = client.GetResponse();
var stream = response.GetResponseStream();
var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
Blocking I/O operation
The Cost of I/O
I/O Operations are expensive.
I/O Source CPU Cycles
L1 – Cache 3
L2 – Cache 14
RAM 250
Disk 41,000,000
Network 240,000,000
Handling I/O
Waiting for I/O operations to complete is one of
the most common performance bottlenecks.
There are several common solutions to handle
it:
Synchronous
Pros: simple.
Cons: blocking, can hold up other requests.
Fork a new process
Pros: efficient, not holding up other requests.
Cons: does not scale, ~100 connections=~100 processes .
Handling I/O
Threads:
Pros:
efficient, not holding up other requests but more
lightweight then executing another process
Cons:
memory-expensive - ~1MB per thread, complicated, need
to worry about controlling access and shared resources.
Traditional web-servers (IIS, Apache) today use
an optimized thread-per-connection model that
uses thread pools.
Handling I/O in Node.js
Node.js runs your code on a single thread.
All I/O operations are asynchronous and Non-
Blocking
Internally threads and processes are used but not
explicitly exposed to your code.
When an I/O operation completes, an event is
triggered and the result is passed to a callback
function.
Why Node.js
Lightweight and efficient
using non-blocking I/O keeps memory consumption
stable by reducing the number of threads.
Less context switching overhead.
Concurrency
using non-blocking I/O keeps the main thread
responsive and allowing it support tens of thousands
of concurrent connections.
One Language
allows reuse of resources between the client and
server.
Demo
Async server in Node.js
What Node.js code looks like
Node.js Event loop
I/O operations are evented and external events
are handled by Node’s Event loop.
Javascript functions are passed to a queue and
invoked when the return value from their
current I/O calls is available.
I/O Callbacks are invoked synchronously by the
order they returned.
Node.js Event loop
Server
Async
Workers
DDB, FS,
Network,
etc…
Request
Response
Request
Response
Demo
Node.js single thread
Node.js Usage
Running CPU intensive tasks (e.g. long running
loops) on Node.js’s main thread should be
avoided as it will block handling other requests
to the server.
Running CPU intensive tasks can be scaled out
to multiple node processes.
Node.js can run a managed cluster of multiple
processes to scale out an entire application.
The Node.js process
Unlike client-side JavaScript Node.js does not
run inside a browser window.
There are no window or document global
objects
The Node process provides the runtime for
node programs
Node.js process architecture
Node.exe
V8
CommonJS – Module loader
JavaScript Application
libuv
OS
Core Javascript modules for file
system, network, http, etc…
Responsible for loading modules
and manage dependencies.
Using CommonJS’s module
definition.
Multi-platform library written in C
that handles all async I/O
operations.
Google’s Javascript Engine.
Compiles the Javascript code to
native machine code.
The process global object
The process global object provides an API for
interacting with the process
Access command-line arguments
Get the execution path, current platform, node.js
version
Environment variables
Accessing standard input/output
Demo
Running Node from the command line
File System
File System
Node.js provides the fs module for file system
operations:
Readingwriting files
Getting file metadata
Reading directories
Creating a file watcher
Most fs functions have synchronous APIs
Reading Directories
var fs = require('fs');
// this method reads the content of a directory
fs.readdir(process.argv[2], function(err,files){
files.forEach(function(file){
//Do something with file…
});
});
Demo
Inspecting directory’s content using the
fs module
Reading files
The fs module prvides different methods for
reading file content:
readFileSync reading the whole file synchronously
readFile reading the whole file asynchronously
createReadStream provides a stream based API for
reading files
var fs = require('fs');
//Async
fs.readFile(process.argv[2],'utf-8', function (err, data) {
if (err) throw err;
console.log(data)
});
//Read file sync
var f = fs.readFileSync(process.argv[2],'utf-8');
console.log(f);
Reading Files
Demo
Different ways to read files
Streams
Just like other frameworks Node.js use streams
as an abstraction for reading/writing data.
Just like most IO in Node.js, streams provide an
event base API using the on method
close, open
data
error
When using streams, data is read in chunks and
doesn’t block the main thread for the entire
time the data is buffered into memory.
Streams (cont.)
var fs = require('fs');
var strm = fs.createReadStream(process.argv[2]);
strm.setEncoding('utf8');
strm.on('data', function(data) {
console.log('read from strm');
});
strm.on('end', function(){
console.log('ended strm')
})
The pipe method allows you to connect a
readable stream as the destination of a
writeable stream
var fs = require("fs");
// Read File
fs.createReadStream("input/people.json")
// Write File
.pipe(fs.createWriteStream("output/people.json"));
Stream.pipe
Demo
Fun with standard IO
Lab
FS Module
Building servers
Building HTTP servers
Node.js was originally designed as a platform
for building web servers.
Most Web applications are I/O Bound
~90% of a request’s processing time is spent on
waiting for I/O to complete.
Node.js async I/O mechanism provides node
with high concurrency and a low memory
footprint.
Building HTTP servers (cont.)
Node.js is designed to be scaled out to multiple
processes and machines which makes it ideal
for cloud hosting.
The http module provides basic functionality
for handling HTTP (client and server)
Additional frameworks like Express and Restify
provide higher level abstractions (like MVC)
var http = require('http');
http.createServer(function(req,res){
var response = 'Hello World';
res.writeHead(200,
{
'Content-Type': 'text/plain',
'Content-Length': response.length
});
res.write(response);
res.end();
}).listen(3000);
Node Http Server
Demo
Hello HTTP
The http.Server class
The http.createServer() method is used to
create a server.
It returns an instance of the http.Server object.
The http.Server provides a set of events
request – fires on every incoming request.
Connection -fires on every new tcp connection.
Upgrade - fires on every incoming upgrade request.
Demo
Handling the ‘connection’ event
Receiving data
HTTP allows server applications to receive data:
Using the request URI
Message body
Use the url and querystring modules for
parsing URLs and query strings.
Message body can contain any format
Being a JavaScript runtime, Node.js process JSON
natively
Other formats are supported through npm packages.
var http = require('http');
var url = require('url') ;
http.createServer(function (req, res) {
var queryObject = url.parse(req.url,true).query;
console.log(queryObject);
res.writeHead(200);
res.end('Feel free to add query parameters to the end of the
url');
}).listen(8080);
Parsing URL and Querystring
Demo
Using the URL and QueryString APIs
Http streaming
// handling incoming HTTP requests
var handleRequests = function(req,res){
// creating an outgoing HTTP request
req = http.request(options, responseCallback =
function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function(){
res.end(str);
});
});
req.end();
};
Chunked transfer encoding
HTTP 1.1 introduced Chunked transfer encoding
that allows messages to be sent in chunks.
The Content-Length header is removed and a
Transfer-Encoding:chunked header is added to
the response.
HTTP can send messages in chunks
Write data in small chunks keeping a small memory
footprint
Freeing node’s single thread to serve more requests
var http = require('http');
var handleRequests = function(req,res){
// creating an outgoing HTTP request
var req2 = http.request(options, responseCallback = function(response) {
res.writeHead(200, {'content-type': 'text/xml', 'Content-
Encoding':'gzip'})
response.on('data', function (chunk) {
res.write(chunk);
});
response.on('end', function(){
res.end();
});
});
req2.end();
};
http.createServer(handleRequests).listen(3000);
Chunked transfer encoding
Demo
HTTP Chunked transfer
Lab
Simple Http Server
Building APIs using modules, events
and packages
CommonJS Modules
Node.js uses CommonJS modules for
structuring code.
Modules are defined in separate .js files
To consume a module use the require
function
Modules and Scopes
Modules provide a simple mechanism for
creating scopes in JavaScript
Members defined inside a module are not
accessible outside
To expose a member use the exports object
This allow CommonJS to simplify dependency
resolution
Demo
Defining and Using Modules
The Global object
Unlike browsers the top-level scope in Node.js
is the module not global
To expose objects globally (across modules)
you can add them to the global object
Demo
Exposing Objects Globally
Node Package Manager (NPM)
The Node Package Manager (NPM) provides a
management mechanism for modules:
Download and install
Version management
Deployment
Demo
Getting Express.js
Managing Dependencies
NPM packages are managed in a file called
package.json
package.json schema define fields like:
name, description
Version
Dependencies
Dependencies are being resolved during NPM
install
{
"name": "app",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.10.2",
"cookie-parser": "~1.3.3",
"debug": "~2.1.1",
"express": "~4.11.1",
"jade": "~1.9.1",
"lodash": "^3.3.1",
"morgan": "~1.5.1",
"serve-favicon": "~2.2.0"
}
}
A look at Package.json
Demo
A look at package.json
Managing Dependencies
NPM packages are installed inside a folder
named node_modules
The folder is created inside the path where the
“npm install …” was executed.
When a npm module is required node will look
it up inside the node_modules folder of the
current path.
If the module is not found it is recursively searched
up the folder tree.
Demo
Modules Dependency Resolution
The EventEmitter
Most of Node.js's APIs are event based
The events module provides the event emitter
object for emitting events.
Events are fired through the emit method and
can be watched using the on method.
Demo
Emitting Events
Lab
Being Modular
Express Web framework
Introduction to Express
Node.js http module provides bare-bones HTTP
server functionality
Building a modern web application server
would require implementing many common
features such as:
Routing
Session Management
Cookies & Requests Parsers
Request Logging
Introduction to Express
Express is a web application framework inspired
by Sinatra.
Express middleware provides an expendable
Http pipeline on top of Node.js's httpServer
An Express application is essentially a series of
middleware calls
A middleware is simply a function with access to
the request object, response object and a
callback to next middleware in line.
Express is available through npm
$ npm install express --save
Express provides a generator tool to quickly
create an application skeleton.
$ npm install express-generator –g
//run
$ express -h
Express Installation
Demo
Simple Express Server
Routing is one of the pillars of Express
To create a route use the app.verb convention
// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
res.send('Hello World!');
})
// accept POST request on the homepage
app.post('/', function (req, res) {
res.send('Got a POST request');
})
// accept PUT request at /user
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user');
})
Routing
Routers
An Express application might have a large
number of routes defined.
Maintaining All of them in a single file can be a pain.
Routers helps you keep your routes clean,
organized and modular.
Routers are defined in a separate node modules
and used as middlewares.
A router is an isolated instance of middlewares
and routes.
The router can have middleware and http VERB
routes added just like an application.
var router = express.Router([options]);
router.get('/events', function(req, res, next) {
// .. some logic here .. like any other middleware // ..
});
Routers (cont.)
Demo
Simple routing
Routing and Parameters
Express support parameters as part of the URI
Declare a parameter in the URI by using a “:” in
front of it
Access query-string parameters using req.query
Use regular expressions
To set a parameter as optional add a “?” suffix.
router.get('/user/:username',function(req,res){
//Do something
})
router.get("/page1/:id?",function(req,res){
req.params.id=req.params.id || 0;
res.send("query: "+ JSON.stringify(req.query));
});
Routes With Parameters
Demo
Passing Parameters to Routes
Express application settings can be set using
app.set() and retrieved using app.get()
You can also set middleware functions using
app.use().
// this middleware will be executed for every request to the
app
app.use(function (req, res, next) {
console.log('Time: %d', Date.now());
next();
})
Configuring Express
Views are template based UI mechanism
Express support many view-engines including:
Jade
JSHtml
EJS
View engines are defined by setting the ‘view-
engine’ variable
app.set('view engine', 'jade');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
Views
Jade
Jade is Express default view-engine
It is based on Haml it provide a clean syntax for
generating HTML
Tab based
Full support for HTML
doctype
html
head
title My Page
body
div.jumbotron
h1#title This is my Page
p how do you like my styling?
Jade template
Demo
Basic Jade Template
Jade fully support JavaScript using the script
element:
Linking to external JS files
Embedding in-line JavaScript
To setup static content serving in Express use
the built-in static middleware.
app.use(express.static(__dirname+'/public'));
// multiple static folders can be defined.
Mixing up JavaSript & Jade
Demo
Jade and bootstrap
Blocks
In most applications, some UI components are
used throughout the application
Blocks provide a way to provide a common
layout that is shared among views
doctype
html
head
title My Application
link(href='/css/bootstrap.min.css', rel="stylesheet")
link(href='/css/bootstrap-theme.min.css',
rel="stylesheet")
body
div.page-header
h1 This is my Application
div.container-fluid
block content
Jade Layout Template
extends layout
block content
div.container
p this is a container
div and some more text here
Jade Template Using Layout
Demo
Using Blocks
Model
Express provides a mechanism to insert data-
models into views
The rendering of the complete artifact is up to
the view engine
extends layout
block content
div.container.bg-danger
h1 oops...,Server error
p #{error}
Rendering data in Jade
Demo
Rendering Data with Jade
Functionality to Express apps are added via
third-party middleware installed through npm.
$ npm install cookie-parser
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
// load the cookie parsing middleware
app.use(cookieParser());
Express Middlewares
Common Express Middlewares
Express 4.0 Name
body-parser
compression
cookie-session
morgan
cookie-parser
express-session
static-favicon
response-time
errorhandler
method-override
connect-timeout
vhost
csurf
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:n')
res.end(JSON.stringify(req.body, null, 2))
})
The body-parser middleware
var express = require('express')
var session = require('express-session')
var app = express()
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.use(function(req, res, next) {
var sess = req.session
if (sess.views) {
sess.views++
} else {
sess.views = 1
res.end('welcome to the session demo. refresh!')
}
})
Express-Session
Demo
Login with Express
Lab
Express App
Summary
Node.js is not just for building servers
It allows JavaScript to run outside of browsers
and perform asynchronous IO
It is asynchronous by nature
Node.js runs your code on a single thread.
Lightweight, fast and extremely cool.
nirn@sela.co.il | @noynir
Questions

Contenu connexe

Tendances

Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
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 backendDavid Padbury
 
NodeJS: the good parts? A skeptic’s view (devnexus2014)
NodeJS: the good parts? A skeptic’s view (devnexus2014)NodeJS: the good parts? A skeptic’s view (devnexus2014)
NodeJS: the good parts? A skeptic’s view (devnexus2014)Chris Richardson
 
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
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsGanesh Iyer
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
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 talkAarti Parikh
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js ExplainedJeff Kunkle
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Understanding the Single Thread Event Loop
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event LoopTorontoNodeJS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginnersEnoch Joshua
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
Getting started with developing Nodejs
Getting started with developing NodejsGetting started with developing Nodejs
Getting started with developing NodejsPhil Hawksworth
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 

Tendances (20)

Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven 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
 
NodeJS: the good parts? A skeptic’s view (devnexus2014)
NodeJS: the good parts? A skeptic’s view (devnexus2014)NodeJS: the good parts? A skeptic’s view (devnexus2014)
NodeJS: the good parts? A skeptic’s view (devnexus2014)
 
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
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
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
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Understanding the Single Thread Event Loop
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event Loop
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Node.js code tracing
Node.js code tracingNode.js code tracing
Node.js code tracing
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Getting started with developing Nodejs
Getting started with developing NodejsGetting started with developing Nodejs
Getting started with developing Nodejs
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 

En vedette

JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015Igor Laborie
 
Implement Dependency Injection in Java
Implement Dependency Injection in JavaImplement Dependency Injection in Java
Implement Dependency Injection in JavaGeng-Dian Huang
 
Intro to Front End Development with Angular + Firebase
Intro to Front End Development with Angular + FirebaseIntro to Front End Development with Angular + Firebase
Intro to Front End Development with Angular + FirebaseBen Drucker
 
Scaling AngularJS: Enterprise SOA on the MEAN Stack (Responsive Web & Mobile)
Scaling AngularJS: Enterprise SOA on the MEAN Stack (Responsive Web & Mobile)Scaling AngularJS: Enterprise SOA on the MEAN Stack (Responsive Web & Mobile)
Scaling AngularJS: Enterprise SOA on the MEAN Stack (Responsive Web & Mobile)Movel
 
Creating MVC Application with backbone js
Creating MVC Application with backbone jsCreating MVC Application with backbone js
Creating MVC Application with backbone jsMindfire Solutions
 
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Burgas Conf 21.06.2014 - Single page application Angularjs and NodejsBurgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Burgas Conf 21.06.2014 - Single page application Angularjs and NodejsDimitar Danailov
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architectureGabriele Falace
 
Node.js 101
 Node.js 101 Node.js 101
Node.js 101FITC
 
AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)Gary Arora
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
API Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
API  Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015 API  Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
API Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015 Hamdi Hmidi
 
Bhasma - Nano Medicine (Ancient India - Ayurveda)
Bhasma - Nano Medicine (Ancient India -  Ayurveda)Bhasma - Nano Medicine (Ancient India -  Ayurveda)
Bhasma - Nano Medicine (Ancient India - Ayurveda)Piyush Kapil
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksSlideShare
 

En vedette (20)

JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015
 
Implement Dependency Injection in Java
Implement Dependency Injection in JavaImplement Dependency Injection in Java
Implement Dependency Injection in Java
 
Groovy to gradle
Groovy to gradleGroovy to gradle
Groovy to gradle
 
Firebase and AngularJS
Firebase and AngularJSFirebase and AngularJS
Firebase and AngularJS
 
Intro to Front End Development with Angular + Firebase
Intro to Front End Development with Angular + FirebaseIntro to Front End Development with Angular + Firebase
Intro to Front End Development with Angular + Firebase
 
Scaling AngularJS: Enterprise SOA on the MEAN Stack (Responsive Web & Mobile)
Scaling AngularJS: Enterprise SOA on the MEAN Stack (Responsive Web & Mobile)Scaling AngularJS: Enterprise SOA on the MEAN Stack (Responsive Web & Mobile)
Scaling AngularJS: Enterprise SOA on the MEAN Stack (Responsive Web & Mobile)
 
Zookeeper
ZookeeperZookeeper
Zookeeper
 
Creating MVC Application with backbone js
Creating MVC Application with backbone jsCreating MVC Application with backbone js
Creating MVC Application with backbone js
 
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Burgas Conf 21.06.2014 - Single page application Angularjs and NodejsBurgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Best node js course
Best node js courseBest node js course
Best node js course
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architecture
 
Node.js 101
 Node.js 101 Node.js 101
Node.js 101
 
AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
API Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
API  Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015 API  Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
API Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
 
Bhasma - Nano Medicine (Ancient India - Ayurveda)
Bhasma - Nano Medicine (Ancient India -  Ayurveda)Bhasma - Nano Medicine (Ancient India -  Ayurveda)
Bhasma - Nano Medicine (Ancient India - Ayurveda)
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 

Similaire à Node.js Workshop - Sela SDP 2015

Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tourcacois
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami SayarFITC
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebBhagaban Behera
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101Rami Sayar
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Lucas Jellema
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Building Applications With the MEAN Stack
Building Applications With the MEAN StackBuilding Applications With the MEAN Stack
Building Applications With the MEAN StackNir Noy
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.jsAyush Mishra
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
 
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?Christian Joudrey
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 

Similaire à Node.js Workshop - Sela SDP 2015 (20)

Node js beginner
Node js beginnerNode js beginner
Node js beginner
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Exploring Node.jS
Exploring Node.jSExploring Node.jS
Exploring 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 GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami Sayar
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
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
 
A java servers
A java serversA java servers
A java servers
 
A java servers
A java serversA java servers
A java servers
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Building Applications With the MEAN Stack
Building Applications With the MEAN StackBuilding Applications With the MEAN Stack
Building Applications With the MEAN Stack
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
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?
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 

Dernier

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
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
 
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
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
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
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 

Dernier (20)

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
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
 
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...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
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
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 

Node.js Workshop - Sela SDP 2015

  • 1. © Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com SELA DEVELOPER PRACTICE MAY 31 – JUNE 4, 2015 Nir Noy Consultant, Web, Sela @noynir Node.js
  • 2. Agenda Introduction - What is Node.js. File system. Building servers. Building APIs using modules, events and packages. Express Web framework.
  • 3. Introduction – What is Node.js ?
  • 4. What is Node.js A JavaScript runtime that is designed for asynchronous IO operations Very lightweight and fast Being used by a growing number of companies:
  • 5. The Node.js ecosystem Node.js has a rapidly growing ecosystem: Web frameworks: Express Socket.io Database support Sql Databases NoSql Databases Hosting and Cloud environments IIS, Azure Heroku Joyent
  • 6. Synchronous server operations // GET api/countries public string Get() { var client = WebRequest.Create("http://.../"); var response = client.GetResponse(); var stream = response.GetResponseStream(); var reader = new StreamReader(stream); return reader.ReadToEnd(); } Blocking I/O operation
  • 7. The Cost of I/O I/O Operations are expensive. I/O Source CPU Cycles L1 – Cache 3 L2 – Cache 14 RAM 250 Disk 41,000,000 Network 240,000,000
  • 8. Handling I/O Waiting for I/O operations to complete is one of the most common performance bottlenecks. There are several common solutions to handle it: Synchronous Pros: simple. Cons: blocking, can hold up other requests. Fork a new process Pros: efficient, not holding up other requests. Cons: does not scale, ~100 connections=~100 processes .
  • 9. Handling I/O Threads: Pros: efficient, not holding up other requests but more lightweight then executing another process Cons: memory-expensive - ~1MB per thread, complicated, need to worry about controlling access and shared resources. Traditional web-servers (IIS, Apache) today use an optimized thread-per-connection model that uses thread pools.
  • 10. Handling I/O in Node.js Node.js runs your code on a single thread. All I/O operations are asynchronous and Non- Blocking Internally threads and processes are used but not explicitly exposed to your code. When an I/O operation completes, an event is triggered and the result is passed to a callback function.
  • 11. Why Node.js Lightweight and efficient using non-blocking I/O keeps memory consumption stable by reducing the number of threads. Less context switching overhead. Concurrency using non-blocking I/O keeps the main thread responsive and allowing it support tens of thousands of concurrent connections. One Language allows reuse of resources between the client and server.
  • 13. What Node.js code looks like
  • 14. Node.js Event loop I/O operations are evented and external events are handled by Node’s Event loop. Javascript functions are passed to a queue and invoked when the return value from their current I/O calls is available. I/O Callbacks are invoked synchronously by the order they returned.
  • 15. Node.js Event loop Server Async Workers DDB, FS, Network, etc… Request Response Request Response
  • 17. Node.js Usage Running CPU intensive tasks (e.g. long running loops) on Node.js’s main thread should be avoided as it will block handling other requests to the server. Running CPU intensive tasks can be scaled out to multiple node processes. Node.js can run a managed cluster of multiple processes to scale out an entire application.
  • 18. The Node.js process Unlike client-side JavaScript Node.js does not run inside a browser window. There are no window or document global objects The Node process provides the runtime for node programs
  • 19. Node.js process architecture Node.exe V8 CommonJS – Module loader JavaScript Application libuv OS Core Javascript modules for file system, network, http, etc… Responsible for loading modules and manage dependencies. Using CommonJS’s module definition. Multi-platform library written in C that handles all async I/O operations. Google’s Javascript Engine. Compiles the Javascript code to native machine code.
  • 20. The process global object The process global object provides an API for interacting with the process Access command-line arguments Get the execution path, current platform, node.js version Environment variables Accessing standard input/output
  • 21. Demo Running Node from the command line
  • 23. File System Node.js provides the fs module for file system operations: Readingwriting files Getting file metadata Reading directories Creating a file watcher Most fs functions have synchronous APIs
  • 24. Reading Directories var fs = require('fs'); // this method reads the content of a directory fs.readdir(process.argv[2], function(err,files){ files.forEach(function(file){ //Do something with file… }); });
  • 26. Reading files The fs module prvides different methods for reading file content: readFileSync reading the whole file synchronously readFile reading the whole file asynchronously createReadStream provides a stream based API for reading files
  • 27. var fs = require('fs'); //Async fs.readFile(process.argv[2],'utf-8', function (err, data) { if (err) throw err; console.log(data) }); //Read file sync var f = fs.readFileSync(process.argv[2],'utf-8'); console.log(f); Reading Files
  • 29. Streams Just like other frameworks Node.js use streams as an abstraction for reading/writing data. Just like most IO in Node.js, streams provide an event base API using the on method close, open data error When using streams, data is read in chunks and doesn’t block the main thread for the entire time the data is buffered into memory.
  • 30. Streams (cont.) var fs = require('fs'); var strm = fs.createReadStream(process.argv[2]); strm.setEncoding('utf8'); strm.on('data', function(data) { console.log('read from strm'); }); strm.on('end', function(){ console.log('ended strm') })
  • 31. The pipe method allows you to connect a readable stream as the destination of a writeable stream var fs = require("fs"); // Read File fs.createReadStream("input/people.json") // Write File .pipe(fs.createWriteStream("output/people.json")); Stream.pipe
  • 35. Building HTTP servers Node.js was originally designed as a platform for building web servers. Most Web applications are I/O Bound ~90% of a request’s processing time is spent on waiting for I/O to complete. Node.js async I/O mechanism provides node with high concurrency and a low memory footprint.
  • 36. Building HTTP servers (cont.) Node.js is designed to be scaled out to multiple processes and machines which makes it ideal for cloud hosting. The http module provides basic functionality for handling HTTP (client and server) Additional frameworks like Express and Restify provide higher level abstractions (like MVC)
  • 37. var http = require('http'); http.createServer(function(req,res){ var response = 'Hello World'; res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': response.length }); res.write(response); res.end(); }).listen(3000); Node Http Server
  • 39. The http.Server class The http.createServer() method is used to create a server. It returns an instance of the http.Server object. The http.Server provides a set of events request – fires on every incoming request. Connection -fires on every new tcp connection. Upgrade - fires on every incoming upgrade request.
  • 41. Receiving data HTTP allows server applications to receive data: Using the request URI Message body Use the url and querystring modules for parsing URLs and query strings. Message body can contain any format Being a JavaScript runtime, Node.js process JSON natively Other formats are supported through npm packages.
  • 42. var http = require('http'); var url = require('url') ; http.createServer(function (req, res) { var queryObject = url.parse(req.url,true).query; console.log(queryObject); res.writeHead(200); res.end('Feel free to add query parameters to the end of the url'); }).listen(8080); Parsing URL and Querystring
  • 43. Demo Using the URL and QueryString APIs
  • 44. Http streaming // handling incoming HTTP requests var handleRequests = function(req,res){ // creating an outgoing HTTP request req = http.request(options, responseCallback = function(response) { var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function(){ res.end(str); }); }); req.end(); };
  • 45. Chunked transfer encoding HTTP 1.1 introduced Chunked transfer encoding that allows messages to be sent in chunks. The Content-Length header is removed and a Transfer-Encoding:chunked header is added to the response. HTTP can send messages in chunks Write data in small chunks keeping a small memory footprint Freeing node’s single thread to serve more requests
  • 46. var http = require('http'); var handleRequests = function(req,res){ // creating an outgoing HTTP request var req2 = http.request(options, responseCallback = function(response) { res.writeHead(200, {'content-type': 'text/xml', 'Content- Encoding':'gzip'}) response.on('data', function (chunk) { res.write(chunk); }); response.on('end', function(){ res.end(); }); }); req2.end(); }; http.createServer(handleRequests).listen(3000); Chunked transfer encoding
  • 49. Building APIs using modules, events and packages
  • 50. CommonJS Modules Node.js uses CommonJS modules for structuring code. Modules are defined in separate .js files To consume a module use the require function
  • 51. Modules and Scopes Modules provide a simple mechanism for creating scopes in JavaScript Members defined inside a module are not accessible outside To expose a member use the exports object This allow CommonJS to simplify dependency resolution
  • 53. The Global object Unlike browsers the top-level scope in Node.js is the module not global To expose objects globally (across modules) you can add them to the global object
  • 55. Node Package Manager (NPM) The Node Package Manager (NPM) provides a management mechanism for modules: Download and install Version management Deployment
  • 57. Managing Dependencies NPM packages are managed in a file called package.json package.json schema define fields like: name, description Version Dependencies Dependencies are being resolved during NPM install
  • 58. { "name": "app", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.10.2", "cookie-parser": "~1.3.3", "debug": "~2.1.1", "express": "~4.11.1", "jade": "~1.9.1", "lodash": "^3.3.1", "morgan": "~1.5.1", "serve-favicon": "~2.2.0" } } A look at Package.json
  • 59. Demo A look at package.json
  • 60. Managing Dependencies NPM packages are installed inside a folder named node_modules The folder is created inside the path where the “npm install …” was executed. When a npm module is required node will look it up inside the node_modules folder of the current path. If the module is not found it is recursively searched up the folder tree.
  • 62. The EventEmitter Most of Node.js's APIs are event based The events module provides the event emitter object for emitting events. Events are fired through the emit method and can be watched using the on method.
  • 66. Introduction to Express Node.js http module provides bare-bones HTTP server functionality Building a modern web application server would require implementing many common features such as: Routing Session Management Cookies & Requests Parsers Request Logging
  • 67. Introduction to Express Express is a web application framework inspired by Sinatra. Express middleware provides an expendable Http pipeline on top of Node.js's httpServer An Express application is essentially a series of middleware calls A middleware is simply a function with access to the request object, response object and a callback to next middleware in line.
  • 68. Express is available through npm $ npm install express --save Express provides a generator tool to quickly create an application skeleton. $ npm install express-generator –g //run $ express -h Express Installation
  • 70. Routing is one of the pillars of Express To create a route use the app.verb convention // respond with "Hello World!" on the homepage app.get('/', function (req, res) { res.send('Hello World!'); }) // accept POST request on the homepage app.post('/', function (req, res) { res.send('Got a POST request'); }) // accept PUT request at /user app.put('/user', function (req, res) { res.send('Got a PUT request at /user'); }) Routing
  • 71. Routers An Express application might have a large number of routes defined. Maintaining All of them in a single file can be a pain. Routers helps you keep your routes clean, organized and modular. Routers are defined in a separate node modules and used as middlewares.
  • 72. A router is an isolated instance of middlewares and routes. The router can have middleware and http VERB routes added just like an application. var router = express.Router([options]); router.get('/events', function(req, res, next) { // .. some logic here .. like any other middleware // .. }); Routers (cont.)
  • 74. Routing and Parameters Express support parameters as part of the URI Declare a parameter in the URI by using a “:” in front of it Access query-string parameters using req.query Use regular expressions To set a parameter as optional add a “?” suffix.
  • 77. Express application settings can be set using app.set() and retrieved using app.get() You can also set middleware functions using app.use(). // this middleware will be executed for every request to the app app.use(function (req, res, next) { console.log('Time: %d', Date.now()); next(); }) Configuring Express
  • 78. Views are template based UI mechanism Express support many view-engines including: Jade JSHtml EJS View engines are defined by setting the ‘view- engine’ variable app.set('view engine', 'jade'); // view engine setup app.set('views', path.join(__dirname, 'views')); Views
  • 79. Jade Jade is Express default view-engine It is based on Haml it provide a clean syntax for generating HTML Tab based Full support for HTML
  • 80. doctype html head title My Page body div.jumbotron h1#title This is my Page p how do you like my styling? Jade template
  • 82. Jade fully support JavaScript using the script element: Linking to external JS files Embedding in-line JavaScript To setup static content serving in Express use the built-in static middleware. app.use(express.static(__dirname+'/public')); // multiple static folders can be defined. Mixing up JavaSript & Jade
  • 84. Blocks In most applications, some UI components are used throughout the application Blocks provide a way to provide a common layout that is shared among views
  • 85. doctype html head title My Application link(href='/css/bootstrap.min.css', rel="stylesheet") link(href='/css/bootstrap-theme.min.css', rel="stylesheet") body div.page-header h1 This is my Application div.container-fluid block content Jade Layout Template
  • 86. extends layout block content div.container p this is a container div and some more text here Jade Template Using Layout
  • 88. Model Express provides a mechanism to insert data- models into views The rendering of the complete artifact is up to the view engine
  • 89. extends layout block content div.container.bg-danger h1 oops...,Server error p #{error} Rendering data in Jade
  • 91. Functionality to Express apps are added via third-party middleware installed through npm. $ npm install cookie-parser var express = require('express'); var app = express(); var cookieParser = require('cookie-parser'); // load the cookie parsing middleware app.use(cookieParser()); Express Middlewares
  • 92. Common Express Middlewares Express 4.0 Name body-parser compression cookie-session morgan cookie-parser express-session static-favicon response-time errorhandler method-override connect-timeout vhost csurf
  • 93. var express = require('express') var bodyParser = require('body-parser') var app = express() // parse application/json app.use(bodyParser.json()) app.use(function (req, res) { res.setHeader('Content-Type', 'text/plain') res.write('you posted:n') res.end(JSON.stringify(req.body, null, 2)) }) The body-parser middleware
  • 94. var express = require('express') var session = require('express-session') var app = express() app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true })); app.use(function(req, res, next) { var sess = req.session if (sess.views) { sess.views++ } else { sess.views = 1 res.end('welcome to the session demo. refresh!') } }) Express-Session
  • 97. Summary Node.js is not just for building servers It allows JavaScript to run outside of browsers and perform asynchronous IO It is asynchronous by nature Node.js runs your code on a single thread. Lightweight, fast and extremely cool. nirn@sela.co.il | @noynir

Notes de l'éditeur

  1. Talk about yourself Ask how many write server code? How many .net? Something about your references are from the .net world Anybody from bat-yam
  2. Ask what is node.JS? Probably get an answer “Server side javascript”
  3. Explain the exact definition, more to come on async io Small memory footprint and fast because doesn’t sit on top of a framework, more to come… All the big players are using this which makes node a safer bet because these companies are actively taking part in node development (Microsoft on the windows side…) and have interest in moving this technology forward.
  4. In addition to companies node.js has a very active community What is npm? Npm has ~150 packages, nuget ~37
  5. What seems to be wrong in this code?? Client.getResponse is a blocking I/O Operation. I/O Operation are costly and have impact on performance mostly because they take time and are blocking our code.
  6. Take a look at the bottom 2 lines and see the Hugh difference. The actual time depends on hardware.
  7. So how does node.js handles IO? Your code runs on a single thread, very important to be in our state of mind cause we can cause to be blocking. What happens when we want to IO? -> async, non blocking. Everything runs with events we give a callback function and once io completes the callback executes. Internally it runs threads, but not the same threads we use, but kernel level threads run by the OS.
  8. So why is this model good for us?-> Explain the restaurant analogy. On large scales opening threads on each connection is not good enough.
  9. Explain the basic node concepts: Modules and how we import them using require The use of callbacks
  10. Explain why javascript?
  11. So how does the async io is managed? -> event loops. Node.js runs on events, every callback is inserted in to a queue, that check in a loop all the time Once io completes the callback in the queue is marked completed and when node gets to it he will execute it. Important!! callback are invokes sync.
  12. Show 2_setTimeout add a for loop with 10000 iterations inside the first callback and show how it effects the execution of the second one
  13. Run the 1_AsyncServer demo from the command line Use the REPL and do some basic JavaScript
  14. Run the 3_FileSystem – list.js demo from the command line
  15. Run the 3_FileSystem demos First -> Explain it is blocking node’s only thread Second -> read-> readfilesync.js fileasync.js -> Not blocking but is performed in a serial manner Third -> readstream.js -> explain streams
  16. Run the 3_FileSystem demos pipes
  17. Run the 1_AsyncServer demo from the command line Use the REPL and do some basic JavaScript
  18. Run the 1_AsyncServer demo from the command line Use the REPL and do some basic JavaScript
  19. 50
  20. 51
  21. 52
  22. 54
  23. 56
  24. 59
  25. 61
  26. 63
  27. 73
  28. 76
  29. 81
  30. 83
  31. 87
  32. 90
  33. 95