Node.js - A Quick Tour II

Felix Geisendörfer
Felix GeisendörferChief Quality Enforcer at Debuggable Limited
node.js
                            A quick tour




                                           by Felix Geisendörfer
Donnerstag, 4. März 2010                                           1
Who is talking?

                    • node.js hacker

                    • Cofounder of Debuggable

                    • CakePHP core alumnus

Donnerstag, 4. März 2010                        2
Why Node?



Donnerstag, 4. März 2010               3
Why?

                           Node's goal is to provide an easy
                           way to build scalable network
                           programs.
                                                   -- nodejs.org




Donnerstag, 4. März 2010                                           4
How?

                           Keep slow operations from
                           blocking other operations.




Donnerstag, 4. März 2010                                5
Traditional I/O

                           var data = file.read('file.txt');
                           doSomethingWith(data);




                             Something is not right here


Donnerstag, 4. März 2010                                       6
Traditional I/O

                           var data = file.read('file.txt');

                           // zzzZZzzz   FAIL!
                           doSomethingWith(data);




                              Don’t waste those cycles!


Donnerstag, 4. März 2010                                       7
Async I/O

             file.read('file.txt', function(data) {
               doSomethingWith(data);
             });                                   WIN     ✔
             doSomethingElse();




                           No need to wait for the disk,
                           do something else meanwhile!

Donnerstag, 4. März 2010                                       8
The Present



Donnerstag, 4. März 2010                 9
Quality components

                    • V8 (developed for google chrome)

                    • libev (event loop)

                    • libeio (non-block posix, thread pool)
Donnerstag, 4. März 2010                                      10
CommonJS Modules
            hello.js
             exports.world = function() {
                return 'Hello World';
             };

            main.js
             var hello = require('./hello');
             var sys = require('sys');
             sys.puts(hello.world());


                                $ node main.js
                                Hello World

Donnerstag, 4. März 2010                         11
Child processes
            child.js
             var child = process.createChildProcess('sh',
             ['-c', 'echo hello; sleep 1; echo world;']);
             child.addListener('data', function (chunk) {
               p(chunk);
             });

                              $ node child.js
                              "hellon"
                              # 1 sec delay
                              "worldn"
                              null

Donnerstag, 4. März 2010                                    12
Http Server
 var http = require('http');
 http.createServer(function(req, res) {
   setTimeout(function() {
     res.writeHeader(200, {'Content-Type': 'text/plain'});
     res.write('Thanks for waiting!');
     res.close();
   }, 1000);
 }).listen(4000);

                           $ curl localhost:4000
                           # 1 sec delay
                           Thanks for waiting!

Donnerstag, 4. März 2010                                 13
Tcp Server
              var tcp = require('tcp');
              tcp.createServer(function(socket) {
                socket.addListener('connect', function() {
                  socket.write("Hi, How Are You?n> ");
                });
                socket.addListener('data', function(data) {
                  socket.write(data);
                });
              }).listen(4000);

                            $ nc localhost 4000
                            Hi, How Are You?
                            > Great!
                            Great!
Donnerstag, 4. März 2010                                      14
DNS
          dns.js
           var dns = require('dns');
           dns.resolve4('nodejs.org', function(err, addr, ttl,
           cname) {
            p(addr, ttl, cname);
           });


                           $ node dns.js
                           [ '97.107.132.72' ]
                           84279
                           'nodejs.org'

Donnerstag, 4. März 2010                                         15
Watch File
             watch.js
              process.watchFile(__filename, function() {
                puts('You changed me!');
                process.exit();
              });



                              $ node watch.js
                              # edit watch.js
                              You changed me!

Donnerstag, 4. März 2010                                   16
ECMAScript 5
                    • Getters / setters
                      var a = {};
                      a.__defineGetter__('foo', function() {
                        return 'bar';
                      });
                      puts(a.foo);


                     • Array: filter, forEach, reduce, etc.

                     • JSON.stringify(), JSON.parse()          & more [1]
