SlideShare ist ein Scribd-Unternehmen logo
1 von 69
Downloaden Sie, um offline zu lesen
verona
21/05/2011
gabriele lana
gabriele.lana@cleancode.it
  twitter: @gabrielelana
why
         node.js?

“Node's goal is to
  provide an easy
   way to build
scalable network
    programs”

              http://nodejs.org/#about
what is
                  node.js?
•   asynchronous i/o framework
•   core in c++ on top of v8
•   rest of it in javascript
•   swiss army knife for network
    related stuffs
•   can handle thousands of
    concurrent connections with
    minimal overhead (cpu/memory)
    on a single process
Single thread
synchronous I/0
Single thread
synchronous I/0
multiple thread
synchronous I/0
multiple thread
synchronous I/0
you can
  “always”
 scale with
  multiple
machines but
  it costs
  you $$$
Introduction to Nodejs
but...
what is HE
 doing?
CPU BOUND
          TASKS?


  but...
what is HE
 doing?
CPU BOUND
          TASKS?

             ...OR I/o
  but...       BOUND
what is HE    TASKS?
 doing?
synchronous I/0

function productsInCart(request, response) {
    var db = new Db()
    var user = new User(request)
    if (user.isAuthorized("cart/products")) {
        response.write(
             JSON.stringify(
                 db.productsInCart(user.cartId())
             )
        )
    } else {
        response.unauthorized()
    }
}
synchronous I/0

function productsInCart(request, response) {
    var db = new Db()
    var user = new User(request)
    if (user.isAuthorized("cart/products")) {
        response.write(
             JSON.stringify(
                 db.productsInCart(user.cartId())
             )
        )
    } else {
        response.unauthorized()
    }
}
synchronous I/0

function productsInCart(request, response) {
    var db = new Db()
    var user = new User(request)
    if (user.isAuthorized("cart/products")) {
        response.write(
             JSON.stringify(
                 db.productsInCart(user.cartId())
             )
        )
    } else {
        response.unauthorized()
    }
}
synchronous I/0

function productsInCart(request, response) {
    var db = new Db()
    var user = new User(request)
    if (user.isAuthorized("cart/products")) {
        response.write(
             JSON.stringify(
                 db.productsInCart(user.cartId())
             )
        )
    } else {
        response.unauthorized()
    }
}
single thread
asynchronous I/0
single thread
asynchronous I/0


           I am
       “callback”
         call me
         if you
        need me...
hello_world_server.js
                                          Event Emitter

                        var http = require("http")

                        var server = http.createServer(function(request, response) {
                           response.writeHead(200, {
                              "Content-Type": "plain/text"
                           })
                           response.write("Hello Worldn")
                           response.end()
                        })

                        server.listen(8080)

                        console.log("> SERVER STARTED")
hello_world_server.js
                                          Event Emitter

                        var http = require("http")

                        var server = http.createServer(function(request, response) {
                           response.writeHead(200, {
                              "Content-Type": "plain/text"
                           })
                           response.write("Hello Worldn")
                           response.end()
                        })

                        server.listen(8080)

                        console.log("> SERVER STARTED")
hello_world_server.js
                                          Event Emitter

                        var http = require("http")

                        var server = http.createServer(function(request, response) {
                           response.writeHead(200, {
                              "Content-Type": "plain/text"
                           })
                           response.write("Hello Worldn")
                           response.end()
                        })

                        server.listen(8080)

                        console.log("> SERVER STARTED")
hello_world_server.js
                                          Event Emitter

                        var http = require("http")

                        var server = http.createServer(function(request, response) {
                           response.writeHead(200, {
                              "Content-Type": "plain/text"
                           })
                           response.write("Hello Worldn")
                           response.end()
                        })

                        server.listen(8080)

                        console.log("> SERVER STARTED")
Event Emitter

coder@apollo:~/Work/src/node/examples$ node hello_world_server.js
> SERVER STARTED
                                                                    #1
coder@apollo:~$ curl "http://localhost:8080/"
Hello World
                                                                    #2
Event Emitter

                        var server = require("http").createServer()
