SlideShare uma empresa Scribd logo
1 de 135
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
Tom Croucher
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 

Mais procurados (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
 

Destaque

Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)
PCampRussia
 

Destaque (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
 

Semelhante a Building servers with Node.js

Why Node.js
Why Node.jsWhy Node.js
Why Node.js
guileen
 
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
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"
EPAM Systems
 

Semelhante a 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"
 

Mais de ConFoo

Debugging applications with network security tools
Debugging applications with network security toolsDebugging applications with network security tools
Debugging applications with network security tools
ConFoo
 
The business behind open source
The business behind open sourceThe business behind open source
The business behind open source
ConFoo
 
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 API
ConFoo
 
Opensource Authentication and Authorization
Opensource Authentication and AuthorizationOpensource Authentication and Authorization
Opensource Authentication and Authorization
ConFoo
 
Introduction à la sécurité des WebServices
Introduction à la sécurité des WebServicesIntroduction à la sécurité des WebServices
Introduction à la sécurité des WebServices
ConFoo
 
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
ConFoo
 
The Solar Framework for PHP
The Solar Framework for PHPThe Solar Framework for PHP
The Solar Framework for PHP
ConFoo
 
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
ConFoo
 
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
ConFoo
 
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 Enhance
ConFoo
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
ConFoo
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101
ConFoo
 
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 Git
ConFoo
 
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
ConFoo
 
Android Jump Start
Android Jump StartAndroid Jump Start
Android Jump Start
ConFoo
 
Develop mobile applications with Flex
Develop mobile applications with FlexDevelop mobile applications with Flex
Develop mobile applications with Flex
ConFoo
 
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
ConFoo
 

Mais de 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
 

Último

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

Último (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 

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