Donnerstag, 4. März 2010                                                    17
There is only 1 thread
             file.read('file.txt', function(data) {
               // Will never fire
             });

             while (true) {
               // this blocks the entire process
             }


                           Good for conceptual simplicity
                           Bad for CPU-bound algorithms

Donnerstag, 4. März 2010                                    18
The Future



Donnerstag, 4. März 2010                19
Web workers
                    • Multiple node processes that do
                           interprocess communication


                    • CPU-bound algorithms can run separately

                    • Multiple CPU cores can be used efficiently
Donnerstag, 4. März 2010                                          20
Streams

                • Node is working towards a unified data
                           stream interface


                • Stream can be readable, writable or both

                                                             see [2]
Donnerstag, 4. März 2010                                           21
Readable Streams

                • events: ‘data’, ‘end’

                • methods: pause(), resume()


Donnerstag, 4. März 2010                       22
Writeable Streams

                • events: ‘drain’, ‘close’

                • methods: write(), close()


Donnerstag, 4. März 2010                       23
Stream Redirection
    http.createServer(function (req, res) {
      // Open writable file system
      var temp = fs.openTemporaryFile();
      // Pump the request into the temp file.
      stream.pump(req, temp, function (err) {
        if (err) throw err;

        p('sweet!');
      });
    });




Donnerstag, 4. März 2010                        24
Better Socket Support

               • Support for unix sockets, socketpair(), pipe()

               • Pass sockets between processes ➠ load
                       balance requests between web workers




Donnerstag, 4. März 2010                                          25
Debugger
                • V8 support debugging

                • Node has a few bugs with exposing the
                           debugger, those need fixing


                • Command line node-debug REPL tool
Donnerstag, 4. März 2010                                  26
Readline and Curses
                • Bindings for JavaScript

                • Would allow to build better command line
                           tools


                • Goal should be to write a screen clone in
                           node


Donnerstag, 4. März 2010                                      27
HTML and XML parsing
                • HTML is a major protocol

                • Node should be able to parse dirty XML/
                           HTML


                • Should be a SAX-style parser in pure JS
Donnerstag, 4. März 2010                                    28
Support for Windows


                • Patches welcome! : )



Donnerstag, 4. März 2010                     29
Hot code reloading
                                   (maybe)



                • Reload module during runtime

                • Update code without taking server offline


Donnerstag, 4. März 2010                                     30
Suitable Applications

                    • Web frameworks

                    • Real time

                    • Crawlers

Donnerstag, 4. März 2010                           31
More Applications

                    • Process monitoring

                    • File uploading

                    • Streaming

Donnerstag, 4. März 2010                       32
Let’s write a chat



Donnerstag, 4. März 2010                        33
Http Chat in 14 LoC
    var
      http = require('http'),
      messages = [];

    http.createServer(function(req, res) {
      res.writeHeader(200, {'Content-Type' : 'text/plain'});
      if (req.url == '/') {
        res.write(messages.join("n"));
      } else if (req.url !== '/favicon.ico') {
        messages.push(decodeURIComponent(req.url.substr(1)));
        res.write('ok!');
      }
      res.close();
    }).listen(4000);

Donnerstag, 4. März 2010                                        34
Production ready?

                    • For small systems, yes.

                    • Perfect example: Comet server

                    • Usually few bugs, but API is still changing

Donnerstag, 4. März 2010                                            35
Questions?




       ✎             @felixge
       $             http://debuggable.com/
Donnerstag, 4. März 2010                      36
Links
          [1]: http://wiki.github.com/ry/node/ecma-5mozilla-
          features-implemented-in-v8
          [2]: http://wiki.github.com/ry/node/streams




Donnerstag, 4. März 2010                                       37
Bonus Slides!



Donnerstag, 4. März 2010                   38
Dirty



                    JavaScript Views            Memory Store
                    Disk Persistence            Speed > Safety


                                        Dirty


Donnerstag, 4. März 2010                                         39
A scriptable key-value store

    • Let your business logic and your data share the same
            memory / process


    • Network = OVERHEAD - Avoid whenever possible

    • V8 makes it very fast
