SlideShare ist ein Scribd-Unternehmen logo
1 von 135
Downloaden Sie, um offline zu lesen
Building Servers
  with Node.js
         Travis Swicegood

       #nodetalk
   Licensed under Creative Commons,
        Attribution, Share-Alike
Hi, I’m Travis
building servers with node.js   some rights reserved
#nodetalk
building servers with node.js   some rights reserved
What’s this
               talk about?
building servers with node.js   some rights reserved
What is
                 Node.js?
building servers with node.js   some rights reserved
Servers
building servers with node.js   some rights reserved
GTD
building servers with node.js         some rights reserved
Is it Right
           For Me?
building servers with node.js   some rights reserved
What is
                 Node.js?
building servers with node.js   some rights reserved
Evented I/O
                   Networking
                     Toolkit
building servers with node.js   some rights reserved
What’s “evented?”
building servers with node.js   some rights reserved
Some Code
building servers with node.js      some rights reserved
Standard Data Store
     var db = new Database({host: "localhost"});
     db.connect();
     var result = db.find({name: "a-post"});
     // do something with result




building servers with node.js                      some rights reserved
Evented Data Store
     var db = new Database({host: "localhost"});
     db.connect(function(conn) {
       conn.find({name: "a-post"}, function(result) {
         // do something with result
       });
     });




building servers with node.js                           some rights reserved
Event Loop
building servers with node.js       some rights reserved
An Analogy
building servers with node.js      some rights reserved
A rabbi, a priest,
  and a cowboy walk
      into a bar.
building servers with node.js   some rights reserved
Take 1
     Simple Bartender
building servers with node.js   some rights reserved
Rabbi
building servers with node.js           some rights reserved
Priest
building servers with node.js            some rights reserved
Cowboy…
building servers with node.js     some rights reserved
… he starts
                     to talk
building servers with node.js   some rights reserved
Bartender is
                 now blocked
building servers with node.js   some rights reserved
Take 2
  Evented Bartender
building servers with node.js   some rights reserved
Rabbi
building servers with node.js           some rights reserved
Priest
building servers with node.js            some rights reserved
Cowboy…
building servers with node.js     some rights reserved
… he starts
                     to talk
building servers with node.js   some rights reserved
Bartender starts
        filling orders
building servers with node.js   some rights reserved
Fixing Take 1
building servers with node.js   some rights reserved
Add more
                    bartenders
building servers with node.js   some rights reserved
Limit time
        with each client
building servers with node.js   some rights reserved
Respond to
                      Events
building servers with node.js   some rights reserved
Who uses this?
building servers with node.js   some rights reserved
Nginx
building servers with node.js           some rights reserved
Memcached
building servers with node.js   some rights reserved
Most NoSQL
building servers with node.js   some rights reserved
Servers
building servers with node.js   some rights reserved
Basic Socket Server
building servers with node.js   some rights reserved
Echo Server
     var net = require("net");
     net.createServer(function(socket) {
       socket.on("data", function(data) {
         socket.write("You said: " + data);
         socket.end();
       });
       socket.write("Please say something:n");
     }).listen(1234);
     console.log("Listening on 1234");




building servers with node.js                     some rights reserved
Echo Server
     var net = require("net");
     net.createServer(function(socket) {
       socket.on("data", function(data) {
         socket.write("You said: " + data);
         socket.end();
       });
       socket.write("Please say something:n");
     }).listen(1234);
     console.log("Listening on 1234");




building servers with node.js                     some rights reserved
Echo Server
     var net = require("net");
     net.createServer(function(socket) {
       socket.on("data", function(data) {
         socket.write("You said: " + data);
         socket.end();
       });
       socket.write("Please say something:n");
     }).listen(1234);
     console.log("Listening on 1234");




building servers with node.js                     some rights reserved
Echo Server
     var net = require("net");
     net.createServer(function(socket) {
       socket.on("data", function(data) {
         socket.write("You said: " + data);
         socket.end();
       });
       socket.write("Please say something:n");
     }).listen(1234);
     console.log("Listening on 1234");




building servers with node.js                     some rights reserved
Echo Server
     var net = require("net");
     net.createServer(function(socket) {
       socket.on("data", function(data) {
         socket.write("You said: " + data);
         socket.end();
       });
       socket.write("Please say something:n");
     }).listen(1234);
     console.log("Listening on 1234");




building servers with node.js                     some rights reserved
Echo Server
     var net = require("net");
     net.createServer(function(socket) {
       socket.on("data", function(data) {
         socket.write("You said: " + data);
         socket.end();
       });
       socket.write("Please say something:n");
     }).listen(1234);
     console.log("Listening on 1234");




building servers with node.js                     some rights reserved
Echo Server
     var net = require("net");
     net.createServer(function(socket) {
       socket.on("data", function(data) {
         socket.write("You said: " + data);
         socket.end();
       });
       socket.write("Please say something:n");
     }).listen(1234);
     console.log("Listening on 1234");




building servers with node.js                     some rights reserved
Storing State
building servers with node.js   some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Personalized Echo Server
     net.createServer(function(socket) {
       var name = false;
       socket.on("data", function(data) {
         if (!name) {
           name = data.toString('utf8').trim();
           socket.write("Thanks, " + name + "n");
           socket.write("Please say something:n");
         } else {
           socket.write(name + ", you said: " + data);
           socket.end();
         }
       });
       socket.write("Please tell me your name: ");
     }).listen(1234);



