SlideShare a Scribd company logo
Welcome To The Server
             Writing server-side APIs with Node.JS


Monday, March 18, 13
Whoami




                       Ynon Perek

                       http://ynonperek.com

                       ynon@ynonperek.com




Monday, March 18, 13
Agenda




                       Before You Build A Web Server

                       Node JavaScript and Concepts

                       Express Framework




Monday, March 18, 13
Before You Build A Server




                       What is the role of a
                       web server ?




Monday, March 18, 13
Before You Build A Server




                       The web server connects multiple clients

                       The web server can aggregate data

                       The web server has more resources




Monday, March 18, 13
Before You Build A Server




                               GET data




                               Here It Is




Monday, March 18, 13
HTTP Protocol



                       Clients talk to web servers in a protocol called HTTP

                       HTTP is built around a request/response model

                       HTTP is text-based

                       Each message has headers and data




Monday, March 18, 13
HTTP Demo

                       HTTP Request Headers



            GET / HTTP/1.1
            Host: ynonperek.com
            Connection: keep-alive
            Cache-Control: max-age=0
            User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11
            (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
            Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
            Accept-Encoding: gzip,deflate,sdch
            Accept-Language: en-US,en;q=0.8
            Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
            If-None-Match: "1354952510"
            If-Modified-Since: Sat, 08 Dec 2012 07:41:50 +0000




Monday, March 18, 13
HTTP Demo

                       HTTP Response Headers
           HTTP/1.1 200 OK
           Date: Sat, 08 Dec 2012 07:41:57 GMT
           Server: Apache/2.2.16 (Debian)
           X-Powered-By: PHP/5.3.18-1~dotdeb.0
           Expires: Sun, 19 Nov 1978 05:00:00 GMT
           Last-Modified: Sat, 08 Dec 2012 07:41:57 +0000
           Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
           ETag: "1354952517"
           Content-Language: en
           X-Generator: Drupal 7 (http://drupal.org)
           Vary: Accept-Encoding
           Content-Encoding: gzip
           Content-Length: 4482
           Keep-Alive: timeout=15, max=97
           Connection: Keep-Alive
           Content-Type: text/html; charset=utf-8



Monday, March 18, 13
What Is A Web Server




                       A program that
                       “speaks” HTTP

                       Answer HTTP requests
                       from clients




Monday, March 18, 13
What Is A Web Server



                                  SERVER CODE


                                  APPLICATION
                                     CODE




Monday, March 18, 13
Types of Web Servers



                       Generic web servers:
                       Apache, Nginx, IIS

                       Language-specific
                       servers: JBoss, Tomcat,
                       Starman, Tornado,
                       Event Machine, Thin




Monday, March 18, 13
Story Of Node.JS



                                  Ryan Dahl wrote it as a
                                  tool to write web
                                  servers

                                  Written in JS, and
                                  based on V8 engine

                                  Started at 2009




Monday, March 18, 13
How To Build A Web Server



                       Take an existing
                       skeleton

                       Color it any way you
                       like

                       Enjoy




Monday, March 18, 13
Demo: Simple http server



                  var http = require('http');
                   
                  var handler = function(request, response) {
                    response.write('RESISTANCE IS FUTILE');
                    response.end();
                  };
                   
                  var server = http.createServer( handler );
                   
                  server.listen(8080);




Monday, March 18, 13
Q&A




Monday, March 18, 13
Lab: Getting Started


                       Write a Node server that sends your name to the
                       browser

                       Write a Node server that returns the current time to the
                       browser

                       Write a Node server that sends the requested url back to
                       the browser

                       Use the docs: http://nodejs.org/api/http.html




Monday, March 18, 13
Node.JS Basics
             Module Pattern and Package Management




Monday, March 18, 13
Agenda


                       Welcome To Node

                       The Global Object

                       The Module System

                       Node Packages

                       Common Node




Monday, March 18, 13
Welcome To Node



                       Install by downloading the installer from:

                       http://nodejs.org/download/

                       Recommended Reading:

                       http://www.nodebeginner.org/




Monday, March 18, 13
What’s Missing



                       No window

                       No document

                       No DOM

                       You can still use
                       console.log




Monday, March 18, 13
Welcome To Node



                                                 var x = 5;
                       Run a simple JavaScript   var y = 9;
                       file using                 
                                                 var z = x + y;
                       node hello.js              
                                                 console.log('5 + 9 = ' + z);




Monday, March 18, 13
Global Objects



                       In a browser, window is the global object and it is shared
                       between all JS files

                       In Node, global object is defined per-file

                       It’s harder to pollute global namespace

                       Use other files with require




Monday, March 18, 13
Demo: Require




Monday, March 18, 13
Demo: Require

                       Load a file names twitter.js from current working
                       directory

                       The file returns an object we can use



             var t = require('./twitter.js');
              
             t.tweet('I can has cheezburger');




Monday, March 18, 13
Demo: Require


                       Inside an included file, a special object named exports is
                       provided, and returned to the caller.



                       exports.tweet = function( text ) {
                           console.log( text );
                       }




Monday, March 18, 13
Advantages




                       Cleaner namespaces

                       Better code is now easier to write




Monday, March 18, 13
Node Package Management



                       Many modules are distributes online

                       There’s even an online list of available free modules you
                       can use

                       There’s even a utility that automatically downloads
                       modules from that repository




Monday, March 18, 13
A Node Package




                       A package is a collection of modules with a description
                       JSON file

                       You can depend on a package for your application by
                       specifying dependencies in your package.json file




Monday, March 18, 13
npm repository




                       Currently hosts ~25,000 packages

                       Search and browse online:

                       https://npmjs.org/




Monday, March 18, 13
Demo: Using a package




Monday, March 18, 13
Demo: package.json

           {
                       "name" : "my-app",
                       "version" : "0.0.1",
                       "private" : true,
                       "dependencies" : {
                           "colors" : "*"
                       }
            
           }


Monday, March 18, 13
Demo: app.js



             var colors = require('colors');
              
             console.log('Good Morning'.blue);
             console.log('Hello World'.rainbow);




Monday, March 18, 13
Lab


                       Write a node module that provides the following
                       functions:

                         sum(x, y, z, ... ) - returns the sum total of all
                         numbers passed to it

                         longer_than( n, str1, str2, str3, ... ) - returns an array
                         of all strings longer in length than number n

                       Write a test program that requires(...) for the module




Monday, March 18, 13
Q&A




Monday, March 18, 13
Common Node


                       Working With Buffers

                       Command Line Arguments

                       Working With Files

                       Sending Email

                       Getting Data From Other Websites




Monday, March 18, 13
Node Buffers


                       Memory


                                   Buffer




Monday, March 18, 13
Node Buffers




                       JavaScript does not have native binary data type

                       Node adds the new type: Buffer




Monday, March 18, 13
Thumb Rule




                       String = Buffer + Encoding




Monday, March 18, 13
Working With Buffers



                       Construct a buffer with:

                         new Buffer( size )

                         new Buffer( array )

                         new Buffer( String, Encoding )




Monday, March 18, 13
Working With Buffers


                       Write data with:

                         buf.write( string, offset, length, encoding )

                         offset - where to start writing (default 0)

                         length - maximum length to write

                         encoding - defaults to utf8




Monday, March 18, 13
Working With Buffers




                       Convert a buffer to string with:

                         buf.toString( encoding, start, end )

                         default encoding is utf8




Monday, March 18, 13
Other Buffer Methods



                       buf.slice( start, end ): returns a new buffer for a
                       memory slice. Data is shared.

                       buf.fill( value, offset, end ): fills a buffer with value.

                       API Docs: http://nodejs.org/api/buffer.html




Monday, March 18, 13
Command Line Arguments



                       Use process.argv array    console.dir( process.argv );
                       to access all process
                       arguments                 if ( process.argv.length === 7 )
                                                 {
                       Note the first two are:       console.log('Bingo !');
                       ‘node’ (process name)     }
                       ‘app.js’ (file name)




Monday, March 18, 13
Working With Files




                       All file operations have Sync and Async version

                       Sync blocks until the operation is done

                       ASync takes a callback




Monday, March 18, 13
Reading A File ASync

                                                                             Callback
                       Use fs.readFile to read   var fs = require('fs');
                       a file ASync
                                                 var filename = process.argv[2];
                                                 fs.readFile( filename, function(err, data) {
                       Default encoding is           if ( err != null ) {
                       utf8, but you can pass            console.log('Error: ' + err);
                       another as the second             process.exit(2);
                                                     }
                       argument
                                                       process.stdout.write( data );
                       process.stdout.write      });

                       prints data as-is




Monday, March 18, 13
Writing To A File ASync


                                                   var fs = require('fs');

                       use fs.writeFile to write   var filename = 'output.txt';
                       data (String or Buffer)
                                                   fs.writeFile( filename, 'Hello Worldn',
                       to a file                     function(err, data) {
                                                       console.log('File Write Done');
                       Node the execution            });

                       order                       console.log('Starting To Write To File');




Monday, March 18, 13
Read and Write Streams


Monday, March 18, 13
Read Stream



                       Events: readable, end, error, close(*)

                       Methods:

                         setEncoding(encoding)

                         pipe(destination)




Monday, March 18, 13
Read Stream Demo

             var fs = require('fs');
              
             var f1 = fs.createReadStream('f1.js');
              
              
             f1.on('readable', function() {
               var data = f1.read();
               console.log( data.toString() );
             });



Monday, March 18, 13
Write Stream



                       Events: drain, error, close

                       Methods:

                         write( String or Buffer)

                         end( Optional String or Buffer)




Monday, March 18, 13
Example: Writing To Stream



                       Use                    var fs = require('fs');
                                               
                       fs.createWriteStream   var out =
                                              fs.createWriteStream('output.txt');
                       to create a writable    
                       stream                 out.write('Hellon');
                                              out.write('-----nn');
                                              out.write('Node Streams are cooln');
                       Use write(...) to       
                                              out.end();
                       append data




Monday, March 18, 13
Lab



                       Write a node program that creates a new file and writes
                       your name and home address inside. After writing, print
                       out a message to the console.

                       Write a node program that takes two files as command
                       line arguments, and copies the first to the second




Monday, March 18, 13
Sending Email




                       Use nodemailer to send emails from node.js app

                       Demo: https://github.com/andris9/Nodemailer/blob/
                       master/examples/example_smtp.js




Monday, March 18, 13
Getting Data From Websites




                             GET data




                            Here It Is




Monday, March 18, 13
Node HTTP Requests



                       The request module implements an HTTP client

                       use request( options, callback ) to get the data

                       callback signature:

                         function( error, response, body ) { ... }




Monday, March 18, 13
Demo: Facebook Graph

             var request = require('request');
              
             request('http://graph.facebook.com/ynonp', function(err,
             response, body ) {
               var me = JSON.parse( body );
               console.log( me.id );
             });




Monday, March 18, 13
Demo: Tweets About
                             Israel
           var request = require('request');
            
           request('http://search.twitter.com/search.json?q=israel',

           function(err, response, body ) {

               var data = JSON.parse( body );
               for ( var i=0; i < data.results.length; i++ ) {
                 console.log('---');
                 console.log( data.results[i].from_user + ':' +
                              data.results[i].text );

             }
           });



Monday, March 18, 13
Lab


                       YQL can help you find data online

                       Use the forecast at this URL:
                       http://query.yahooapis.com/v1/public/yql?q=select
                       %20item%20from%20weather.forecast%20where
                       %20woeid%3D%221968212%22&format=json

                       and print out the temperatures in Celsius for today and
                       tomorrow in Tel Aviv




Monday, March 18, 13
Q&A




Monday, March 18, 13
Express: Web
             Framework




Monday, March 18, 13
Express




                       A web framework is a
                       package that helps you
                       build your web
                       application




Monday, March 18, 13
Express


                       It handles HTTP
                       request/response and
                       headers

                       It handles sessions

                       It handles errors

                       It serves static files

                       And more...




Monday, March 18, 13
Who Uses Express


                       http://geekli.st/

                       https://count.ly/

                       http://balloons.io/

                       http://yummly.com/

                       Full List: http://expressjs.com/applications.html




Monday, March 18, 13
var express = require('express');
                              var app = express();
                               
                               
       Express Demo           app.get('/', function(req, res) {
                                res.send('Hello Wrold');
                              });
       Simple Static Server    
                              app.listen(8080);




Monday, March 18, 13
Express Overview


                       Use require(‘express’) to get a reference to the
                       express object

                       Use express() to get a reference to the express
                       application object

                       Then configure routes with app.get(...) and
                       app.post(...)




Monday, March 18, 13
Express Routes



                       A route handles incoming request

                       HTTP request methods:

                         OPTIONS, GET, POST,

                         PUT, DELETE, TRACE, CONNECT




Monday, March 18, 13
Express Routes

                       Each route takes a callback.

                       Keep your callbacks REAL FAST

                       While running a route handler, server is not available to
                       handle other requests


             app.get('/hello', function(req, res) {
                 res.send('Hello World');
             });



Monday, March 18, 13
Express Routes


                       You can also send files


        app.get('/logo.png', function(req, res) {
            res.sendfile('./public/images/logo.png');
        });




Monday, March 18, 13
Express Routes

                       Or complete JSON objects

                       express automatically sets content-type


                app.get('/user.json', function(req, res) {
                    res.send({
                        username: 'amy',
                        password: 'tardis'
                    });
                });



Monday, March 18, 13
Request Parameters


                       A client can pass in
                       extra parameters in the
                       request

                       A GET request provides
                       parameters after the
                       URL

                       A POST request
                       provides parameters in
                       the body




Monday, March 18, 13
GET Parameters


                       If a URL is followed by a question mark (?), you can
                       pass key/value paris separated by & to the server

                       Examples:

                       http://www.google.com/?q=javascript

                       http://www.demo.com?op=add&x=5&y=7




Monday, March 18, 13
Getting The Params In Node


                                         app.get('/add', function(req, res) {
                                             var x = Number( req.param('x') );
                       You can access        var y = Number( req.param('y') );
                       request            
                       parameters by         res.send({
                       using req.param           'operation' : 'add',
                       function                  'x' : x,
                                                 'y' : y,
                       Example:                  'result' : x + y
                                             });
                                         });




Monday, March 18, 13
When Things Go Wrong




                       What should the server do ?

                       GET http://mathserver.com/?x=5




Monday, March 18, 13
One Solution:
             Use URL Parameters



                       http://www.math.com/add/5/10/




Monday, March 18, 13
Getting URL Parameters

                                        app.get('/mul/:x/:y', function(req, res) {
                                            var x = Number( req.param('x') );
                                            var y = Number( req.param('y') );
                       Node allows
                                         
                       treating part of
                                            res.send({
                       the URL as a
                                                'operation' : 'add',
                       parameter                'x' : x,
                                                'y' : y,
                       This way no              'result' : x * y
                       param is             });
                       missing           
                                        });




Monday, March 18, 13
Another Solution
             Handle Errors with next()




Monday, March 18, 13
Express Routes


                       Use the 3-arguments route handler to report errors

                       third argument is a function:

                         If called with no arguments raises HTTP 404

                         If called with arguments raises HTTP 500

                       Don’t forget to return after using next()




Monday, March 18, 13
Express Routes


          app.get('/user.json', function(req, res, next) {
              var userid = req.param('id');
              if ( userid == null ) {
                  next('Invalid User');
                  return;
              }
           
              res.send({ username: 'amy' });
          });




Monday, March 18, 13
Lab #1


                       Write an express web server that responds to the
                       following routes:

                       GET /add - takes 2 params and returns their sum as a
                       JSON object

                       GET /multiply - takes 2 params and returns their
                       multiplication as a JSON object

                       GET /count - returns the total count of operations
                       performed so far




Monday, March 18, 13
Lab #2



                       Write a “wall” server in express

                       POST /wall - adds a message to the wall

                       GET /wall - returns a JSON array with all messages

                       Write an HTML file with a form to test the POST request




Monday, March 18, 13
Getting The Data
             Use jQuery’s ajax calls from the client


Monday, March 18, 13
jQuery Functions



                       $.get - sends a get request to the server.
                       Takes a url, optional data, success handler and data
                       type.

                       $.post - sends a post request to the server.
                       Takes a url, optional data, success handler and data
                       type.




Monday, March 18, 13
get/post Examples

                  $.get(‘test.php’);


                  $.post(‘test.php’, { name : ‘john’,
                  time: ‘2pm’ });


                  $.get(‘test.php’, function(data) {
                    alert(data);
                  });



Monday, March 18, 13
$.ajax



                       Gain full control over the request

                       Can handle errors

                       get/post are actually just shortcuts for this one

                       Takes url and settings object




Monday, March 18, 13
$.ajax Settings


                       error: error handler callback

                       success: success handler callback

                       context: the ‘this’ pointer of callbacks

                       data: data object to send

                       url: the url to use

                       Full docs: http://api.jquery.com/jQuery.ajax/




Monday, March 18, 13
Example: $.ajax


                       $.ajax({
                          type: "POST",
                          url: "some.php",
                          data: "name=John&location=Boston",
                          success: function(msg){
                            alert( "Data Saved: " + msg );
                          }
                        });




Monday, March 18, 13
Demo: “live” wall with
             ajax




Monday, March 18, 13
Q&A




Monday, March 18, 13
Ajax: Lab 1



                       Add client GUI to the lab on page 44 (math server)

                       Allow sum/multiply and show the result

                       Every second, check number of actions performed and
                       update the display




Monday, March 18, 13
Ajax: Lab 2


                       Create a weather application

                       Use Node.JS for server side.

                       Use wunderground to get weather report based on lat/
                       long. URL:
                       http://api.wunderground.com/api/API_KEY/geolookup/
                       q/37.776289,-122.395234.json

                       App should show a picture of Sun or Rain based on
                       current weather




Monday, March 18, 13
Express
             Middleware
             Pipeline
             How the middleware pipeline
             works for you




Monday, March 18, 13
Sample Pipeline



                            1
        Request                      Favicon
                                          2
                            Do you need a favicon ?
                        3                                  4

                       Yes - Here it is        No - Next middleware


Monday, March 18, 13
Sample Pipeline



                         1
        Request                   logger
                                       2
                       Write down the request to log
                                                       3

                                            Next middleware


Monday, March 18, 13
Sample Pipeline



                            1
        Request                       Router
                                           2
                            Is there a named route ?
                        3                                  4

                       Yes - Here it is        No - Next middleware


Monday, March 18, 13
Sample Pipeline



                            1
        Request                       Static
                                           2
                        Is there a matched public file ?
                        3                                  4

                       Yes - Here it is        No - Next middleware


Monday, March 18, 13
Sample Pipeline



                           1
        Request                    Error
                                           2
                                  Bye Bye
                       3




Monday, March 18, 13
Error Handling In Pipeline



                 app.get('/user.json', function(req, res, next) {
                     var userid = req.param('id');
                     if ( userid == null ) {
                         return next('Invalid User');       
                     }
                  
                     res.send({ username: 'amy' });
                 });




Monday, March 18, 13
Custom Express Middleware



                       Let’s write a simple middleware for returning visitors

                       If it’s the first visit, show a banner

                       If it’s a later visit, show another banner

                       Use jade for the template




Monday, March 18, 13
Lab




                       Write a cross domain ajax middleware

                       Add CORS to each response headers

                       Bonus: Initialize with source domains




Monday, March 18, 13
Other Middlewares


                       Authentication is performed by a middleware. Demo:
                       https://github.com/visionmedia/express/tree/master/
                       examples/auth

                       Static middleware will serve a static path

                       bodyParser automatically turns request body to an
                       object

                       compress() automatically compresses responses




Monday, March 18, 13
Q&A




Monday, March 18, 13
Thank You



                       Keynote and Extras: ynonperek.com

                       Photos From:

                         http://123rf.com

                         http://www.flickr.com/photos/crazyeddie/
                         1463295872/




Monday, March 18, 13

More Related Content

What's hot (20)

KEY
Pushing the web — WebSockets
Roland M
 
PDF
Integration with hdfs using WebDFS and NFS
Christophe Marchal
 
PDF
WebHDFS at King - May 2014 Hadoop MeetUp
huguk
 
PDF
Memcached Presentation
Asif Ali
 
ODP
Caching and tuning fun for high scalability @ phpBenelux 2011
Wim Godden
 
ODP
Caching and tuning fun for high scalability
Wim Godden
 
PPTX
Google Chromebook for the Enterprise: Yeah or Meh?
Ericom Software
 
PDF
Jetty and Tomcat
Diego Pacheco
 
PDF
Introduction to WebSockets
Gunnar Hillert
 
PPTX
Using memcache to improve php performance
Sudar Muthu
 
PDF
[Hello world 오픈세미나]varnish로 웹서버성능 향상시키기
NAVER D2
 
PDF
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Ontico
 
PDF
hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...
Michael Stack
 
PPTX
Summer of Fuzz: macOS
Jeremy Brown
 
PDF
Less and faster – Cache tips for WordPress developers
Seravo
 
PDF
Varnish Oscon 2009
Artur Bergman
 
PDF
Cookies and sessions
salissal
 
PPT
Memcache
Abhinav Singh
 
PDF
HTML5 multimedia - where we are, where we're going
brucelawson
 
PPT
Cometdの紹介
Daisuke Sugai
 
Pushing the web — WebSockets
Roland M
 
Integration with hdfs using WebDFS and NFS
Christophe Marchal
 
WebHDFS at King - May 2014 Hadoop MeetUp
huguk
 
Memcached Presentation
Asif Ali
 
Caching and tuning fun for high scalability @ phpBenelux 2011
Wim Godden
 
Caching and tuning fun for high scalability
Wim Godden
 
Google Chromebook for the Enterprise: Yeah or Meh?
Ericom Software
 
Jetty and Tomcat
Diego Pacheco
 
Introduction to WebSockets
Gunnar Hillert
 
Using memcache to improve php performance
Sudar Muthu
 
[Hello world 오픈세미나]varnish로 웹서버성능 향상시키기
NAVER D2
 
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Ontico
 
hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...
Michael Stack
 
Summer of Fuzz: macOS
Jeremy Brown
 
Less and faster – Cache tips for WordPress developers
Seravo
 
Varnish Oscon 2009
Artur Bergman
 
Cookies and sessions
salissal
 
Memcache
Abhinav Singh
 
HTML5 multimedia - where we are, where we're going
brucelawson
 
Cometdの紹介
Daisuke Sugai
 

Viewers also liked (20)

PDF
Getting Started - MongoDB
Wildan Maulana
 
PDF
Carolina Counts: An Update on the Bain Consulting Report
ldconrad
 
PPTX
Bain Resume Sample
ConsultingFact.com
 
PDF
Digital Data Tips Tuesday #1 - Tag Management: Simo Ahava - NetBooster
Webanalisten .nl
 
PPTX
Workshop
Beth Kanter
 
PPTX
Datomic
Jordan Leigh
 
PDF
Datomic
Christophe Marchal
 
PPT
Datomic
jperkelens
 
PPTX
Waldorf Education
xMerodi
 
PDF
Backbone.js
daisuke shimizu
 
PPT
Tesco
Vishal Wadekar
 
PPT
Selena Gomez
guest5fa9931
 
PDF
Management Consulting
Alexandros Chatzopoulos
 
PPTX
Sap fiori
Anudeep Bhatia
 
PDF
French Property Market 2014
David Bourla
 
PPTX
intel core i7
kiran bansod
 
PPTX
Oprah Winfrey
Utkarsh Haldia
 
PDF
Clojure
Rohit Vaidya
 
PPTX
Medical devices
Somnath Zambare
 
Getting Started - MongoDB
Wildan Maulana
 
Carolina Counts: An Update on the Bain Consulting Report
ldconrad
 
Bain Resume Sample
ConsultingFact.com
 
Digital Data Tips Tuesday #1 - Tag Management: Simo Ahava - NetBooster
Webanalisten .nl
 
Workshop
Beth Kanter
 
Datomic
Jordan Leigh
 
Datomic
jperkelens
 
Waldorf Education
xMerodi
 
Backbone.js
daisuke shimizu
 
Selena Gomez
guest5fa9931
 
Management Consulting
Alexandros Chatzopoulos
 
Sap fiori
Anudeep Bhatia
 
French Property Market 2014
David Bourla
 
intel core i7
kiran bansod
 
Oprah Winfrey
Utkarsh Haldia
 
Clojure
Rohit Vaidya
 
Medical devices
Somnath Zambare
 
Ad

Similar to Node JS (20)

PDF
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Ran Mizrahi
 
PDF
Treinamento frontend
Adrian Caetano
 
PDF
Node.js and express
JoaquimSerafim
 
PDF
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
Viktor Todorov
 
PDF
Comet: Making The Web a 2-Way Medium
Joe Walker
 
PDF
Porting Rails Apps to High Availability Systems
Marcelo Pinheiro
 
PPTX
Introduction to NodeJS
Gobinda Karmakar ☁
 
PDF
Bkbiet day1
mihirio
 
PPTX
Webtechnologies
-jyothish kumar sirigidi
 
PPT
02 intro
babak mehrabi
 
PPTX
Node js introduction
Joseph de Castelnau
 
PDF
Hammering Responsive Web Design Into Shape
Ken Tabor
 
PPT
INLS461_day14a.ppt
webhostingguy
 
PDF
Ten practical ways to improve front-end performance
Andrew Rota
 
PDF
Profiling PHP with Xdebug / Webgrind
Sam Keen
 
PDF
Nodejs vatsal shah
Vatsal N Shah
 
PDF
php[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP apps
Pablo Godel
 
PDF
Are Today's Good Practices… Tomorrow's Performance Anti-Patterns
Andy Davies
 
PDF
Node in Real Time - The Beginning
Axilis
 
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Ran Mizrahi
 
Treinamento frontend
Adrian Caetano
 
Node.js and express
JoaquimSerafim
 
The Recording HTTP Proxy: Not Yet Another Messiah - Bulgaria PHP 2019
Viktor Todorov
 
Comet: Making The Web a 2-Way Medium
Joe Walker
 
Porting Rails Apps to High Availability Systems
Marcelo Pinheiro
 
Introduction to NodeJS
Gobinda Karmakar ☁
 
Bkbiet day1
mihirio
 
Webtechnologies
-jyothish kumar sirigidi
 
02 intro
babak mehrabi
 
Node js introduction
Joseph de Castelnau
 
Hammering Responsive Web Design Into Shape
Ken Tabor
 
INLS461_day14a.ppt
webhostingguy
 
Ten practical ways to improve front-end performance
Andrew Rota
 
Profiling PHP with Xdebug / Webgrind
Sam Keen
 
Nodejs vatsal shah
Vatsal N Shah
 
php[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP apps
Pablo Godel
 
Are Today's Good Practices… Tomorrow's Performance Anti-Patterns
Andy Davies
 
Node in Real Time - The Beginning
Axilis
 
Ad

More from Ynon Perek (20)

PDF
Regexp
Ynon Perek
 
PDF
Html5 intro
Ynon Perek
 
PDF
09 performance
Ynon Perek
 
PDF
Mobile Web Intro
Ynon Perek
 
PDF
Qt multi threads
Ynon Perek
 
PDF
Vimperl
Ynon Perek
 
PDF
Syllabus
Ynon Perek
 
PDF
Mobile Devices
Ynon Perek
 
PDF
Network
Ynon Perek
 
PDF
Architecture app
Ynon Perek
 
PDF
Cryptography
Ynon Perek
 
PDF
Unit Testing JavaScript Applications
Ynon Perek
 
PDF
How to write easy-to-test JavaScript
Ynon Perek
 
PDF
Introduction to Selenium and Ruby
Ynon Perek
 
PDF
Introduction To Web Application Testing
Ynon Perek
 
PDF
Accessibility
Ynon Perek
 
PDF
Angularjs
Ynon Perek
 
PDF
Js memory
Ynon Perek
 
PDF
Qt Design Patterns
Ynon Perek
 
PDF
Web Application Security
Ynon Perek
 
Regexp
Ynon Perek
 
Html5 intro
Ynon Perek
 
09 performance
Ynon Perek
 
Mobile Web Intro
Ynon Perek
 
Qt multi threads
Ynon Perek
 
Vimperl
Ynon Perek
 
Syllabus
Ynon Perek
 
Mobile Devices
Ynon Perek
 
Network
Ynon Perek
 
Architecture app
Ynon Perek
 
Cryptography
Ynon Perek
 
Unit Testing JavaScript Applications
Ynon Perek
 
How to write easy-to-test JavaScript
Ynon Perek
 
Introduction to Selenium and Ruby
Ynon Perek
 
Introduction To Web Application Testing
Ynon Perek
 
Accessibility
Ynon Perek
 
Angularjs
Ynon Perek
 
Js memory
Ynon Perek
 
Qt Design Patterns
Ynon Perek
 
Web Application Security
Ynon Perek
 

Recently uploaded (20)

PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Sustainable and comertially viable mining process.pdf
Avijit Kumar Roy
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PPTX
Darren Mills The Migration Modernization Balancing Act: Navigating Risks and...
AWS Chicago
 
PDF
Français Patch Tuesday - Juillet
Ivanti
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PDF
Are there government-backed agri-software initiatives in Limerick.pdf
giselawagner2
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PPTX
Top Managed Service Providers in Los Angeles
Captain IT
 
PDF
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
PDF
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
PDF
Ampere Offers Energy-Efficient Future For AI And Cloud
ShapeBlue
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
PDF
Shuen Mei Parth Sharma Boost Productivity, Innovation and Efficiency wit...
AWS Chicago
 
PDF
Upgrading to z_OS V2R4 Part 01 of 02.pdf
Flavio787771
 
PDF
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
PDF
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Sustainable and comertially viable mining process.pdf
Avijit Kumar Roy
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
Darren Mills The Migration Modernization Balancing Act: Navigating Risks and...
AWS Chicago
 
Français Patch Tuesday - Juillet
Ivanti
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Are there government-backed agri-software initiatives in Limerick.pdf
giselawagner2
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
Top Managed Service Providers in Los Angeles
Captain IT
 
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
Ampere Offers Energy-Efficient Future For AI And Cloud
ShapeBlue
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
Shuen Mei Parth Sharma Boost Productivity, Innovation and Efficiency wit...
AWS Chicago
 
Upgrading to z_OS V2R4 Part 01 of 02.pdf
Flavio787771
 
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
 
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 

Node JS

  • 1. Welcome To The Server Writing server-side APIs with Node.JS Monday, March 18, 13
  • 2. Whoami Ynon Perek http://ynonperek.com [email protected] Monday, March 18, 13
  • 3. Agenda Before You Build A Web Server Node JavaScript and Concepts Express Framework Monday, March 18, 13
  • 4. Before You Build A Server What is the role of a web server ? Monday, March 18, 13
  • 5. Before You Build A Server The web server connects multiple clients The web server can aggregate data The web server has more resources Monday, March 18, 13
  • 6. Before You Build A Server GET data Here It Is Monday, March 18, 13
  • 7. HTTP Protocol Clients talk to web servers in a protocol called HTTP HTTP is built around a request/response model HTTP is text-based Each message has headers and data Monday, March 18, 13
  • 8. HTTP Demo HTTP Request Headers GET / HTTP/1.1 Host: ynonperek.com Connection: keep-alive Cache-Control: max-age=0 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 If-None-Match: "1354952510" If-Modified-Since: Sat, 08 Dec 2012 07:41:50 +0000 Monday, March 18, 13
  • 9. HTTP Demo HTTP Response Headers HTTP/1.1 200 OK Date: Sat, 08 Dec 2012 07:41:57 GMT Server: Apache/2.2.16 (Debian) X-Powered-By: PHP/5.3.18-1~dotdeb.0 Expires: Sun, 19 Nov 1978 05:00:00 GMT Last-Modified: Sat, 08 Dec 2012 07:41:57 +0000 Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0 ETag: "1354952517" Content-Language: en X-Generator: Drupal 7 (http://drupal.org) Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 4482 Keep-Alive: timeout=15, max=97 Connection: Keep-Alive Content-Type: text/html; charset=utf-8 Monday, March 18, 13
  • 10. What Is A Web Server A program that “speaks” HTTP Answer HTTP requests from clients Monday, March 18, 13
  • 11. What Is A Web Server SERVER CODE APPLICATION CODE Monday, March 18, 13
  • 12. Types of Web Servers Generic web servers: Apache, Nginx, IIS Language-specific servers: JBoss, Tomcat, Starman, Tornado, Event Machine, Thin Monday, March 18, 13
  • 13. Story Of Node.JS Ryan Dahl wrote it as a tool to write web servers Written in JS, and based on V8 engine Started at 2009 Monday, March 18, 13
  • 14. How To Build A Web Server Take an existing skeleton Color it any way you like Enjoy Monday, March 18, 13
  • 15. Demo: Simple http server var http = require('http');   var handler = function(request, response) {   response.write('RESISTANCE IS FUTILE');   response.end(); };   var server = http.createServer( handler );   server.listen(8080); Monday, March 18, 13
  • 17. Lab: Getting Started Write a Node server that sends your name to the browser Write a Node server that returns the current time to the browser Write a Node server that sends the requested url back to the browser Use the docs: http://nodejs.org/api/http.html Monday, March 18, 13
  • 18. Node.JS Basics Module Pattern and Package Management Monday, March 18, 13
  • 19. Agenda Welcome To Node The Global Object The Module System Node Packages Common Node Monday, March 18, 13
  • 20. Welcome To Node Install by downloading the installer from: http://nodejs.org/download/ Recommended Reading: http://www.nodebeginner.org/ Monday, March 18, 13
  • 21. What’s Missing No window No document No DOM You can still use console.log Monday, March 18, 13
  • 22. Welcome To Node var x = 5; Run a simple JavaScript var y = 9; file using   var z = x + y; node hello.js   console.log('5 + 9 = ' + z); Monday, March 18, 13
  • 23. Global Objects In a browser, window is the global object and it is shared between all JS files In Node, global object is defined per-file It’s harder to pollute global namespace Use other files with require Monday, March 18, 13
  • 25. Demo: Require Load a file names twitter.js from current working directory The file returns an object we can use var t = require('./twitter.js');   t.tweet('I can has cheezburger'); Monday, March 18, 13
  • 26. Demo: Require Inside an included file, a special object named exports is provided, and returned to the caller. exports.tweet = function( text ) {     console.log( text ); } Monday, March 18, 13
  • 27. Advantages Cleaner namespaces Better code is now easier to write Monday, March 18, 13
  • 28. Node Package Management Many modules are distributes online There’s even an online list of available free modules you can use There’s even a utility that automatically downloads modules from that repository Monday, March 18, 13
  • 29. A Node Package A package is a collection of modules with a description JSON file You can depend on a package for your application by specifying dependencies in your package.json file Monday, March 18, 13
  • 30. npm repository Currently hosts ~25,000 packages Search and browse online: https://npmjs.org/ Monday, March 18, 13
  • 31. Demo: Using a package Monday, March 18, 13
  • 32. Demo: package.json {     "name" : "my-app",     "version" : "0.0.1",     "private" : true,     "dependencies" : {         "colors" : "*"     }   } Monday, March 18, 13
  • 33. Demo: app.js var colors = require('colors');   console.log('Good Morning'.blue); console.log('Hello World'.rainbow); Monday, March 18, 13
  • 34. Lab Write a node module that provides the following functions: sum(x, y, z, ... ) - returns the sum total of all numbers passed to it longer_than( n, str1, str2, str3, ... ) - returns an array of all strings longer in length than number n Write a test program that requires(...) for the module Monday, March 18, 13
  • 36. Common Node Working With Buffers Command Line Arguments Working With Files Sending Email Getting Data From Other Websites Monday, March 18, 13
  • 37. Node Buffers Memory Buffer Monday, March 18, 13
  • 38. Node Buffers JavaScript does not have native binary data type Node adds the new type: Buffer Monday, March 18, 13
  • 39. Thumb Rule String = Buffer + Encoding Monday, March 18, 13
  • 40. Working With Buffers Construct a buffer with: new Buffer( size ) new Buffer( array ) new Buffer( String, Encoding ) Monday, March 18, 13
  • 41. Working With Buffers Write data with: buf.write( string, offset, length, encoding ) offset - where to start writing (default 0) length - maximum length to write encoding - defaults to utf8 Monday, March 18, 13
  • 42. Working With Buffers Convert a buffer to string with: buf.toString( encoding, start, end ) default encoding is utf8 Monday, March 18, 13
  • 43. Other Buffer Methods buf.slice( start, end ): returns a new buffer for a memory slice. Data is shared. buf.fill( value, offset, end ): fills a buffer with value. API Docs: http://nodejs.org/api/buffer.html Monday, March 18, 13
  • 44. Command Line Arguments Use process.argv array console.dir( process.argv ); to access all process arguments if ( process.argv.length === 7 ) { Note the first two are: console.log('Bingo !'); ‘node’ (process name) } ‘app.js’ (file name) Monday, March 18, 13
  • 45. Working With Files All file operations have Sync and Async version Sync blocks until the operation is done ASync takes a callback Monday, March 18, 13
  • 46. Reading A File ASync Callback Use fs.readFile to read var fs = require('fs'); a file ASync var filename = process.argv[2]; fs.readFile( filename, function(err, data) { Default encoding is if ( err != null ) { utf8, but you can pass console.log('Error: ' + err); another as the second process.exit(2); } argument process.stdout.write( data ); process.stdout.write }); prints data as-is Monday, March 18, 13
  • 47. Writing To A File ASync var fs = require('fs'); use fs.writeFile to write var filename = 'output.txt'; data (String or Buffer) fs.writeFile( filename, 'Hello Worldn', to a file function(err, data) { console.log('File Write Done'); Node the execution }); order console.log('Starting To Write To File'); Monday, March 18, 13
  • 48. Read and Write Streams Monday, March 18, 13
  • 49. Read Stream Events: readable, end, error, close(*) Methods: setEncoding(encoding) pipe(destination) Monday, March 18, 13
  • 50. Read Stream Demo var fs = require('fs');   var f1 = fs.createReadStream('f1.js');     f1.on('readable', function() {   var data = f1.read();   console.log( data.toString() ); }); Monday, March 18, 13
  • 51. Write Stream Events: drain, error, close Methods: write( String or Buffer) end( Optional String or Buffer) Monday, March 18, 13
  • 52. Example: Writing To Stream Use var fs = require('fs');   fs.createWriteStream var out = fs.createWriteStream('output.txt'); to create a writable   stream out.write('Hellon'); out.write('-----nn'); out.write('Node Streams are cooln'); Use write(...) to   out.end(); append data Monday, March 18, 13
  • 53. Lab Write a node program that creates a new file and writes your name and home address inside. After writing, print out a message to the console. Write a node program that takes two files as command line arguments, and copies the first to the second Monday, March 18, 13
  • 54. Sending Email Use nodemailer to send emails from node.js app Demo: https://github.com/andris9/Nodemailer/blob/ master/examples/example_smtp.js Monday, March 18, 13
  • 55. Getting Data From Websites GET data Here It Is Monday, March 18, 13
  • 56. Node HTTP Requests The request module implements an HTTP client use request( options, callback ) to get the data callback signature: function( error, response, body ) { ... } Monday, March 18, 13
  • 57. Demo: Facebook Graph var request = require('request');   request('http://graph.facebook.com/ynonp', function(err, response, body ) { var me = JSON.parse( body ); console.log( me.id ); }); Monday, March 18, 13
  • 58. Demo: Tweets About Israel var request = require('request');   request('http://search.twitter.com/search.json?q=israel', function(err, response, body ) { var data = JSON.parse( body ); for ( var i=0; i < data.results.length; i++ ) { console.log('---'); console.log( data.results[i].from_user + ':' + data.results[i].text ); } }); Monday, March 18, 13
  • 59. Lab YQL can help you find data online Use the forecast at this URL: http://query.yahooapis.com/v1/public/yql?q=select %20item%20from%20weather.forecast%20where %20woeid%3D%221968212%22&format=json and print out the temperatures in Celsius for today and tomorrow in Tel Aviv Monday, March 18, 13
  • 61. Express: Web Framework Monday, March 18, 13
  • 62. Express A web framework is a package that helps you build your web application Monday, March 18, 13
  • 63. Express It handles HTTP request/response and headers It handles sessions It handles errors It serves static files And more... Monday, March 18, 13
  • 64. Who Uses Express http://geekli.st/ https://count.ly/ http://balloons.io/ http://yummly.com/ Full List: http://expressjs.com/applications.html Monday, March 18, 13
  • 65. var express = require('express'); var app = express();     Express Demo app.get('/', function(req, res) {   res.send('Hello Wrold'); }); Simple Static Server   app.listen(8080); Monday, March 18, 13
  • 66. Express Overview Use require(‘express’) to get a reference to the express object Use express() to get a reference to the express application object Then configure routes with app.get(...) and app.post(...) Monday, March 18, 13
  • 67. Express Routes A route handles incoming request HTTP request methods: OPTIONS, GET, POST, PUT, DELETE, TRACE, CONNECT Monday, March 18, 13
  • 68. Express Routes Each route takes a callback. Keep your callbacks REAL FAST While running a route handler, server is not available to handle other requests app.get('/hello', function(req, res) {     res.send('Hello World'); }); Monday, March 18, 13
  • 69. Express Routes You can also send files app.get('/logo.png', function(req, res) {     res.sendfile('./public/images/logo.png'); }); Monday, March 18, 13
  • 70. Express Routes Or complete JSON objects express automatically sets content-type app.get('/user.json', function(req, res) {     res.send({         username: 'amy',         password: 'tardis'     }); }); Monday, March 18, 13
  • 71. Request Parameters A client can pass in extra parameters in the request A GET request provides parameters after the URL A POST request provides parameters in the body Monday, March 18, 13
  • 72. GET Parameters If a URL is followed by a question mark (?), you can pass key/value paris separated by & to the server Examples: http://www.google.com/?q=javascript http://www.demo.com?op=add&x=5&y=7 Monday, March 18, 13
  • 73. Getting The Params In Node app.get('/add', function(req, res) {     var x = Number( req.param('x') ); You can access     var y = Number( req.param('y') ); request   parameters by     res.send({ using req.param         'operation' : 'add', function         'x' : x,         'y' : y, Example:         'result' : x + y     }); }); Monday, March 18, 13
  • 74. When Things Go Wrong What should the server do ? GET http://mathserver.com/?x=5 Monday, March 18, 13
  • 75. One Solution: Use URL Parameters http://www.math.com/add/5/10/ Monday, March 18, 13
  • 76. Getting URL Parameters app.get('/mul/:x/:y', function(req, res) {     var x = Number( req.param('x') );     var y = Number( req.param('y') ); Node allows   treating part of     res.send({ the URL as a         'operation' : 'add', parameter         'x' : x,         'y' : y, This way no         'result' : x * y param is     }); missing   }); Monday, March 18, 13
  • 77. Another Solution Handle Errors with next() Monday, March 18, 13
  • 78. Express Routes Use the 3-arguments route handler to report errors third argument is a function: If called with no arguments raises HTTP 404 If called with arguments raises HTTP 500 Don’t forget to return after using next() Monday, March 18, 13
  • 79. Express Routes app.get('/user.json', function(req, res, next) {     var userid = req.param('id');     if ( userid == null ) {         next('Invalid User');         return;     }       res.send({ username: 'amy' }); }); Monday, March 18, 13
  • 80. Lab #1 Write an express web server that responds to the following routes: GET /add - takes 2 params and returns their sum as a JSON object GET /multiply - takes 2 params and returns their multiplication as a JSON object GET /count - returns the total count of operations performed so far Monday, March 18, 13
  • 81. Lab #2 Write a “wall” server in express POST /wall - adds a message to the wall GET /wall - returns a JSON array with all messages Write an HTML file with a form to test the POST request Monday, March 18, 13
  • 82. Getting The Data Use jQuery’s ajax calls from the client Monday, March 18, 13
  • 83. jQuery Functions $.get - sends a get request to the server. Takes a url, optional data, success handler and data type. $.post - sends a post request to the server. Takes a url, optional data, success handler and data type. Monday, March 18, 13
  • 84. get/post Examples $.get(‘test.php’); $.post(‘test.php’, { name : ‘john’, time: ‘2pm’ }); $.get(‘test.php’, function(data) { alert(data); }); Monday, March 18, 13
  • 85. $.ajax Gain full control over the request Can handle errors get/post are actually just shortcuts for this one Takes url and settings object Monday, March 18, 13
  • 86. $.ajax Settings error: error handler callback success: success handler callback context: the ‘this’ pointer of callbacks data: data object to send url: the url to use Full docs: http://api.jquery.com/jQuery.ajax/ Monday, March 18, 13
  • 87. Example: $.ajax $.ajax({    type: "POST",    url: "some.php",    data: "name=John&location=Boston",    success: function(msg){      alert( "Data Saved: " + msg );    }  }); Monday, March 18, 13
  • 88. Demo: “live” wall with ajax Monday, March 18, 13
  • 90. Ajax: Lab 1 Add client GUI to the lab on page 44 (math server) Allow sum/multiply and show the result Every second, check number of actions performed and update the display Monday, March 18, 13
  • 91. Ajax: Lab 2 Create a weather application Use Node.JS for server side. Use wunderground to get weather report based on lat/ long. URL: http://api.wunderground.com/api/API_KEY/geolookup/ q/37.776289,-122.395234.json App should show a picture of Sun or Rain based on current weather Monday, March 18, 13
  • 92. Express Middleware Pipeline How the middleware pipeline works for you Monday, March 18, 13
  • 93. Sample Pipeline 1 Request Favicon 2 Do you need a favicon ? 3 4 Yes - Here it is No - Next middleware Monday, March 18, 13
  • 94. Sample Pipeline 1 Request logger 2 Write down the request to log 3 Next middleware Monday, March 18, 13
  • 95. Sample Pipeline 1 Request Router 2 Is there a named route ? 3 4 Yes - Here it is No - Next middleware Monday, March 18, 13
  • 96. Sample Pipeline 1 Request Static 2 Is there a matched public file ? 3 4 Yes - Here it is No - Next middleware Monday, March 18, 13
  • 97. Sample Pipeline 1 Request Error 2 Bye Bye 3 Monday, March 18, 13
  • 98. Error Handling In Pipeline app.get('/user.json', function(req, res, next) {     var userid = req.param('id');     if ( userid == null ) {         return next('Invalid User');            }       res.send({ username: 'amy' }); }); Monday, March 18, 13
  • 99. Custom Express Middleware Let’s write a simple middleware for returning visitors If it’s the first visit, show a banner If it’s a later visit, show another banner Use jade for the template Monday, March 18, 13
  • 100. Lab Write a cross domain ajax middleware Add CORS to each response headers Bonus: Initialize with source domains Monday, March 18, 13
  • 101. Other Middlewares Authentication is performed by a middleware. Demo: https://github.com/visionmedia/express/tree/master/ examples/auth Static middleware will serve a static path bodyParser automatically turns request body to an object compress() automatically compresses responses Monday, March 18, 13
  • 103. Thank You Keynote and Extras: ynonperek.com Photos From: http://123rf.com http://www.flickr.com/photos/crazyeddie/ 1463295872/ Monday, March 18, 13