hello_world_server.js



                        server.on("request", function(request, response) {
                           console.log("> REQUEST STARTED")
                           request.on("end", function() {
                              console.log("> REQUEST CLOSED")
                              response.writeHead(200, {
                                 "Content-Type": "plain/text"
                              })
                              response.end("Hello Worldn")
                              server.close()
                           })
                           response.on("close", function() {
                              console.log("> RESPONSE CLOSED")
                           })
                        })
hello_world_server.js
                                          Event Emitter


                        ...

                        server.on("close", function() {
                           console.log("> SERVER CLOSED")
                        })

                        server.on("listening", function() {
                           console.log("> SERVER STARTED")
                        })

                        server.listen(8080)
Event Emitter

coder@apollo:~/Work/src/node/examples$ node hello_world_server.js
> SERVER STARTED                                                    #1
coder@apollo:~$ curl "http://localhost:8080/"
Hello World                                                         #2
                                                                    #1
> REQUEST STARTED
> REQUEST CLOSED
> SERVER CLOSED
why so
complicated?
data streamS
                  server.on("request", function(request, response) {
                    var chunks = [],
                        output = fs.createWriteStream("./output")
proxy_stream.js




                       request.on("data", function(chunk) {
                          chunks = forEachLine(chunks.concat(chunk), function(line) {
                             output.write(parseInt(line, 10) * 2)
                             output.write("n")
                          })
                       })

                       request.on("end", function() {
                          response.writeHead(200, { "Content-Type": "plain/text" })
                          response.end("OKn")
                          output.end()
                          server.close()
                       })
                  })
data streamS

coder@apollo:~/Work/src/node/examples$ node stream_doubler.js
                                                                    #1
coder@apollo:~$ curl "http://localhost:8080/" --data $'1n2n3n'
OK                                                                  #2
coder@apollo:~/Work/src/node/examples$ cat output
2
4
6                                                                   #1
why
                 javascript?


•   Friendly callbacks
•   ubiquitous (well known)
•   no I/o primitives
•   one language to rule them all
web applications
                             before: a web
mind shift #1               server with some
                            application logic


                        application
           Web server

                        application


                        application


                        application
web applications
                        after: an application
mind shift #1             accessible over
                                http
        web server




                     application
web applications
                        after: an application
mind shift #1                 that can
                          communicate and
                         collaborate with
                             the world
        web server




                     application
web applications
                    before: stateful
mind shift #2   • no easy to scale
                • no easy to reuse

                v
                     M
                c
web applications
                    before: stateful
mind shift #2   • no easy to scale
                • no easy to reuse

                v
                     M
                c


  conversation       application
     state             state
web applications
                    before: stateful
mind shift #2   • no easy to scale
                • no easy to reuse

                v
                     M
                c



   tightly coupled
web applications
                    after: stateless
mind shift #2      • easy to scale
                   • easy to reuse


       v
            http
                       M
       c
web applications
                    after: stateless
mind shift #2      • easy to scale
                   • easy to reuse


       v
            http
                       M
       c


conversation       application
   state             state
web applications
                       after: stateless
mind shift #2
                http




                       web server
                                        M
                http

                                     statefull
                                    connection



• easy to scale                                  M
• easy to reuse
no fluff
just stuff
What about
cpu bound
  tasks?
the fork
long_running_job.sh                          be with you



                      #!/bin/bash

                      for count in `seq 1 100`; do
                           echo $count
                           sleep 0.1
                      done
the fork
long_running_server.js                              be with you
                         var spawn = require("child_process").spawn,
                             server = require("http").createServer()

                         server.on("request", function(request, response) {
                           var job = spawn("./long_running_job.sh")

                              job.stdout.on("data", function(tick) {
                                 response.write(tick)
                              })

                              job.on("exit", function() {
                                 response.end()
                              })
                         })
the fork
                                     be with you
coder@apollo:~$ ab -c 1 -n 1 "http://localhost:8080/"
...
Concurrency Level:      1
Time taken for tests:   10.531 seconds
...


coder@apollo:~$ ab -c 1 -n 2 "http://localhost:8080/"
...
Concurrency Level:      1
Time taken for tests:   20.108 seconds
...
the fork
                                     be with you