building servers with node.js                            some rights reserved
Web Servers
building servers with node.js   some rights reserved
Hello World
building servers with node.js       some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/html"});
       response.write("<h1>Hello, World!</h1>");
       response.end();
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/html"});
       response.write("<h1>Hello, World!</h1>");
       response.end();
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/html"});
       response.write("<h1>Hello, World!</h1>");
       response.end();
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/html"});
       response.write("<h1>Hello, World!</h1>");
       response.end();
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/html"});
       response.write("<h1>Hello, World!</h1>");
       response.end();
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/html"});
       response.write("<h1>Hello, World!</h1>");
       response.end();
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Something’s
                     Different
building servers with node.js   some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/html"});
       response.write("<h1>Hello, World!</h1>");
       response.end();
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/html"});
       response.write("<h1>Hello, World!</h1>");
       response.end();
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Any idea why?
building servers with node.js   some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       setTimeout(function() {
         response.writeHead(200, {"Content-Type": "text/html"});
         response.write("<h1>Hello, World!</h1>");
         response.end();
       }, 1000);
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Hello World
     var http = require("http");
     http.createServer(function(request, response) {
       db.find({"slug": "a-blog-post"}, function(post) {
         response.writeHead(200, {"Content-Type": "text/html"});
         response.write("<h1>" + post.title + "</h1>");
         response.write(post.body);
         response.end();
       });
     }).listen(4321);
     console.log("Now listening on port 4321");




building servers with node.js                               some rights reserved
Grokking
                    the Request
building servers with node.js   some rights reserved
Output the Request
building servers with node.js   some rights reserved
Output the Request
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/plain"});
       response.write(require("util").inspect(request));
       response.end();
     }).listen(4321);
     console.log("Listening on 4321");




building servers with node.js                               some rights reserved
Output the Request
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/plain"});
       response.write(require("util").inspect(request));
       response.end();
     }).listen(4321);
     console.log("Listening on 4321");




building servers with node.js                               some rights reserved
Output the Request
     $ curl -s http://localhost:4321/
     { socket:
        { bufferSize: 0,
          fd: 7,
          type: 'tcp4',
          allowHalfOpen: true,
          _readWatcher:
           { socket: [Circular],
             callback: [Function: onReadable] },
          readable: true,
          _writeQueue: [],
          _writeQueueEncoding: [],
          _writeQueueFD: [],
     … and so on, and so on …



building servers with node.js                      some rights reserved
Output the Request
     $ curl -s http://localhost:4321/
     … way down around line 148 …
       url: '/',
       method: 'GET',




building servers with node.js           some rights reserved
Output the Request
     $ curl -s http://localhost:4321/say?msg=Hello | grep "url:"
       url: '/say?msg=Hello',




building servers with node.js                               some rights reserved
Parsing the URL
building servers with node.js   some rights reserved
Parsing the URL
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/plain"});
       var parsedUrl = require("url").parse(request.url);
       response.write(require("util").inspect(parsedUrl));
       response.end();
     }).listen(4321);
     console.log("Listening on 4321");




building servers with node.js                               some rights reserved
Parsing the URL
     $ curl -s http://localhost:4321/say?msg=Hello
     { href: '/say?msg=Hello',
       search: '?msg=Hello',
       query: 'msg=Hello',
       pathname: '/say' }




building servers with node.js                        some rights reserved
Parsing the URL
     $ curl -s http://localhost:4321/say?msg=Hello
     { href: '/say?msg=Hello',
       search: '?msg=Hello',
       query: 'msg=Hello',
       pathname: '/say' }




building servers with node.js                        some rights reserved
Parsing the URL
     $ curl -s http://localhost:4321/say?msg=Hello
     { href: '/say?msg=Hello',
       search: '?msg=Hello',
       query: 'msg=Hello',
       pathname: '/say' }




building servers with node.js                        some rights reserved
Parsing the URL
     $ curl -s http://localhost:4321/say?msg=Hello
     { href: '/say?msg=Hello',
       search: '?msg=Hello',
       query: 'msg=Hello',
       pathname: '/say' }




building servers with node.js                        some rights reserved
Parsing the URL
     $ curl -s http://localhost:4321/say?msg=Hello
     { href: '/say?msg=Hello',
       search: '?msg=Hello',
       query: 'msg=Hello',
       pathname: '/say' }




building servers with node.js                        some rights reserved
Parsing the Query
building servers with node.js   some rights reserved
Parsing the Query
     $ curl -s http://localhost:4321/say?msg=Hello
     { href: '/say?msg=Hello',
       search: '?msg=Hello',
       query: 'msg=Hello',
       pathname: '/say' }




building servers with node.js                        some rights reserved
Parsing the Query
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/plain"});
       var parsedUrl = require("url").parse(request.url, true);
       response.write(require("util").inspect(parsedUrl));
       response.end();
     }).listen(4321);
     console.log("Listening on 4321");




building servers with node.js                               some rights reserved
Parsing the Query
     var http = require("http");
     http.createServer(function(request, response) {
       response.writeHead(200, {"Content-Type": "text/plain"});
       var parsedUrl = require("url").parse(request.url, true);
       response.write(require("util").inspect(parsedUrl));
       response.end();
     }).listen(4321);
     console.log("Listening on 4321");




building servers with node.js                               some rights reserved
Parsing the Query
     $ curl -s http://localhost:4321/say?msg=Hello
     { href: '/say?msg=Hello',
       search: '?msg=Hello',
       query: { msg: 'Hello' },
       pathname: '/say' }




building servers with node.js                        some rights reserved
Receiving Data
building servers with node.js   some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Receiving Data
     function(request, response) {
       var raw = "";
       request.on("data", function(chunk) {
         raw += chunk;
       });
       request.on("end", function() {
         var data = JSON.parse(raw),
             obj = {message: data.message.split("").reverse().join("")};
         response.writeHead(200, {"Content-Type": "application/json"});
         response.write(JSON.stringify(obj));
         response.end();
       });
     }