Donnerstag, 4. März 2010                                     40
How fast?

                   • Set: 3-5 million docs / sec

                   • Get: 40-50 million docs / sec

                           (on my laptop - your milage may vary)
Donnerstag, 4. März 2010                                           41
Benchmarks


                           Do your own!



Donnerstag, 4. März 2010                  42
Disk persistence
               • Append-only log

               • Writes happen every x-Sec or every x-
                      Records


               • Callbacks fire after disk write succeeded
Donnerstag, 4. März 2010                                    43
Dirty Hello World
           hello.js
           var
             Dirty = require('dirty').Dirty,
             posts = new Dirty('test.dirty');

           posts.add({hello: 'dirty world!'});
           posts.set('my-key', {looks: 'nice'});


                     $ node hello.js
                     $ cat test.dirty
                     {"hello":"dirty world!","_key":"3b8f86..."}
                     {"looks":"nice","_key":"my-key"}

Donnerstag, 4. März 2010                                           44
Reloading from Disk
           hello.js
           var
             Dirty = require('dirty').Dirty,
             posts = new Dirty('test.dirty');

           posts.load(function() {
             p(posts.get('my-key'));
           });



                            $ node hello.js
                            {"looks": "nice", "_key": "my-key"}


Donnerstag, 4. März 2010                                          45
Use Cases

                    • Small projects (db < memory)

                    • Rapid prototyping

                    • Add HTTP/TCP interface and scale

Donnerstag, 4. März 2010                                 46
http://github.com/felixge/node-dirty



                              (or google for “dirty felixge”)



Donnerstag, 4. März 2010                                          47
1 of 47

Recommended

Node.js - A practical introduction (v2) by
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)Felix Geisendörfer
4.7K views77 slides
Nodejs - A-quick-tour-v3 by
Nodejs - A-quick-tour-v3Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3Felix Geisendörfer
3.1K views36 slides
Nodejs - A quick tour (v5) by
Nodejs - A quick tour (v5)Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)Felix Geisendörfer
2.8K views58 slides
Nodejs a-practical-introduction-oredev by
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
2.9K views59 slides
Nodejs - A quick tour (v6) by
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Felix Geisendörfer
3.9K views68 slides
Node.js - As a networking tool by
Node.js - As a networking toolNode.js - As a networking tool
Node.js - As a networking toolFelix Geisendörfer
12.9K views47 slides

More Related Content

What's hot

Node.js in production by
Node.js in productionNode.js in production
Node.js in productionFelix Geisendörfer
8.4K views36 slides
Dirty - How simple is your database? by
Dirty - How simple is your database?Dirty - How simple is your database?
Dirty - How simple is your database?Felix Geisendörfer
10.3K views32 slides
Node.js - A Quick Tour by
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick TourFelix Geisendörfer
9.3K views37 slides
Nginx-lua by
Nginx-luaNginx-lua
Nginx-luaДэв Тим Афс
2K views21 slides
How to Test Asynchronous Code (v2) by
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)Felix Geisendörfer
4.8K views41 slides
Introduction to NodeJS with LOLCats by
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
1.2K views31 slides

What's hot(20)