coder@apollo:~$ ab -c 2 -n 1 "http://localhost:8080/"
...
Concurrency Level:      2
Time taken for tests:   10.634 seconds
...

coder@apollo:~$ ab -c 100 -n 100 "http://localhost:8080/"
...
Concurrency Level:      100
Time taken for tests:   11.198 seconds
...

coder@apollo:~$ ab -c 500 -n 500 "http://localhost:8080/"
...
Concurrency Level:      500
Time taken for tests:   31.082 seconds
...
enter comet

w
 at
   ch
watch          M                spawn
   ch
 at
w




               watch
           w




                       w
        t a




                       at
          ch




                           ch
enter comet




demo
INSTALL NPM
                                     (node packet manager)

coder@apollo:~/Work/src/node/examples$ curl http://npmjs.org/install.sh | sh
...
npm ok
It worked

coder@apollo:~/Work/src/node/examples$ npm search | wc -l
1918

coder@apollo:~/Work/src/node/examples$ npm install connect socket.io underscore
coder@apollo:~/Work/src/node/examples$ npm list
!"# connect@1.4.1
$ !"" mime@1.2.2
$ %"" qs@0.1.0
%"" socket.io@0.6.17
%"" underscore@1.1.6
server/
                                                      routing
progress_server.js




                     var server = connect(
                       connect.favicon(),
                       connect.logger({"buffer": true}),
                       connect.router(function(resource) {
                         resource.post("/spawn", function(request, response) {
                            ...
                         })
                       }),
                       connect.static(path.join(__dirname, "public"), {"cache": true})
                     )
server/
                                                       routing
progress_server.js



                     resource.post("/spawn", function(request, response) {
                       var job = spawn(path.join(__dirname, "bin", "job.sh")),
                           id = ++counter

                          response.writeHead(202, {"Content-Type": "plain/text"})
                          response.end("OKn")

                          job.stdout.on("data", function(output) {
                             var progress = parseInt(output.toString(), 10)
                             _(connections).each(function(connection) {
                                connection.send({"id": id, "progress": progress})
                             })
                          })
                     })
server/
                                                   socket.io
progress_server.js




                     io.listen(server).on("connection", function(client) {

                          connections[client.sessionId] = client

                          client.on("disconnect", function() {
                             delete connections[client.sessionId]
                          })

                     })
server/
                                                       simulation
progress_server.js



                     server.listen(port, host, function() {
                       var spawnJobsInterval = setInterval(function() {
                         http.request({
                           "port": port, "host": host, "method": "POST", "path": "/spawn"
                         }).end()
                       }, Math.floor(Math.random()*2000)+500)

                          server.on("close", function() {
                             clearInterval(spawnJobsInterval)
                             process.exit()
                          })
                     })

                     process.on("SIGINT", function() {
                        server.close()
                     })
interface/html
             <html>
               <head>
                 <title>Node.js - Long Running Jobs</title>
                 <link href="css/style.css" rel="stylesheet" />
                 <script type="text/javascript" src="/socket.io/socket.io.js"></script>
                 <script type="text/javascript" src="js/jquery-1.6.0.js"></script>
                 <script type="text/javascript" src="js/progress.js"></script>
index.html




               </head>
               <body>
                 <div id="template">
                    <div class="progress-container">
                      <span class="progress-text">JOB/? - ?%</span>
                      <div class="progress-bar"></div>
                    </div>
                 </div>
                 <div id="container"> </div>
               </body>
               <script>
                 ...
               </script>
             </html>
interface/
                                            socket.io
             <html>
               ...
               <script>
                 $(function() {
                    var socket = new io.Socket()
index.html




                   socket.on("connect", function() { })
                   socket.on("disconnect", function() { })
                   socket.on("message", function(job) {
                      $("#template").progressBar(job.id, job.progress)
                   })

                   socket.connect()
                 })
               </script>
             </html>