building servers with node.js                               some rights reserved
Something
                        is Wrong
building servers with node.js      some rights reserved
Can’t handle Errors
     $ node json-reverse.js
     Listening on 4321

     undefined:0
     ^
     SyntaxError: Unexpected end of input
         at Object.parse (native)
         at IncomingMessage.<anonymous> (/Book/code/servers/json-
     reverse.js:8:21)
         at IncomingMessage.emit (events.js:39:17)
         at HTTPParser.onMessageComplete (http.js:111:23)
         at Socket.ondata (http.js:945:22)
         at Socket._onReadable (net.js:654:27)
         at IOWatcher.onReadable [as callback] (net.js:156:10)



building servers with node.js                               some rights reserved
Fault-Tolerance
building servers with node.js   some rights reserved
Quick Refactor
     var handleResponse = function(response, code, message) {
        response.writeHead(code, {"Content-Type": "application/json"});
        response.write(message);
        response.end();
     };




building servers with node.js                                some rights reserved
Fault Tolerant Reverse
       request.on("end", function() {
         if (!raw) {
           handleResponse(response, 400, "Requires more data");
           return;
         }
         try {
           var data = JSON.parse(raw);
         } catch(e) {
           handleResponse(response, 400, "Invalid JSON");
           return;
         }
         if (!data.message) {
           handleResponse(response, 400, "Requires a message");
           return;
         }

         var obj = {message: data.message.split("").reverse().join("") };
         handleResponse(response, 200, JSON.stringify(obj))
       });




building servers with node.js                                               some rights reserved
Fault Tolerant Reverse
       request.on("end", function() {
         if (!raw) {
           handleResponse(response, 400, "Requires more data");
           return;
         }
         try {
           var data = JSON.parse(raw);
         } catch(e) {
           handleResponse(response, 400, "Invalid JSON");
           return;
         }
         if (!data.message) {
           handleResponse(response, 400, "Requires a message");




building servers with node.js                               some rights reserved
Fault Tolerant Reverse
       request.on("end", function() {
         if (!raw) {
           handleResponse(response, 400, "Requires more data");
           return;
         }
         try {
           var data = JSON.parse(raw);
         } catch(e) {
           handleResponse(response, 400, "Invalid JSON");
           return;
         }
         if (!data.message) {
           handleResponse(response, 400, "Requires a message");




building servers with node.js                               some rights reserved
Fault Tolerant Reverse
          // earlier code
          } catch(e) {
            handleResponse(response, 400, "Invalid JSON");
            return;
          }
          if (!data.message) {
            handleResponse(response, 400, "Requires a message");
            return;
          }

         var obj = {message: data.message.split("").reverse().join("") };
         handleResponse(response, 200, JSON.stringify(obj))
       });




building servers with node.js                                some rights reserved
Fault Tolerant Reverse
          // earlier code
          } catch(e) {
            handleResponse(response, 400, "Invalid JSON");
            return;
          }
          if (!data.message) {
            handleResponse(response, 400, "Requires a message");
            return;
          }

         var obj = {message: data.message.split("").reverse().join("") };
         handleResponse(response, 200, JSON.stringify(obj))
       });




building servers with node.js                                some rights reserved
GTD
building servers with node.js         some rights reserved
Libraries Help
building servers with node.js   some rights reserved
Express
                     visionmedia/express

building servers with node.js          some rights reserved
Hello World
     var app = express.createServer();

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

     app.listen(3000);




building servers with node.js            some rights reserved
Socket.IO
                         http://socket.io/

building servers with node.js                some rights reserved
Push from the Server
     var http = require('http'),  
         io = require('socket.io');

     var server = http.createServer(function(req, res){
      // your normal server code
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end('<h1>Hello world</h1>');
     });
     server.listen(80);
      
     // socket.io
     var socket = io.listen(server);
     socket.on('connection', function(client){
       // new client is here!
       client.on('message', function(){ … })
       client.on('disconnect', function(){ … })
     });




building servers with node.js                              some rights reserved
Socket.IO
     // socket.io
     var socket = io.listen(server);
     socket.on('connection', function(client){
       // new client is here!
       client.on('message', function(){ … })
       client.on('disconnect', function(){ … })
     });




building servers with node.js                     some rights reserved
Sending to Client
     // socket.io
     var socket = io.listen(server);
     socket.on('connection', function(client) {
       // send a message back to the client
       client.send({msg: "Thanks for connecting…"});
       // broadcast a message to everyone
       client.broadcast({msg: "Another one connected!"});
     });




building servers with node.js                               some rights reserved
CoffeeScript
                 jashkenas/coffee-script

building servers with node.js         some rights reserved
Remember this code?
       request.on("end", function() {
         if (!raw) {
           handleResponse(response, 400, "Requires more data");
           return;
         }
         try {
           var data = JSON.parse(raw);
         } catch(e) {
           handleResponse(response, 400, "Invalid JSON");
           return;
         }
         if (!data.message) {
           handleResponse(response, 400, "Requires a message");
           return;
         }

         var obj = {message: data.message.split("").reverse().join("") };
         handleResponse(response, 200, JSON.stringify(obj))
       });




building servers with node.js                                               some rights reserved
In CoffeeScript
       request.on "end", () ->
         return handleResponse response, 400, "Requires more data" unless raw

         try
           data = JSON.parse raw
         catch e
           return handleResponse response, 400, "Requires more data"

         return handleResponse response, 400, "Requires a message" unless data.message

         obj =
           message: data.message.split("").reverse().join("")
         handleResponse response, 200, JSON.stringify obj




building servers with node.js                                               some rights reserved
Vows
                         cloudhead/vows
                        http://vowjs.org/