Introduction to NodeJS with LOLCats by Derek Anderson
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
Derek Anderson1.2K views
A language for the Internet: Why JavaScript and Node.js is right for Internet... by 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...
Tom Croucher9.4K views
Non-blocking I/O, Event loops and node.js by Marcus Frödin
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
Marcus Frödin22.8K views
MongoDB Shell Tips & Tricks by MongoDB
MongoDB Shell Tips & TricksMongoDB Shell Tips & Tricks
MongoDB Shell Tips & Tricks
MongoDB8.8K views
Shell Tips & Tricks by MongoDB
Shell Tips & TricksShell Tips & Tricks
Shell Tips & Tricks
MongoDB1.4K views
How Secure Are Docker Containers? by Ben Hall
How Secure Are Docker Containers?How Secure Are Docker Containers?
How Secure Are Docker Containers?
Ben Hall375 views
Introduction to redis - version 2 by Dvir Volk
Introduction to redis - version 2Introduction to redis - version 2
Introduction to redis - version 2
Dvir Volk9.9K views
Debugging and Testing ES Systems by Chris Birchall
Debugging and Testing ES SystemsDebugging and Testing ES Systems
Debugging and Testing ES Systems
Chris Birchall6.8K views
Event-driven IO server-side JavaScript environment based on V8 Engine by Ricardo Silva
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva4.1K views
Kicking ass with redis by Dvir Volk
Kicking ass with redisKicking ass with redis
Kicking ass with redis
Dvir Volk39.1K views
Functional Hostnames and Why they are Bad by Puppet
Functional Hostnames and Why they are BadFunctional Hostnames and Why they are Bad
Functional Hostnames and Why they are Bad
Puppet15.5K views
ElasticSearch by Luiz Rocha
ElasticSearchElasticSearch
ElasticSearch
Luiz Rocha3.8K views

Viewers also liked

Beyond Phoenix by
Beyond PhoenixBeyond Phoenix
Beyond PhoenixGabriele Lana
1.3K views26 slides
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a... by
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...MongoDB
15.5K views60 slides
Building a real life application in node js by
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
20.4K views37 slides
Anatomy of a Modern Node.js Application Architecture by
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
40K views1 slide
Nodejs Explained with Examples by
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
112.3K views78 slides
Introduction to Node.js by
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
71.2K views21 slides

Viewers also liked(6)

Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a... by MongoDB
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
MongoDB15.5K views
Building a real life application in node js by fakedarren
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
fakedarren20.4K views
Anatomy of a Modern Node.js Application Architecture by AppDynamics
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
AppDynamics40K views
Nodejs Explained with Examples by Gabriele Lana
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana112.3K views
Introduction to Node.js by Vikash Singh
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh71.2K views

Similar to Node.js - A Quick Tour II

Node.js and Ruby by
Node.js and RubyNode.js and Ruby
Node.js and RubyMichael Bleigh
16K views61 slides
Ruby on CouchDB - SimplyStored and RockingChair by
Ruby on CouchDB - SimplyStored and RockingChairRuby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChairJonathan Weiss
882 views21 slides
Real Time Web with Node by
Real Time Web with NodeReal Time Web with Node
Real Time Web with NodeTim Caswell
11.3K views29 slides
Persistence Smoothie: Blending SQL and NoSQL (RubyNation Edition) by
Persistence  Smoothie: Blending SQL and NoSQL (RubyNation Edition)Persistence  Smoothie: Blending SQL and NoSQL (RubyNation Edition)
Persistence Smoothie: Blending SQL and NoSQL (RubyNation Edition)Michael Bleigh
3.8K views59 slides
Node js techtalksto by
Node js techtalkstoNode js techtalksto
Node js techtalkstoJason Diller
826 views66 slides
Node Powered Mobile by
Node Powered MobileNode Powered Mobile
Node Powered MobileTim Caswell
2.6K views36 slides

Similar to Node.js - A Quick Tour II(20)