interface/
                                          progress bar
              $.fn.progressBar = function(id, progress) {
                var $template = $(this)
                $("#job-" + id)
                  .otherwise(function() {
                     return $template.children().clone()
progress.js




                       .attr("id", "job-" + id)
                       .find(".progress-text").text("JOB/" + id + " - 0%").end()
                       .appendTo("#container")
                  })
                  .find(".progress-text").text("JOB/" + id + " - " + progress + "%").end()
                  .find(".progress-bar").css("width", progress + "%").end()
                  .tap(function() {
                     if (progress === 100) {
                       $(this)
                         .find(".progress-bar").css("background-color", "red").end()
                         .after(500, function() {
                            $(this).fadeOut("slow", function() {
                               $(this).remove()
                            })
                         })
                     }
interface/
                                       progress bar
              $.fn.otherwise = function(ifNotFound) {
                if (this.length === 0) {
                  return ifNotFound()
                }
progress.js




                return this
              }

              $.fn.after = function(milliseconds, doSomething) {
                var self = this
                setTimeout(function() {
                  doSomething.apply(self)
                }, milliseconds)
                return this
              }

              $.fn.tap = function() {
                var fn = Array.prototype.shift.apply(arguments)
                fn.apply(this, arguments)
                return this
              }
we can do it
with a little
more “style”
server/
                                                   event emitter
                     var Job = (function() {
                       var EventEmitter = require("events").EventEmitter,
progress_server.js



                           spawn = require("child_process").spawn,
                           inherits = require("util").inherits

                       function Job(id) {
                         EventEmitter.call(this)
                         this.id = id
                       }

                       inherits(Job, EventEmitter)

                       Job.prototype.run = function() {
                          return _(this).tap(function(job) {
                             spawn(path.join(__dirname, "bin", "job.sh"))
                               .stdout.on("data", function(output) {
                                  job.emit("progress", job.id, parseInt(output.toString(), 10))
                               })
                          })
                       }
                       return Job
                     })()
server/
                                               event emitter
progress_server.js




                     resource.post("/spawn", function(request, response) {
                       new Job(++counter)
                         .on("progress", function(id, progress) {
                            _(connections).each(function(connection) {
                               connection.send({"id": id, "progress": progress})
                            })
                         })
                         .run()

                          response.writeHead(202, { "Content-Type": "plain/text" })
                          response.end("OKn")
                     })
node.js is
 awesome
 but when
 should i
  use it?
when to use it?

•   chat/messaging
•   real-time applications
•   intelligent proxies
•   high concurrency applications
•   communication hubs
•   coordinators
please tell
me something
 bad about
  node.js
some warnings
•   release stable 0.4.7 (young)
•   lots of stuffs to look at
•   lots of half backed stuffs
•   retro compatibility???
•   bad at handling static contents
•   Bad at handling binary contents
•   hard to find organized and
    authoritative informations
vs
Introduction to Nodejs
Introduction to Nodejs
Questions?
gabriele lana
   gabriele.lana@cleancode.it
     twitter: @gabrielelana

http://joind.in/3359

Weitere ähnliche Inhalte

Was ist angesagt?

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJSSylvain Zimmer
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
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
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
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
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev ConfTom Croucher
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsjacekbecela
 

Was ist angesagt? (20)

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Express node js
Express node jsExpress node js
Express node js
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Express js
Express jsExpress js
Express js
 
Beyond Phoenix
Beyond PhoenixBeyond Phoenix
Beyond Phoenix
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
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
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on 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...
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
NodeJS
NodeJSNodeJS
NodeJS
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
What is nodejs
What is nodejsWhat is nodejs
What is nodejs
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Node ppt
Node pptNode ppt
Node ppt
 

Andere mochten auch

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture AppDynamics
 
JavaScript and Node.js Fundamentals
JavaScript and Node.js FundamentalsJavaScript and Node.js Fundamentals
JavaScript and Node.js FundamentalsJimmy Guerrero
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907NodejsFoundation
 

Andere mochten auch (6)

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
JavaScript and Node.js Fundamentals
JavaScript and Node.js FundamentalsJavaScript and Node.js Fundamentals
JavaScript and Node.js Fundamentals
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 

Ähnlich wie Introduction to Nodejs

Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Sunny Gupta
 
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
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Ismael Celis
 
Spring data iii
Spring data iiiSpring data iii
Spring data iii명철 강
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
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
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless BallerinaBallerina
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web developmentJohannes Brodwall
 
node.js workshop- node.js basics
node.js workshop- node.js basicsnode.js workshop- node.js basics
node.js workshop- node.js basicsQiong Wu
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.jsWebsecurify
 

Ähnlich wie Introduction to Nodejs (20)

Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02
 
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...
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010
 
Spring data iii
Spring data iiiSpring data iii
Spring data iii
 
From Node to Go
From Node to GoFrom Node to Go
From Node to Go
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
Socket.IO
Socket.IOSocket.IO
Socket.IO
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
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.
 
XQuery Rocks
XQuery RocksXQuery Rocks
XQuery Rocks
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless Ballerina
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web development
 
node.js workshop- node.js basics
node.js workshop- node.js basicsnode.js workshop- node.js basics
node.js workshop- node.js basics
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 

Mehr von Gabriele Lana

Microservice Architectures
Microservice ArchitecturesMicroservice Architectures
Microservice ArchitecturesGabriele Lana
 
Professional Programmer 2018
Professional Programmer 2018Professional Programmer 2018
Professional Programmer 2018Gabriele Lana
 
Parse Everything With Elixir
Parse Everything With ElixirParse Everything With Elixir
Parse Everything With ElixirGabriele Lana
 
Professional Programmer (3 Years Later)
Professional Programmer (3 Years Later)Professional Programmer (3 Years Later)
Professional Programmer (3 Years Later)Gabriele Lana
 
Resource Oriented Design
Resource Oriented DesignResource Oriented Design
Resource Oriented DesignGabriele Lana
 
Agileday Coderetreat 2013
Agileday Coderetreat 2013Agileday Coderetreat 2013
Agileday Coderetreat 2013Gabriele Lana
 
Milano Legacy Coderetreat 2013
Milano Legacy Coderetreat 2013Milano Legacy Coderetreat 2013
Milano Legacy Coderetreat 2013Gabriele Lana
 
Minimum Viable Product
Minimum Viable ProductMinimum Viable Product
Minimum Viable ProductGabriele Lana
 
Professional Programmer
Professional ProgrammerProfessional Programmer
Professional ProgrammerGabriele Lana
 
It is not supposed to fly but it does
It is not supposed to fly but it doesIt is not supposed to fly but it does
It is not supposed to fly but it doesGabriele Lana
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartGabriele Lana
 

Mehr von Gabriele Lana (20)

Microservice Architectures
Microservice ArchitecturesMicroservice Architectures
Microservice Architectures
 
Professional Programmer 2018
Professional Programmer 2018Professional Programmer 2018
Professional Programmer 2018
 
Parse Everything With Elixir
Parse Everything With ElixirParse Everything With Elixir
Parse Everything With Elixir
 
The Magic Of Elixir
The Magic Of ElixirThe Magic Of Elixir
The Magic Of Elixir
 
Professional Programmer (3 Years Later)
Professional Programmer (3 Years Later)Professional Programmer (3 Years Later)
Professional Programmer (3 Years Later)
 
Resource Oriented Design
Resource Oriented DesignResource Oriented Design
Resource Oriented Design
 
Agileday Coderetreat 2013
Agileday Coderetreat 2013Agileday Coderetreat 2013
Agileday Coderetreat 2013
 
Milano Legacy Coderetreat 2013
Milano Legacy Coderetreat 2013Milano Legacy Coderetreat 2013
Milano Legacy Coderetreat 2013
 
Minimum Viable Product
Minimum Viable ProductMinimum Viable Product
Minimum Viable Product
 
API Over HTTP
API Over HTTPAPI Over HTTP
API Over HTTP
 
coderetreat
coderetreatcoderetreat
coderetreat
 
Professional Programmer
Professional ProgrammerProfessional Programmer
Professional Programmer
 
It is not supposed to fly but it does
It is not supposed to fly but it doesIt is not supposed to fly but it does
It is not supposed to fly but it does
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
 
Nosql
NosqlNosql
Nosql
 
Magic of Ruby
Magic of RubyMagic of Ruby
Magic of Ruby
 
Why couchdb is cool
Why couchdb is coolWhy couchdb is cool
Why couchdb is cool
 
ProgrammingKatas
ProgrammingKatasProgrammingKatas
ProgrammingKatas
 
CouchDB Vs MongoDB
CouchDB Vs MongoDBCouchDB Vs MongoDB
CouchDB Vs MongoDB
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 

Kürzlich hochgeladen

Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 

Kürzlich hochgeladen (20)

Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 

Introduction to Nodejs

  • 3. why node.js? “Node's goal is to provide an easy way to build scalable network programs” http://nodejs.org/#about
  • 4. what is node.js? • asynchronous i/o framework • core in c++ on top of v8 • rest of it in javascript • swiss army knife for network related stuffs • can handle thousands of concurrent connections with minimal overhead (cpu/memory) on a single process
  • 9. you can “always” scale with multiple machines but it costs you $$$
  • 12. CPU BOUND TASKS? but... what is HE doing?
  • 13. CPU BOUND TASKS? ...OR I/o but... BOUND what is HE TASKS? doing?
  • 14. synchronous I/0 function productsInCart(request, response) { var db = new Db() var user = new User(request) if (user.isAuthorized("cart/products")) { response.write( JSON.stringify( db.productsInCart(user.cartId()) ) ) } else { response.unauthorized() } }
  • 15. synchronous I/0 function productsInCart(request, response) { var db = new Db() var user = new User(request) if (user.isAuthorized("cart/products")) { response.write( JSON.stringify( db.productsInCart(user.cartId()) ) ) } else { response.unauthorized() } }
  • 16. synchronous I/0 function productsInCart(request, response) { var db = new Db() var user = new User(request) if (user.isAuthorized("cart/products")) { response.write( JSON.stringify( db.productsInCart(user.cartId()) ) ) } else { response.unauthorized() } }
  • 17. synchronous I/0 function productsInCart(request, response) { var db = new Db() var user = new User(request) if (user.isAuthorized("cart/products")) { response.write( JSON.stringify( db.productsInCart(user.cartId()) ) ) } else { response.unauthorized() } }
  • 19. single thread asynchronous I/0 I am “callback” call me if you need me...
  • 20. hello_world_server.js Event Emitter var http = require("http") var server = http.createServer(function(request, response) { response.writeHead(200, { "Content-Type": "plain/text" }) response.write("Hello Worldn") response.end() }) server.listen(8080) console.log("> SERVER STARTED")
  • 21. hello_world_server.js Event Emitter var http = require("http") var server = http.createServer(function(request, response) { response.writeHead(200, { "Content-Type": "plain/text" }) response.write("Hello Worldn") response.end() }) server.listen(8080) console.log("> SERVER STARTED")
  • 22. hello_world_server.js Event Emitter var http = require("http") var server = http.createServer(function(request, response) { response.writeHead(200, { "Content-Type": "plain/text" }) response.write("Hello Worldn") response.end() }) server.listen(8080) console.log("> SERVER STARTED")
  • 23. hello_world_server.js Event Emitter var http = require("http") var server = http.createServer(function(request, response) { response.writeHead(200, { "Content-Type": "plain/text" }) response.write("Hello Worldn") response.end() }) server.listen(8080) console.log("> SERVER STARTED")
  • 24. Event Emitter coder@apollo:~/Work/src/node/examples$ node hello_world_server.js > SERVER STARTED #1 coder@apollo:~$ curl "http://localhost:8080/" Hello World #2
  • 25. Event Emitter var server = require("http").createServer() hello_world_server.js server.on("request", function(request, response) { console.log("> REQUEST STARTED") request.on("end", function() { console.log("> REQUEST CLOSED") response.writeHead(200, { "Content-Type": "plain/text" }) response.end("Hello Worldn") server.close() }) response.on("close", function() { console.log("> RESPONSE CLOSED") }) })
  • 26. hello_world_server.js Event Emitter ... server.on("close", function() { console.log("> SERVER CLOSED") }) server.on("listening", function() { console.log("> SERVER STARTED") }) server.listen(8080)
  • 27. Event Emitter coder@apollo:~/Work/src/node/examples$ node hello_world_server.js > SERVER STARTED #1 coder@apollo:~$ curl "http://localhost:8080/" Hello World #2 #1 > REQUEST STARTED > REQUEST CLOSED > SERVER CLOSED
  • 29. data streamS server.on("request", function(request, response) { var chunks = [], output = fs.createWriteStream("./output") proxy_stream.js request.on("data", function(chunk) { chunks = forEachLine(chunks.concat(chunk), function(line) { output.write(parseInt(line, 10) * 2) output.write("n") }) }) request.on("end", function() { response.writeHead(200, { "Content-Type": "plain/text" }) response.end("OKn") output.end() server.close() }) })
  • 30. data streamS coder@apollo:~/Work/src/node/examples$ node stream_doubler.js #1 coder@apollo:~$ curl "http://localhost:8080/" --data $'1n2n3n' OK #2 coder@apollo:~/Work/src/node/examples$ cat output 2 4 6 #1
  • 31. why javascript? • Friendly callbacks • ubiquitous (well known) • no I/o primitives • one language to rule them all
  • 32. web applications before: a web mind shift #1 server with some application logic application Web server application application application
  • 33. web applications after: an application mind shift #1 accessible over http web server application
  • 34. web applications after: an application mind shift #1 that can communicate and collaborate with the world web server application
  • 35. web applications before: stateful mind shift #2 • no easy to scale • no easy to reuse v M c
  • 36. web applications before: stateful mind shift #2 • no easy to scale • no easy to reuse v M c conversation application state state
  • 37. web applications before: stateful mind shift #2 • no easy to scale • no easy to reuse v M c tightly coupled
  • 38. web applications after: stateless mind shift #2 • easy to scale • easy to reuse v http M c
  • 39. web applications after: stateless mind shift #2 • easy to scale • easy to reuse v http M c conversation application state state
  • 40. web applications after: stateless mind shift #2 http web server M http statefull connection • easy to scale M • easy to reuse
  • 43. the fork long_running_job.sh be with you #!/bin/bash for count in `seq 1 100`; do echo $count sleep 0.1 done
  • 44. the fork long_running_server.js be with you var spawn = require("child_process").spawn, server = require("http").createServer() server.on("request", function(request, response) { var job = spawn("./long_running_job.sh") job.stdout.on("data", function(tick) { response.write(tick) }) job.on("exit", function() { response.end() }) })
  • 45. the fork be with you coder@apollo:~$ ab -c 1 -n 1 "http://localhost:8080/" ... Concurrency Level: 1 Time taken for tests: 10.531 seconds ... coder@apollo:~$ ab -c 1 -n 2 "http://localhost:8080/" ... Concurrency Level: 1 Time taken for tests: 20.108 seconds ...
  • 46. the fork be with you coder@apollo:~$ ab -c 2 -n 1 "http://localhost:8080/" ... Concurrency Level: 2 Time taken for tests: 10.634 seconds ... coder@apollo:~$ ab -c 100 -n 100 "http://localhost:8080/" ... Concurrency Level: 100 Time taken for tests: 11.198 seconds ... coder@apollo:~$ ab -c 500 -n 500 "http://localhost:8080/" ... Concurrency Level: 500 Time taken for tests: 31.082 seconds ...
  • 47. enter comet w at ch watch M spawn ch at w watch w w t a at ch ch
  • 49. INSTALL NPM (node packet manager) coder@apollo:~/Work/src/node/examples$ curl http://npmjs.org/install.sh | sh ... npm ok It worked coder@apollo:~/Work/src/node/examples$ npm search | wc -l 1918 coder@apollo:~/Work/src/node/examples$ npm install connect socket.io underscore coder@apollo:~/Work/src/node/examples$ npm list !"# connect@1.4.1 $ !"" mime@1.2.2 $ %"" qs@0.1.0 %"" socket.io@0.6.17 %"" underscore@1.1.6
  • 50. server/ routing progress_server.js var server = connect( connect.favicon(), connect.logger({"buffer": true}), connect.router(function(resource) { resource.post("/spawn", function(request, response) { ... }) }), connect.static(path.join(__dirname, "public"), {"cache": true}) )
  • 51. server/ routing progress_server.js resource.post("/spawn", function(request, response) { var job = spawn(path.join(__dirname, "bin", "job.sh")), id = ++counter response.writeHead(202, {"Content-Type": "plain/text"}) response.end("OKn") job.stdout.on("data", function(output) { var progress = parseInt(output.toString(), 10) _(connections).each(function(connection) { connection.send({"id": id, "progress": progress}) }) }) })
  • 52. server/ socket.io progress_server.js io.listen(server).on("connection", function(client) { connections[client.sessionId] = client client.on("disconnect", function() { delete connections[client.sessionId] }) })
  • 53. server/ simulation progress_server.js server.listen(port, host, function() { var spawnJobsInterval = setInterval(function() { http.request({ "port": port, "host": host, "method": "POST", "path": "/spawn" }).end() }, Math.floor(Math.random()*2000)+500) server.on("close", function() { clearInterval(spawnJobsInterval) process.exit() }) }) process.on("SIGINT", function() { server.close() })
  • 54. interface/html <html> <head> <title>Node.js - Long Running Jobs</title> <link href="css/style.css" rel="stylesheet" /> <script type="text/javascript" src="/socket.io/socket.io.js"></script> <script type="text/javascript" src="js/jquery-1.6.0.js"></script> <script type="text/javascript" src="js/progress.js"></script> index.html </head> <body> <div id="template"> <div class="progress-container"> <span class="progress-text">JOB/? - ?%</span> <div class="progress-bar"></div> </div> </div> <div id="container"> </div> </body> <script> ... </script> </html>
  • 55. interface/ socket.io <html> ... <script> $(function() { var socket = new io.Socket() index.html socket.on("connect", function() { }) socket.on("disconnect", function() { }) socket.on("message", function(job) { $("#template").progressBar(job.id, job.progress) }) socket.connect() }) </script> </html>
  • 56. interface/ progress bar $.fn.progressBar = function(id, progress) { var $template = $(this) $("#job-" + id) .otherwise(function() { return $template.children().clone() progress.js .attr("id", "job-" + id) .find(".progress-text").text("JOB/" + id + " - 0%").end() .appendTo("#container") }) .find(".progress-text").text("JOB/" + id + " - " + progress + "%").end() .find(".progress-bar").css("width", progress + "%").end() .tap(function() { if (progress === 100) { $(this) .find(".progress-bar").css("background-color", "red").end() .after(500, function() { $(this).fadeOut("slow", function() { $(this).remove() }) }) }
  • 57. interface/ progress bar $.fn.otherwise = function(ifNotFound) { if (this.length === 0) { return ifNotFound() } progress.js return this } $.fn.after = function(milliseconds, doSomething) { var self = this setTimeout(function() { doSomething.apply(self) }, milliseconds) return this } $.fn.tap = function() { var fn = Array.prototype.shift.apply(arguments) fn.apply(this, arguments) return this }
  • 58. we can do it with a little more “style”
  • 59. server/ event emitter var Job = (function() { var EventEmitter = require("events").EventEmitter, progress_server.js spawn = require("child_process").spawn, inherits = require("util").inherits function Job(id) { EventEmitter.call(this) this.id = id } inherits(Job, EventEmitter) Job.prototype.run = function() { return _(this).tap(function(job) { spawn(path.join(__dirname, "bin", "job.sh")) .stdout.on("data", function(output) { job.emit("progress", job.id, parseInt(output.toString(), 10)) }) }) } return Job })()
  • 60. server/ event emitter progress_server.js resource.post("/spawn", function(request, response) { new Job(++counter) .on("progress", function(id, progress) { _(connections).each(function(connection) { connection.send({"id": id, "progress": progress}) }) }) .run() response.writeHead(202, { "Content-Type": "plain/text" }) response.end("OKn") })
  • 61. node.js is awesome but when should i use it?
  • 62. when to use it? • chat/messaging • real-time applications • intelligent proxies • high concurrency applications • communication hubs • coordinators
  • 63. please tell me something bad about node.js
  • 64. some warnings • release stable 0.4.7 (young) • lots of stuffs to look at • lots of half backed stuffs • retro compatibility??? • bad at handling static contents • Bad at handling binary contents • hard to find organized and authoritative informations
  • 65. vs
  • 69. gabriele lana gabriele.lana@cleancode.it twitter: @gabrielelana http://joind.in/3359