building servers with node.js               some rights reserved
No Samples
building servers with node.js     some rights reserved
Is it Right
           For Me?
building servers with node.js   some rights reserved
It Depends
building servers with node.js       some rights reserved
The Checklist
building servers with node.js   some rights reserved
Control
                          the Stack
building servers with node.js         some rights reserved
Comfortable
                    with Change
building servers with node.js   some rights reserved
Full Control Over
              App Logic
building servers with node.js   some rights reserved
Lots of Small
                   Independent
                      Pieces
building servers with node.js   some rights reserved
Then Maybe
building servers with node.js   some rights reserved
Where to?
building servers with node.js     some rights reserved
nodejs.org
building servers with node.js     some rights reserved
#Node.js
                      (freenode)
building servers with node.js   some rights reserved
Travis Swicegood
                       travisswicegood.com
                           @tswicegood
                       travis@domain51.com
                       http://joind.in/2810
building servers with node.js                 some rights reserved

Weitere ähnliche Inhalte

Was ist angesagt?

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 Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
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
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialTom Croucher
 
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
 
Communication in Node.js
Communication in Node.jsCommunication in Node.js
Communication in Node.jsEdureka!
 
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
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
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
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & ExpressChristian Joudrey
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 
Getting started with developing Nodejs
Getting started with developing NodejsGetting started with developing Nodejs
Getting started with developing NodejsPhil Hawksworth
 

Was ist angesagt? (20)

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 Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
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
 
NodeJS
NodeJSNodeJS
NodeJS
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
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
 
Communication in Node.js
Communication in Node.jsCommunication in Node.js
Communication in Node.js
 
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
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
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
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Nodejs in Production
Nodejs in ProductionNodejs in Production
Nodejs in Production
 
Getting started with developing Nodejs
Getting started with developing NodejsGetting started with developing Nodejs
Getting started with developing Nodejs
 

Andere mochten auch

Node js: che cos'è e a che cosa serve?
Node js: che cos'è e a che cosa serve?Node js: che cos'è e a che cosa serve?
Node js: che cos'è e a che cosa serve?Flavius-Florin Harabor
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.jsRyan Anklam
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
Angular 2.0: Getting ready
Angular 2.0: Getting readyAngular 2.0: Getting ready
Angular 2.0: Getting readyAxilis
 
Grunt JS - Getting Started With Grunt
Grunt JS - Getting Started With GruntGrunt JS - Getting Started With Grunt
Grunt JS - Getting Started With GruntDouglas Reynolds
 
Introduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal devIntroduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal devmcantelon
 
Grunt - The JavaScript Task Runner
Grunt - The JavaScript Task RunnerGrunt - The JavaScript Task Runner
Grunt - The JavaScript Task RunnerMohammed Arif
 
Planning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js ApplicationsPlanning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js ApplicationsModulus
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。Tatsuya Tobioka
 
Horizontally Scaling Node.js and WebSockets
Horizontally Scaling Node.js and WebSocketsHorizontally Scaling Node.js and WebSockets
Horizontally Scaling Node.js and WebSocketsJames Simpson
 
Scaling and securing node.js apps
Scaling and securing node.js appsScaling and securing node.js apps
Scaling and securing node.js appsMaciej Lasyk
 
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...Ivan Loire
 
Scalability using Node.js
Scalability using Node.jsScalability using Node.js
Scalability using Node.jsratankadam
 
Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)PCampRussia
 
Fullstack End-to-end test automation with Node.js, one year later
Fullstack End-to-end test automation with Node.js, one year laterFullstack End-to-end test automation with Node.js, one year later
Fullstack End-to-end test automation with Node.js, one year laterMek Srunyu Stittri
 
Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideMek Srunyu Stittri
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applicationsSergi Mansilla
 

Andere mochten auch (20)

Node js: che cos'è e a che cosa serve?
Node js: che cos'è e a che cosa serve?Node js: che cos'è e a che cosa serve?
Node js: che cos'è e a che cosa serve?
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.js
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Angular 2.0: Getting ready
Angular 2.0: Getting readyAngular 2.0: Getting ready
Angular 2.0: Getting ready
 
Grunt JS - Getting Started With Grunt
Grunt JS - Getting Started With GruntGrunt JS - Getting Started With Grunt
Grunt JS - Getting Started With Grunt
 
Introduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal devIntroduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal dev
 
Grunt - The JavaScript Task Runner
Grunt - The JavaScript Task RunnerGrunt - The JavaScript Task Runner
Grunt - The JavaScript Task Runner
 
Planning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js ApplicationsPlanning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js Applications
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。
 
Horizontally Scaling Node.js and WebSockets
Horizontally Scaling Node.js and WebSocketsHorizontally Scaling Node.js and WebSockets
Horizontally Scaling Node.js and WebSockets
 
Scaling and securing node.js apps
Scaling and securing node.js appsScaling and securing node.js apps
Scaling and securing node.js apps
 
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
 
Scalability using Node.js
Scalability using Node.jsScalability using Node.js
Scalability using Node.js
 
Node.js security
Node.js securityNode.js security
Node.js security
 
Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)
 
Fullstack End-to-end test automation with Node.js, one year later
Fullstack End-to-end test automation with Node.js, one year laterFullstack End-to-end test automation with Node.js, one year later
Fullstack End-to-end test automation with Node.js, one year later
 
Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java side
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
 

Ähnlich wie Building servers with Node.js

A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Ayes Chinmay
 
Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiJackson Tian
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.jsguileen
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionParth Joshi
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...Tom Croucher
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"EPAM Systems
 

Ähnlich wie Building servers with Node.js (20)