Ruby on CouchDB - SimplyStored and RockingChair by Jonathan Weiss
Ruby on CouchDB - SimplyStored and RockingChairRuby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChair
Jonathan Weiss882 views
Real Time Web with Node by Tim Caswell
Real Time Web with NodeReal Time Web with Node
Real Time Web with Node
Tim Caswell11.3K views
Persistence Smoothie: Blending SQL and NoSQL (RubyNation Edition) by Michael Bleigh
Persistence  Smoothie: Blending SQL and NoSQL (RubyNation Edition)Persistence  Smoothie: Blending SQL and NoSQL (RubyNation Edition)
Persistence Smoothie: Blending SQL and NoSQL (RubyNation Edition)
Michael Bleigh3.8K views
Node Powered Mobile by Tim Caswell
Node Powered MobileNode Powered Mobile
Node Powered Mobile
Tim Caswell2.6K views
Node.js: The What, The How and The When by FITC
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
FITC4.6K views
Introduction to node.js by Ran Mizrahi @ Reversim Summit by Ran Mizrahi
Introduction to node.js by Ran Mizrahi @ Reversim SummitIntroduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Ran Mizrahi2.9K views
Introduction to HTML5 by Adrian Olaru
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
Adrian Olaru1.6K views
New kid on the block node.js by Joel Divekar
New kid on the block node.jsNew kid on the block node.js
New kid on the block node.js
Joel Divekar2.4K views
Node.js and websockets intro by kompozer
Node.js and websockets introNode.js and websockets intro
Node.js and websockets intro
kompozer5.3K views
Database Scalability Patterns by Robert Treat
Database Scalability PatternsDatabase Scalability Patterns
Database Scalability Patterns
Robert Treat967 views
NodeJs by dizabl
NodeJsNodeJs
NodeJs
dizabl722 views
Edted 2010 Dicas de Web by Fabio Akita
Edted 2010 Dicas de WebEdted 2010 Dicas de Web
Edted 2010 Dicas de Web
Fabio Akita651 views
2010.10.30 steven sustaining tdd agile tour shenzhen by Odd-e
2010.10.30 steven sustaining tdd   agile tour shenzhen2010.10.30 steven sustaining tdd   agile tour shenzhen
2010.10.30 steven sustaining tdd agile tour shenzhen
Odd-e460 views
Planning for the Horizontal: Scaling Node.js Applications by Modulus
Planning for the Horizontal: Scaling Node.js ApplicationsPlanning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js Applications
Modulus 5.8K views

Recently uploaded

Melek BEN MAHMOUD.pdf by
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdfMelekBenMahmoud
14 views1 slide
Vertical User Stories by
Vertical User StoriesVertical User Stories
Vertical User StoriesMoisés Armani Ramírez
14 views16 slides
STPI OctaNE CoE Brochure.pdf by
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdfmadhurjyapb
14 views1 slide
The Research Portal of Catalonia: Growing more (information) & more (services) by
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)CSUC - Consorci de Serveis Universitaris de Catalunya
80 views25 slides
The details of description: Techniques, tips, and tangents on alternative tex... by
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...BookNet Canada
127 views24 slides
Scaling Knowledge Graph Architectures with AI by
Scaling Knowledge Graph Architectures with AIScaling Knowledge Graph Architectures with AI
Scaling Knowledge Graph Architectures with AIEnterprise Knowledge
30 views15 slides

Recently uploaded(20)

STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb14 views
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada127 views
Transcript: The Details of Description Techniques tips and tangents on altern... by BookNet Canada
Transcript: The Details of Description Techniques tips and tangents on altern...Transcript: The Details of Description Techniques tips and tangents on altern...
Transcript: The Details of Description Techniques tips and tangents on altern...
BookNet Canada136 views
handbook for web 3 adoption.pdf by Liveplex
handbook for web 3 adoption.pdfhandbook for web 3 adoption.pdf
handbook for web 3 adoption.pdf
Liveplex22 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely21 views
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab19 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi127 views
Empathic Computing: Delivering the Potential of the Metaverse by Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
Mark Billinghurst478 views
AMAZON PRODUCT RESEARCH.pdf by JerikkLaureta
AMAZON PRODUCT RESEARCH.pdfAMAZON PRODUCT RESEARCH.pdf
AMAZON PRODUCT RESEARCH.pdf
JerikkLaureta26 views