Node.js - As a networking tool
Node.js - As a networking toolNode.js - As a networking tool
Node.js - As a networking tool
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Node azure
Node azureNode azure
Node azure
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
 
Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)
 
Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin Shanghai
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.js
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Node.js Introduction
Node.js IntroductionNode.js Introduction
Node.js Introduction
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011Ferrara Linux Day 2011
Ferrara Linux Day 2011
 
Node.js
Node.jsNode.js
Node.js
 
node.js dao
node.js daonode.js dao
node.js dao
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"
 

Mehr von ConFoo

Debugging applications with network security tools
Debugging applications with network security toolsDebugging applications with network security tools
Debugging applications with network security toolsConFoo
 
The business behind open source
The business behind open sourceThe business behind open source
The business behind open sourceConFoo
 
Security 202 - Are you sure your site is secure?
Security 202 - Are you sure your site is secure?Security 202 - Are you sure your site is secure?
Security 202 - Are you sure your site is secure?ConFoo
 
OWASP Enterprise Security API
OWASP Enterprise Security APIOWASP Enterprise Security API
OWASP Enterprise Security APIConFoo
 
Opensource Authentication and Authorization
Opensource Authentication and AuthorizationOpensource Authentication and Authorization
Opensource Authentication and AuthorizationConFoo
 
Introduction à la sécurité des WebServices
Introduction à la sécurité des WebServicesIntroduction à la sécurité des WebServices
Introduction à la sécurité des WebServicesConFoo
 
Le bon, la brute et le truand dans les nuages
Le bon, la brute et le truand dans les nuagesLe bon, la brute et le truand dans les nuages
Le bon, la brute et le truand dans les nuagesConFoo
 
The Solar Framework for PHP
The Solar Framework for PHPThe Solar Framework for PHP
The Solar Framework for PHPConFoo
 
Décrire un projet PHP dans des rapports
Décrire un projet PHP dans des rapportsDécrire un projet PHP dans des rapports
Décrire un projet PHP dans des rapportsConFoo
 
Server Administration in Python with Fabric, Cuisine and Watchdog
Server Administration in Python with Fabric, Cuisine and WatchdogServer Administration in Python with Fabric, Cuisine and Watchdog
Server Administration in Python with Fabric, Cuisine and WatchdogConFoo
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+ConFoo
 
Think Mobile First, Then Enhance
Think Mobile First, Then EnhanceThink Mobile First, Then Enhance
Think Mobile First, Then EnhanceConFoo
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in RubyConFoo
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101ConFoo
 
As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?ConFoo
 
Pragmatic Guide to Git
Pragmatic Guide to GitPragmatic Guide to Git
Pragmatic Guide to GitConFoo
 
An Overview of Flash Storage for Databases
An Overview of Flash Storage for DatabasesAn Overview of Flash Storage for Databases
An Overview of Flash Storage for DatabasesConFoo
 
Android Jump Start
Android Jump StartAndroid Jump Start
Android Jump StartConFoo
 
Develop mobile applications with Flex
Develop mobile applications with FlexDevelop mobile applications with Flex
Develop mobile applications with FlexConFoo
 
WordPress pour le développement d'aplications web
WordPress pour le développement d'aplications webWordPress pour le développement d'aplications web
WordPress pour le développement d'aplications webConFoo
 

Mehr von ConFoo (20)

Debugging applications with network security tools
Debugging applications with network security toolsDebugging applications with network security tools
Debugging applications with network security tools
 
The business behind open source
The business behind open sourceThe business behind open source
The business behind open source
 
Security 202 - Are you sure your site is secure?
Security 202 - Are you sure your site is secure?Security 202 - Are you sure your site is secure?
Security 202 - Are you sure your site is secure?
 
OWASP Enterprise Security API
OWASP Enterprise Security APIOWASP Enterprise Security API
OWASP Enterprise Security API
 
Opensource Authentication and Authorization
Opensource Authentication and AuthorizationOpensource Authentication and Authorization
Opensource Authentication and Authorization
 
Introduction à la sécurité des WebServices
Introduction à la sécurité des WebServicesIntroduction à la sécurité des WebServices
Introduction à la sécurité des WebServices
 
Le bon, la brute et le truand dans les nuages
Le bon, la brute et le truand dans les nuagesLe bon, la brute et le truand dans les nuages
Le bon, la brute et le truand dans les nuages
 
The Solar Framework for PHP
The Solar Framework for PHPThe Solar Framework for PHP
The Solar Framework for PHP
 
Décrire un projet PHP dans des rapports
Décrire un projet PHP dans des rapportsDécrire un projet PHP dans des rapports
Décrire un projet PHP dans des rapports
 
Server Administration in Python with Fabric, Cuisine and Watchdog
Server Administration in Python with Fabric, Cuisine and WatchdogServer Administration in Python with Fabric, Cuisine and Watchdog
Server Administration in Python with Fabric, Cuisine and Watchdog
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
Think Mobile First, Then Enhance
Think Mobile First, Then EnhanceThink Mobile First, Then Enhance
Think Mobile First, Then Enhance
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101
 
As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?As-t-on encore besoin d'un framework web ?
As-t-on encore besoin d'un framework web ?
 
Pragmatic Guide to Git
Pragmatic Guide to GitPragmatic Guide to Git
Pragmatic Guide to Git
 
An Overview of Flash Storage for Databases
An Overview of Flash Storage for DatabasesAn Overview of Flash Storage for Databases
An Overview of Flash Storage for Databases
 
Android Jump Start
Android Jump StartAndroid Jump Start
Android Jump Start
 
Develop mobile applications with Flex
Develop mobile applications with FlexDevelop mobile applications with Flex
Develop mobile applications with Flex
 
WordPress pour le développement d'aplications web
WordPress pour le développement d'aplications webWordPress pour le développement d'aplications web
WordPress pour le développement d'aplications web
 

Kürzlich hochgeladen

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

Kürzlich hochgeladen (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 

Building servers with Node.js

  • 1. Building Servers with Node.js Travis Swicegood #nodetalk Licensed under Creative Commons, Attribution, Share-Alike
  • 2. Hi, I’m Travis building servers with node.js some rights reserved
  • 3. #nodetalk building servers with node.js some rights reserved
  • 4. What’s this talk about? building servers with node.js some rights reserved
  • 5. What is Node.js? building servers with node.js some rights reserved
  • 6. Servers building servers with node.js some rights reserved
  • 7. GTD building servers with node.js some rights reserved
  • 8. Is it Right For Me? building servers with node.js some rights reserved
  • 9. What is Node.js? building servers with node.js some rights reserved
  • 10. Evented I/O Networking Toolkit building servers with node.js some rights reserved
  • 11. What’s “evented?” building servers with node.js some rights reserved
  • 12. Some Code building servers with node.js some rights reserved
  • 13. Standard Data Store var db = new Database({host: "localhost"}); db.connect(); var result = db.find({name: "a-post"}); // do something with result building servers with node.js some rights reserved
  • 14. Evented Data Store var db = new Database({host: "localhost"}); db.connect(function(conn) { conn.find({name: "a-post"}, function(result) { // do something with result }); }); building servers with node.js some rights reserved
  • 15. Event Loop building servers with node.js some rights reserved
  • 16. An Analogy building servers with node.js some rights reserved
  • 17. A rabbi, a priest, and a cowboy walk into a bar. building servers with node.js some rights reserved
  • 18. Take 1 Simple Bartender building servers with node.js some rights reserved
  • 19. Rabbi building servers with node.js some rights reserved
  • 20. Priest building servers with node.js some rights reserved
  • 21. Cowboy… building servers with node.js some rights reserved
  • 22. … he starts to talk building servers with node.js some rights reserved
  • 23. Bartender is now blocked building servers with node.js some rights reserved
  • 24. Take 2 Evented Bartender building servers with node.js some rights reserved
  • 25. Rabbi building servers with node.js some rights reserved
  • 26. Priest building servers with node.js some rights reserved
  • 27. Cowboy… building servers with node.js some rights reserved
  • 28. … he starts to talk building servers with node.js some rights reserved
  • 29. Bartender starts filling orders building servers with node.js some rights reserved
  • 30. Fixing Take 1 building servers with node.js some rights reserved
  • 31. Add more bartenders building servers with node.js some rights reserved
  • 32. Limit time with each client building servers with node.js some rights reserved
  • 33. Respond to Events building servers with node.js some rights reserved
  • 34. Who uses this? building servers with node.js some rights reserved
  • 35. Nginx building servers with node.js some rights reserved
  • 36. Memcached building servers with node.js some rights reserved
  • 37. Most NoSQL building servers with node.js some rights reserved
  • 38. Servers building servers with node.js some rights reserved
  • 39. Basic Socket Server building servers with node.js some rights reserved
  • 40. Echo Server var net = require("net"); net.createServer(function(socket) { socket.on("data", function(data) { socket.write("You said: " + data); socket.end(); }); socket.write("Please say something:n"); }).listen(1234); console.log("Listening on 1234"); building servers with node.js some rights reserved
  • 41. Echo Server var net = require("net"); net.createServer(function(socket) { socket.on("data", function(data) { socket.write("You said: " + data); socket.end(); }); socket.write("Please say something:n"); }).listen(1234); console.log("Listening on 1234"); building servers with node.js some rights reserved
  • 42. Echo Server var net = require("net"); net.createServer(function(socket) { socket.on("data", function(data) { socket.write("You said: " + data); socket.end(); }); socket.write("Please say something:n"); }).listen(1234); console.log("Listening on 1234"); building servers with node.js some rights reserved
  • 43. Echo Server var net = require("net"); net.createServer(function(socket) { socket.on("data", function(data) { socket.write("You said: " + data); socket.end(); }); socket.write("Please say something:n"); }).listen(1234); console.log("Listening on 1234"); building servers with node.js some rights reserved
  • 44. Echo Server var net = require("net"); net.createServer(function(socket) { socket.on("data", function(data) { socket.write("You said: " + data); socket.end(); }); socket.write("Please say something:n"); }).listen(1234); console.log("Listening on 1234"); building servers with node.js some rights reserved
  • 45. Echo Server var net = require("net"); net.createServer(function(socket) { socket.on("data", function(data) { socket.write("You said: " + data); socket.end(); }); socket.write("Please say something:n"); }).listen(1234); console.log("Listening on 1234"); building servers with node.js some rights reserved
  • 46. Echo Server var net = require("net"); net.createServer(function(socket) { socket.on("data", function(data) { socket.write("You said: " + data); socket.end(); }); socket.write("Please say something:n"); }).listen(1234); console.log("Listening on 1234"); building servers with node.js some rights reserved
  • 47. Storing State building servers with node.js some rights reserved
  • 48. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 49. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 50. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 51. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 52. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 53. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 54. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 55. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 56. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 57. Personalized Echo Server net.createServer(function(socket) { var name = false; socket.on("data", function(data) { if (!name) { name = data.toString('utf8').trim(); socket.write("Thanks, " + name + "n"); socket.write("Please say something:n"); } else { socket.write(name + ", you said: " + data); socket.end(); } }); socket.write("Please tell me your name: "); }).listen(1234); building servers with node.js some rights reserved
  • 58. Web Servers building servers with node.js some rights reserved
  • 59. Hello World building servers with node.js some rights reserved
  • 60. Hello World var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello, World!</h1>"); response.end(); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 61. Hello World var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello, World!</h1>"); response.end(); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 62. Hello World var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello, World!</h1>"); response.end(); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 63. Hello World var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello, World!</h1>"); response.end(); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 64. Hello World var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello, World!</h1>"); response.end(); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 65. Hello World var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello, World!</h1>"); response.end(); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 66. Something’s Different building servers with node.js some rights reserved
  • 67. Hello World var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello, World!</h1>"); response.end(); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 68. Hello World var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello, World!</h1>"); response.end(); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 69. Any idea why? building servers with node.js some rights reserved
  • 70. Hello World var http = require("http"); http.createServer(function(request, response) { setTimeout(function() { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello, World!</h1>"); response.end(); }, 1000); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 71. Hello World var http = require("http"); http.createServer(function(request, response) { db.find({"slug": "a-blog-post"}, function(post) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>" + post.title + "</h1>"); response.write(post.body); response.end(); }); }).listen(4321); console.log("Now listening on port 4321"); building servers with node.js some rights reserved
  • 72. Grokking the Request building servers with node.js some rights reserved
  • 73. Output the Request building servers with node.js some rights reserved
  • 74. Output the Request var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write(require("util").inspect(request)); response.end(); }).listen(4321); console.log("Listening on 4321"); building servers with node.js some rights reserved
  • 75. Output the Request var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write(require("util").inspect(request)); response.end(); }).listen(4321); console.log("Listening on 4321"); building servers with node.js some rights reserved
  • 76. Output the Request $ curl -s http://localhost:4321/ { socket: { bufferSize: 0, fd: 7, type: 'tcp4', allowHalfOpen: true, _readWatcher: { socket: [Circular], callback: [Function: onReadable] }, readable: true, _writeQueue: [], _writeQueueEncoding: [], _writeQueueFD: [], … and so on, and so on … building servers with node.js some rights reserved
  • 77. Output the Request $ curl -s http://localhost:4321/ … way down around line 148 … url: '/', method: 'GET', building servers with node.js some rights reserved
  • 78. Output the Request $ curl -s http://localhost:4321/say?msg=Hello | grep "url:" url: '/say?msg=Hello', building servers with node.js some rights reserved
  • 79. Parsing the URL building servers with node.js some rights reserved
  • 80. Parsing the URL var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); var parsedUrl = require("url").parse(request.url); response.write(require("util").inspect(parsedUrl)); response.end(); }).listen(4321); console.log("Listening on 4321"); building servers with node.js some rights reserved
  • 81. Parsing the URL $ curl -s http://localhost:4321/say?msg=Hello { href: '/say?msg=Hello', search: '?msg=Hello', query: 'msg=Hello', pathname: '/say' } building servers with node.js some rights reserved
  • 82. Parsing the URL $ curl -s http://localhost:4321/say?msg=Hello { href: '/say?msg=Hello', search: '?msg=Hello', query: 'msg=Hello', pathname: '/say' } building servers with node.js some rights reserved
  • 83. Parsing the URL $ curl -s http://localhost:4321/say?msg=Hello { href: '/say?msg=Hello', search: '?msg=Hello', query: 'msg=Hello', pathname: '/say' } building servers with node.js some rights reserved
  • 84. Parsing the URL $ curl -s http://localhost:4321/say?msg=Hello { href: '/say?msg=Hello', search: '?msg=Hello', query: 'msg=Hello', pathname: '/say' } building servers with node.js some rights reserved
  • 85. Parsing the URL $ curl -s http://localhost:4321/say?msg=Hello { href: '/say?msg=Hello', search: '?msg=Hello', query: 'msg=Hello', pathname: '/say' } building servers with node.js some rights reserved
  • 86. Parsing the Query building servers with node.js some rights reserved
  • 87. Parsing the Query $ curl -s http://localhost:4321/say?msg=Hello { href: '/say?msg=Hello', search: '?msg=Hello', query: 'msg=Hello', pathname: '/say' } building servers with node.js some rights reserved
  • 88. Parsing the Query var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); var parsedUrl = require("url").parse(request.url, true); response.write(require("util").inspect(parsedUrl)); response.end(); }).listen(4321); console.log("Listening on 4321"); building servers with node.js some rights reserved
  • 89. Parsing the Query var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); var parsedUrl = require("url").parse(request.url, true); response.write(require("util").inspect(parsedUrl)); response.end(); }).listen(4321); console.log("Listening on 4321"); building servers with node.js some rights reserved
  • 90. Parsing the Query $ curl -s http://localhost:4321/say?msg=Hello { href: '/say?msg=Hello', search: '?msg=Hello', query: { msg: 'Hello' }, pathname: '/say' } building servers with node.js some rights reserved
  • 91. Receiving Data building servers with node.js some rights reserved
  • 92. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 93. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 94. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 95. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 96. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 97. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 98. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 99. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 100. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 101. Receiving Data function(request, response) { var raw = ""; request.on("data", function(chunk) { raw += chunk; }); request.on("end", function() { var data = JSON.parse(raw), obj = {message: data.message.split("").reverse().join("")}; response.writeHead(200, {"Content-Type": "application/json"}); response.write(JSON.stringify(obj)); response.end(); }); } building servers with node.js some rights reserved
  • 102. Something is Wrong building servers with node.js some rights reserved
  • 103. Can’t handle Errors $ node json-reverse.js Listening on 4321 undefined:0 ^ SyntaxError: Unexpected end of input at Object.parse (native) at IncomingMessage.<anonymous> (/Book/code/servers/json- reverse.js:8:21) at IncomingMessage.emit (events.js:39:17) at HTTPParser.onMessageComplete (http.js:111:23) at Socket.ondata (http.js:945:22) at Socket._onReadable (net.js:654:27) at IOWatcher.onReadable [as callback] (net.js:156:10) building servers with node.js some rights reserved
  • 104. Fault-Tolerance building servers with node.js some rights reserved
  • 105. Quick Refactor var handleResponse = function(response, code, message) { response.writeHead(code, {"Content-Type": "application/json"}); response.write(message); response.end(); }; building servers with node.js some rights reserved
  • 106. Fault Tolerant Reverse request.on("end", function() { if (!raw) { handleResponse(response, 400, "Requires more data"); return; } try { var data = JSON.parse(raw); } catch(e) { handleResponse(response, 400, "Invalid JSON"); return; } if (!data.message) { handleResponse(response, 400, "Requires a message"); return; } var obj = {message: data.message.split("").reverse().join("") }; handleResponse(response, 200, JSON.stringify(obj)) }); building servers with node.js some rights reserved
  • 107. Fault Tolerant Reverse request.on("end", function() { if (!raw) { handleResponse(response, 400, "Requires more data"); return; } try { var data = JSON.parse(raw); } catch(e) { handleResponse(response, 400, "Invalid JSON"); return; } if (!data.message) { handleResponse(response, 400, "Requires a message"); building servers with node.js some rights reserved
  • 108. Fault Tolerant Reverse request.on("end", function() { if (!raw) { handleResponse(response, 400, "Requires more data"); return; } try { var data = JSON.parse(raw); } catch(e) { handleResponse(response, 400, "Invalid JSON"); return; } if (!data.message) { handleResponse(response, 400, "Requires a message"); building servers with node.js some rights reserved
  • 109. Fault Tolerant Reverse // earlier code } catch(e) { handleResponse(response, 400, "Invalid JSON"); return; } if (!data.message) { handleResponse(response, 400, "Requires a message"); return; } var obj = {message: data.message.split("").reverse().join("") }; handleResponse(response, 200, JSON.stringify(obj)) }); building servers with node.js some rights reserved
  • 110. Fault Tolerant Reverse // earlier code } catch(e) { handleResponse(response, 400, "Invalid JSON"); return; } if (!data.message) { handleResponse(response, 400, "Requires a message"); return; } var obj = {message: data.message.split("").reverse().join("") }; handleResponse(response, 200, JSON.stringify(obj)) }); building servers with node.js some rights reserved
  • 111. GTD building servers with node.js some rights reserved
  • 112. Libraries Help building servers with node.js some rights reserved
  • 113. Express visionmedia/express building servers with node.js some rights reserved
  • 114. Hello World var app = express.createServer(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000); building servers with node.js some rights reserved
  • 115. Socket.IO http://socket.io/ building servers with node.js some rights reserved
  • 116. Push from the Server var http = require('http'),       io = require('socket.io'); var server = http.createServer(function(req, res){  // your normal server code  res.writeHead(200, {'Content-Type': 'text/html'});  res.end('<h1>Hello world</h1>'); }); server.listen(80);   // socket.io var socket = io.listen(server); socket.on('connection', function(client){   // new client is here!   client.on('message', function(){ … })   client.on('disconnect', function(){ … }) }); building servers with node.js some rights reserved
  • 117. Socket.IO // socket.io var socket = io.listen(server); socket.on('connection', function(client){   // new client is here!   client.on('message', function(){ … })   client.on('disconnect', function(){ … }) }); building servers with node.js some rights reserved
  • 118. Sending to Client // socket.io var socket = io.listen(server); socket.on('connection', function(client) { // send a message back to the client client.send({msg: "Thanks for connecting…"}); // broadcast a message to everyone client.broadcast({msg: "Another one connected!"}); }); building servers with node.js some rights reserved
  • 119. CoffeeScript jashkenas/coffee-script building servers with node.js some rights reserved
  • 120. Remember this code? request.on("end", function() { if (!raw) { handleResponse(response, 400, "Requires more data"); return; } try { var data = JSON.parse(raw); } catch(e) { handleResponse(response, 400, "Invalid JSON"); return; } if (!data.message) { handleResponse(response, 400, "Requires a message"); return; } var obj = {message: data.message.split("").reverse().join("") }; handleResponse(response, 200, JSON.stringify(obj)) }); building servers with node.js some rights reserved
  • 121. In CoffeeScript request.on "end", () -> return handleResponse response, 400, "Requires more data" unless raw try data = JSON.parse raw catch e return handleResponse response, 400, "Requires more data" return handleResponse response, 400, "Requires a message" unless data.message obj = message: data.message.split("").reverse().join("") handleResponse response, 200, JSON.stringify obj building servers with node.js some rights reserved
  • 122. Vows cloudhead/vows http://vowjs.org/ building servers with node.js some rights reserved
  • 123. No Samples building servers with node.js some rights reserved
  • 124. Is it Right For Me? building servers with node.js some rights reserved
  • 125. It Depends building servers with node.js some rights reserved
  • 126. The Checklist building servers with node.js some rights reserved
  • 127. Control the Stack building servers with node.js some rights reserved
  • 128. Comfortable with Change building servers with node.js some rights reserved
  • 129. Full Control Over App Logic building servers with node.js some rights reserved
  • 130. Lots of Small Independent Pieces building servers with node.js some rights reserved
  • 131. Then Maybe building servers with node.js some rights reserved
  • 132. Where to? building servers with node.js some rights reserved
  • 133. nodejs.org building servers with node.js some rights reserved
  • 134. #Node.js (freenode) building servers with node.js some rights reserved
  • 135. Travis Swicegood travisswicegood.com @tswicegood travis@domain51.com http://joind.in/2810 building servers with node.js some rights reserved