Node.js - A Quick Tour II

  • 1. node.js A quick tour by Felix Geisendörfer Donnerstag, 4. März 2010 1
  • 2. Who is talking? • node.js hacker • Cofounder of Debuggable • CakePHP core alumnus Donnerstag, 4. März 2010 2
  • 4. Why? Node's goal is to provide an easy way to build scalable network programs. -- nodejs.org Donnerstag, 4. März 2010 4
  • 5. How? Keep slow operations from blocking other operations. Donnerstag, 4. März 2010 5
  • 6. Traditional I/O var data = file.read('file.txt'); doSomethingWith(data); Something is not right here Donnerstag, 4. März 2010 6
  • 7. Traditional I/O var data = file.read('file.txt'); // zzzZZzzz FAIL! doSomethingWith(data); Don’t waste those cycles! Donnerstag, 4. März 2010 7
  • 8. Async I/O file.read('file.txt', function(data) { doSomethingWith(data); }); WIN ✔ doSomethingElse(); No need to wait for the disk, do something else meanwhile! Donnerstag, 4. März 2010 8
  • 10. Quality components • V8 (developed for google chrome) • libev (event loop) • libeio (non-block posix, thread pool) Donnerstag, 4. März 2010 10
  • 11. CommonJS Modules hello.js exports.world = function() { return 'Hello World'; }; main.js var hello = require('./hello'); var sys = require('sys'); sys.puts(hello.world()); $ node main.js Hello World Donnerstag, 4. März 2010 11
  • 12. Child processes child.js var child = process.createChildProcess('sh', ['-c', 'echo hello; sleep 1; echo world;']); child.addListener('data', function (chunk) { p(chunk); }); $ node child.js "hellon" # 1 sec delay "worldn" null Donnerstag, 4. März 2010 12
  • 13. Http Server var http = require('http'); http.createServer(function(req, res) { setTimeout(function() { res.writeHeader(200, {'Content-Type': 'text/plain'}); res.write('Thanks for waiting!'); res.close(); }, 1000); }).listen(4000); $ curl localhost:4000 # 1 sec delay Thanks for waiting! Donnerstag, 4. März 2010 13
  • 14. Tcp Server var tcp = require('tcp'); tcp.createServer(function(socket) { socket.addListener('connect', function() { socket.write("Hi, How Are You?n> "); }); socket.addListener('data', function(data) { socket.write(data); }); }).listen(4000); $ nc localhost 4000 Hi, How Are You? > Great! Great! Donnerstag, 4. März 2010 14
  • 15. DNS dns.js var dns = require('dns'); dns.resolve4('nodejs.org', function(err, addr, ttl, cname) { p(addr, ttl, cname); }); $ node dns.js [ '97.107.132.72' ] 84279 'nodejs.org' Donnerstag, 4. März 2010 15
  • 16. Watch File watch.js process.watchFile(__filename, function() { puts('You changed me!'); process.exit(); }); $ node watch.js # edit watch.js You changed me! Donnerstag, 4. März 2010 16
  • 17. ECMAScript 5 • Getters / setters var a = {}; a.__defineGetter__('foo', function() { return 'bar'; }); puts(a.foo); • Array: filter, forEach, reduce, etc. • JSON.stringify(), JSON.parse() & more [1] Donnerstag, 4. März 2010 17
  • 18. There is only 1 thread file.read('file.txt', function(data) { // Will never fire }); while (true) { // this blocks the entire process } Good for conceptual simplicity Bad for CPU-bound algorithms Donnerstag, 4. März 2010 18
  • 19. The Future Donnerstag, 4. März 2010 19
  • 20. Web workers • Multiple node processes that do interprocess communication • CPU-bound algorithms can run separately • Multiple CPU cores can be used efficiently Donnerstag, 4. März 2010 20
  • 21. Streams • Node is working towards a unified data stream interface • Stream can be readable, writable or both see [2] Donnerstag, 4. März 2010 21
  • 22. Readable Streams • events: ‘data’, ‘end’ • methods: pause(), resume() Donnerstag, 4. März 2010 22
  • 23. Writeable Streams • events: ‘drain’, ‘close’ • methods: write(), close() Donnerstag, 4. März 2010 23
  • 24. Stream Redirection http.createServer(function (req, res) { // Open writable file system var temp = fs.openTemporaryFile(); // Pump the request into the temp file. stream.pump(req, temp, function (err) { if (err) throw err; p('sweet!'); }); }); Donnerstag, 4. März 2010 24
  • 25. Better Socket Support • Support for unix sockets, socketpair(), pipe() • Pass sockets between processes ➠ load balance requests between web workers Donnerstag, 4. März 2010 25
  • 26. Debugger • V8 support debugging • Node has a few bugs with exposing the debugger, those need fixing • Command line node-debug REPL tool Donnerstag, 4. März 2010 26
  • 27. Readline and Curses • Bindings for JavaScript • Would allow to build better command line tools • Goal should be to write a screen clone in node Donnerstag, 4. März 2010 27
  • 28. HTML and XML parsing • HTML is a major protocol • Node should be able to parse dirty XML/ HTML • Should be a SAX-style parser in pure JS Donnerstag, 4. März 2010 28
  • 29. Support for Windows • Patches welcome! : ) Donnerstag, 4. März 2010 29
  • 30. Hot code reloading (maybe) • Reload module during runtime • Update code without taking server offline Donnerstag, 4. März 2010 30
  • 31. Suitable Applications • Web frameworks • Real time • Crawlers Donnerstag, 4. März 2010 31
  • 32. More Applications • Process monitoring • File uploading • Streaming Donnerstag, 4. März 2010 32
  • 33. Let’s write a chat Donnerstag, 4. März 2010 33
  • 34. Http Chat in 14 LoC var http = require('http'), messages = []; http.createServer(function(req, res) { res.writeHeader(200, {'Content-Type' : 'text/plain'}); if (req.url == '/') { res.write(messages.join("n")); } else if (req.url !== '/favicon.ico') { messages.push(decodeURIComponent(req.url.substr(1))); res.write('ok!'); } res.close(); }).listen(4000); Donnerstag, 4. März 2010 34
  • 35. Production ready? • For small systems, yes. • Perfect example: Comet server • Usually few bugs, but API is still changing Donnerstag, 4. März 2010 35
  • 36. Questions? ✎ @felixge $ http://debuggable.com/ Donnerstag, 4. März 2010 36
  • 37. Links [1]: http://wiki.github.com/ry/node/ecma-5mozilla- features-implemented-in-v8 [2]: http://wiki.github.com/ry/node/streams Donnerstag, 4. März 2010 37
  • 39. Dirty JavaScript Views Memory Store Disk Persistence Speed > Safety Dirty Donnerstag, 4. März 2010 39
  • 40. A scriptable key-value store • Let your business logic and your data share the same memory / process • Network = OVERHEAD - Avoid whenever possible • V8 makes it very fast Donnerstag, 4. März 2010 40
  • 41. How fast? • Set: 3-5 million docs / sec • Get: 40-50 million docs / sec (on my laptop - your milage may vary) Donnerstag, 4. März 2010 41
  • 42. Benchmarks Do your own! Donnerstag, 4. März 2010 42
  • 43. Disk persistence • Append-only log • Writes happen every x-Sec or every x- Records • Callbacks fire after disk write succeeded Donnerstag, 4. März 2010 43
  • 44. Dirty Hello World hello.js var Dirty = require('dirty').Dirty, posts = new Dirty('test.dirty'); posts.add({hello: 'dirty world!'}); posts.set('my-key', {looks: 'nice'}); $ node hello.js $ cat test.dirty {"hello":"dirty world!","_key":"3b8f86..."} {"looks":"nice","_key":"my-key"} Donnerstag, 4. März 2010 44
  • 45. Reloading from Disk hello.js var Dirty = require('dirty').Dirty, posts = new Dirty('test.dirty'); posts.load(function() { p(posts.get('my-key')); }); $ node hello.js {"looks": "nice", "_key": "my-key"} Donnerstag, 4. März 2010 45
  • 46. Use Cases • Small projects (db < memory) • Rapid prototyping • Add HTTP/TCP interface and scale Donnerstag, 4. März 2010 46
  • 47. http://github.com/felixge/node-dirty (or google for “dirty felixge”) Donnerstag, 4. März 2010 47