SlideShare ist ein Scribd-Unternehmen logo
1 von 51
Downloaden Sie, um offline zu lesen
Using Node.js to
               Build Great
           Streaming Services

@sh1mmer
Tom Hughes-Croucher
       @sh1mmer
@sh1mmer
@sh1mmer
Scalable Server-Side Code with JavaScript




                  Node                        Up and Running




                                             Tom Hughes-Croucher




       http://ofps.oreilly.com/titles/9781449398583/
   http://shop.oreilly.com/product/0636920015956.do
@sh1mmer
A story


@sh1mmer
factory


@sh1mmer
@sh1mmer
@sh1mmer
var http = require('http');

   var server = http.createServer();
   server.listen(8000);
   server.on('request', function(req,res) {
     var doodad = new Doodad();
     res.writeHead(200,{'Content-Type':'text/doodad'});
     res.end(doodad);
   });




@sh1mmer
Making Doodads


@sh1mmer
Knobs
      Screens   Antennas
                           & buttons


@sh1mmer
@sh1mmer
@sh1mmer
@sh1mmer
@sh1mmer
@sh1mmer
var http = require('http'), fs = require('fs');

   var server = http.createServer();
   server.listen(8000);
   server.on('request', function(req,res) {
     var screen = fs.readFileSync('/factory1/screen');
     var dial = fs.readFileSync('/factory2/dial');

     var doodad = new Doodad(screen, dial);
     res.writeHead(200,{'Content-Type':'text/doodad'});
     res.end(doodad);
   });




@sh1mmer
Improving the factory
         with streaming


@sh1mmer
@sh1mmer
@sh1mmer
@sh1mmer
var http = require('http');

   var server = http.createServer();
   server.listen(8000);
   server.on('request', function(req,res) {
     var parts = 0;
     http.get('factory1/screen/', function(res) {
        var screen = "";
        res.on('data', function(d) { screen += d });
        res.on('end', finish);
        parts++;
     };
     http.get('factory2/dial', function(res) {
        var dial = ""
        res.on('data', function(d) { dial += d });
        res.on('end', finish);
        parts++;
     }
     function finish() {
        if(parts == 2) {
          var doodad = new Doodad(screen, dial);
          res.writeHead(200,{'Content-Type':'text/doodad'});
          res.end(doodad);
        }
     }
   });
@sh1mmer
Streams API


@sh1mmer
Streams
     •   Readable              •   Writable
         •   'data' event          •   write()
         •   'end' event           •   end()
         •   pause()
         •   resume()              •   'drain' event
         •   destroy()             •   destroy()
         •   pipe()                •   destroySoon()

@sh1mmer
var stream = require('stream');

   var s = new stream.Stream(); //I am an EventEmitter
   s.readable = true; //now I implement read API

   s.emit('data', "my data");

   s.emit('end'); //I'm done sending data




@sh1mmer
var stream = require('stream');

   var s = new stream.Stream(); //I am an EventEmitter
   s.writable = true; //now I implement write API
   s.data = "";

   s.write = function(d) {
      s.data += d;
   };

   s.end = function() {
      if(s.data) { console.log(s.data) }
   };

   s.destroy = function() {
     s.writable = false;
   }


@sh1mmer
The too many parts
       problem and why
     phone calls don't work

@sh1mmer
@sh1mmer
nextTick
                      Event Loop Fail
nextTick
                     Run stuff
                     TCP
                     Conn             node.cc
                           FS
                          Read

                                 add-ons          v8
                      TCP
                      Conn

                      Timeout             libuv
                     TCP
Interval
                     Conn
                                  libev           iocp
                    FS
  Timeout          Read
             FS
            Read
stream.pause()
nextTick
                      Event Loop Fail
nextTick
                      stream.pause()
                     TCP
                     Conn              node.cc
                           FS
                          Read

                                 add-ons          v8
                      TCP
                      Conn

                      Timeout             libuv
                     TCP
Interval
                     Conn
                                  libev           iocp
                    FS
  Timeout          Read
             FS
            Read
Managing Backpressure
     • Manage Buffer sizes
     • Use pause() / resume() to control back
       pressure
     • Assume that 'data' event may happen after
       pause
     • Remember node buffer -> kernel buffer
@sh1mmer
//manage Node's write Buffers
   if(socket.bufferSize > maxSafe) {
     writeStream.pause();
   }

   //Manage RS read stream Buffers
   fs.createReadStream('./path/to/file', {
     flags: 'r',
     encoding: null,
     fd: null,
     mode: 0666,
     bufferSize: 64 * 1024
   });




@sh1mmer
New API


@sh1mmer
New Streams TBD
•   Writable streams

    •   Same

•   Readable (https://github.com/isaacs/readable-stream)

    •   configurable stream buffer waterline

    •   'readable' event
    •   read(len) -> returns data

•   Pipe

    •   Subscribers must implement readable stream

    •   No more direct access with Pipe
@sh1mmer
Types of Streaming


@sh1mmer
Simplex


@sh1mmer
var fs = require('fs');

   var rs = fs.createReadStream('/my/file/path');
   rs.on('data', function(d) {
     console.log(d);
   });




@sh1mmer
Throughput


@sh1mmer
var fs = require('fs');

   var rs = fs.createReadStream('/my/file/path');
   rs.pipe(process.stdout);




@sh1mmer
Duplex


@sh1mmer
var bot1 = new chatterBot();
   var bot2 = new chatterBot();

   bot1.pipe(bot2).pipe(bot1);




@sh1mmer
Libraries


@sh1mmer
JSONStream


@sh1mmer
{"total_rows":129,"offset":0,"rows":[
      { "id":"change1_0.6995461115147918"
      , "key":"change1_0.6995461115147918"
      , "value":{"rev":"1-e240bae28c7bb3667f02760f6398d508"}
      , "doc":{
           "_id": "change1_0.6995461115147918"
         , "_rev": "1-e240bae28c7bb3667f02760f6398d508","hello":1}
      },
      { "id":"change2_0.6995461115147918"
      , "key":"change2_0.6995461115147918"
      , "value":{"rev":"1-13677d36b98c0c075145bb8975105153"}
      , "doc":{
           "_id":"change2_0.6995461115147918"
         , "_rev":"1-13677d36b98c0c075145bb8975105153"
         , "hello":2
         }
      },
   ]}


@sh1mmer
var stream = JSONStream.parse(['rows', true, 'doc']) //rows,
   ANYTHING, doc

   stream.on('data', function(data) {
     console.log('received:', data);
   });

   stream.on('root', function(root, count) {
     if (!count) {
       console.log('no matches found:', root);
     }
   });




@sh1mmer
node-libexpat


@sh1mmer
Application


@sh1mmer
Questions?


@sh1mmer

Weitere ähnliche Inhalte

Was ist angesagt?

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
Tony Fabeen
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
Tom Croucher
 

Was ist angesagt? (20)

Puppet and the HashiStack
Puppet and the HashiStackPuppet and the HashiStack
Puppet and the HashiStack
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
 
Lua tech talk
Lua tech talkLua tech talk
Lua tech talk
 
Ubic
UbicUbic
Ubic
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stackBootstrapping multidc observability stack
Bootstrapping multidc observability stack
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Securing Prometheus exporters using HashiCorp Vault
Securing Prometheus exporters using HashiCorp VaultSecuring Prometheus exporters using HashiCorp Vault
Securing Prometheus exporters using HashiCorp Vault
 
Testing your infrastructure with litmus
Testing your infrastructure with litmusTesting your infrastructure with litmus
Testing your infrastructure with litmus
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stackBootstrapping multidc observability stack
Bootstrapping multidc observability stack
 
Nginx-lua
Nginx-luaNginx-lua
Nginx-lua
 
Creating Reusable Puppet Profiles
Creating Reusable Puppet ProfilesCreating Reusable Puppet Profiles
Creating Reusable Puppet Profiles
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in Vault
 
Hopping in clouds: a tale of migration from one cloud provider to another
Hopping in clouds: a tale of migration from one cloud provider to anotherHopping in clouds: a tale of migration from one cloud provider to another
Hopping in clouds: a tale of migration from one cloud provider to another
 
Observability with Consul Connect
Observability with Consul ConnectObservability with Consul Connect
Observability with Consul Connect
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 

Ähnlich wie Using Node.js to Build Great Streaming Services - HTML5 Dev Conf

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
 
Use perl creating web services with xml rpc
Use perl creating web services with xml rpcUse perl creating web services with xml rpc
Use perl creating web services with xml rpc
Johnny Pork
 

Ähnlich wie Using Node.js to Build Great Streaming Services - HTML5 Dev Conf (20)

Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
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
 
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...
 
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...
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsAnchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
 
Streams in Node.js
Streams in Node.jsStreams in Node.js
Streams in Node.js
 
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
 
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.
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
03 sockets
03 sockets03 sockets
03 sockets
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011
 
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
 
Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02
 
Use perl creating web services with xml rpc
Use perl creating web services with xml rpcUse perl creating web services with xml rpc
Use perl creating web services with xml rpc
 
Pycon - Python for ethical hackers
Pycon - Python for ethical hackers Pycon - Python for ethical hackers
Pycon - Python for ethical hackers
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 

Mehr von Tom Croucher

Using Node.js to improve the performance of Mobile apps and Mobile web
Using Node.js to improve  the performance of  Mobile apps and Mobile webUsing Node.js to improve  the performance of  Mobile apps and Mobile web
Using Node.js to improve the performance of Mobile apps and Mobile web
Tom Croucher
 
Creating the Internet of Things with JavaScript - Fluent Conf
Creating the Internet of Things with JavaScript - Fluent ConfCreating the Internet of Things with JavaScript - Fluent Conf
Creating the Internet of Things with JavaScript - Fluent Conf
Tom Croucher
 
Using Node.js to make HTML5 work for everyone
Using Node.js to make HTML5 work for everyone Using Node.js to make HTML5 work for everyone
Using Node.js to make HTML5 work for everyone
Tom Croucher
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
Tom Croucher
 
Lessons from a coding veteran - Web Directions @Media
Lessons from a coding veteran - Web Directions @MediaLessons from a coding veteran - Web Directions @Media
Lessons from a coding veteran - Web Directions @Media
Tom Croucher
 
Multi-tiered Node Architectures - JSConf 2011
Multi-tiered Node Architectures - JSConf 2011Multi-tiered Node Architectures - JSConf 2011
Multi-tiered Node Architectures - JSConf 2011
Tom Croucher
 
How to stop writing spaghetti code
How to stop writing spaghetti codeHow to stop writing spaghetti code
How to stop writing spaghetti code
Tom Croucher
 
Doing Horrible Things to DNS in the Name of Science - SF Performance Meetup
Doing Horrible Things to DNS in the Name of Science - SF Performance MeetupDoing Horrible Things to DNS in the Name of Science - SF Performance Meetup
Doing Horrible Things to DNS in the Name of Science - SF Performance Meetup
Tom Croucher
 
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
 
How to stop writing spaghetti code - JSConf.eu 2010
How to stop writing spaghetti code - JSConf.eu 2010How to stop writing spaghetti code - JSConf.eu 2010
How to stop writing spaghetti code - JSConf.eu 2010
Tom Croucher
 
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
 
Server Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yetServer Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yet
Tom Croucher
 
Mobile Data: How to avoid the latency trap - SWDC 2010
Mobile Data: How to avoid the latency trap - SWDC 2010Mobile Data: How to avoid the latency trap - SWDC 2010
Mobile Data: How to avoid the latency trap - SWDC 2010
Tom Croucher
 
How to avoid the latency trap and lessons about software design
How to avoid the latency trap and lessons  about software designHow to avoid the latency trap and lessons  about software design
How to avoid the latency trap and lessons about software design
Tom Croucher
 

Mehr von Tom Croucher (20)

Using Node.js to improve the performance of Mobile apps and Mobile web
Using Node.js to improve  the performance of  Mobile apps and Mobile webUsing Node.js to improve  the performance of  Mobile apps and Mobile web
Using Node.js to improve the performance of Mobile apps and Mobile web
 
Creating the Internet of Things with JavaScript - Fluent Conf
Creating the Internet of Things with JavaScript - Fluent ConfCreating the Internet of Things with JavaScript - Fluent Conf
Creating the Internet of Things with JavaScript - Fluent Conf
 
Using Node.js to make HTML5 work for everyone
Using Node.js to make HTML5 work for everyone Using Node.js to make HTML5 work for everyone
Using Node.js to make HTML5 work for everyone
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
Lessons from a coding veteran - Web Directions @Media
Lessons from a coding veteran - Web Directions @MediaLessons from a coding veteran - Web Directions @Media
Lessons from a coding veteran - Web Directions @Media
 
Multi-tiered Node Architectures - JSConf 2011
Multi-tiered Node Architectures - JSConf 2011Multi-tiered Node Architectures - JSConf 2011
Multi-tiered Node Architectures - JSConf 2011
 
How to stop writing spaghetti code
How to stop writing spaghetti codeHow to stop writing spaghetti code
How to stop writing spaghetti code
 
Doing Horrible Things with DNS - Web Directions South
Doing Horrible Things with DNS - Web Directions SouthDoing Horrible Things with DNS - Web Directions South
Doing Horrible Things with DNS - Web Directions South
 
Doing Horrible Things to DNS in the Name of Science - SF Performance Meetup
Doing Horrible Things to DNS in the Name of Science - SF Performance MeetupDoing Horrible Things to DNS in the Name of Science - SF Performance Meetup
Doing Horrible Things to DNS in the Name of Science - SF Performance Meetup
 
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...
 
How to stop writing spaghetti code - JSConf.eu 2010
How to stop writing spaghetti code - JSConf.eu 2010How to stop writing spaghetti code - JSConf.eu 2010
How to stop writing spaghetti code - JSConf.eu 2010
 
Sf perf
Sf perfSf perf
Sf perf
 
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
 
Server Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yetServer Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yet
 
JavaScript Everywhere! Creating a 100% JavaScript web stack
JavaScript Everywhere! Creating a 100% JavaScript web stackJavaScript Everywhere! Creating a 100% JavaScript web stack
JavaScript Everywhere! Creating a 100% JavaScript web stack
 
Mobile Data: How to avoid the latency trap - SWDC 2010
Mobile Data: How to avoid the latency trap - SWDC 2010Mobile Data: How to avoid the latency trap - SWDC 2010
Mobile Data: How to avoid the latency trap - SWDC 2010
 
Let's run JavaScript Everywhere
Let's run JavaScript EverywhereLet's run JavaScript Everywhere
Let's run JavaScript Everywhere
 
Pirate yql
Pirate yqlPirate yql
Pirate yql
 
YQL Tutorial
YQL TutorialYQL Tutorial
YQL Tutorial
 
How to avoid the latency trap and lessons about software design
How to avoid the latency trap and lessons  about software designHow to avoid the latency trap and lessons  about software design
How to avoid the latency trap and lessons about software design
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Using Node.js to Build Great Streaming Services - HTML5 Dev Conf

  • 1. Using Node.js to Build Great Streaming Services @sh1mmer
  • 5. Scalable Server-Side Code with JavaScript Node Up and Running Tom Hughes-Croucher http://ofps.oreilly.com/titles/9781449398583/ http://shop.oreilly.com/product/0636920015956.do @sh1mmer
  • 10. var http = require('http'); var server = http.createServer(); server.listen(8000); server.on('request', function(req,res) { var doodad = new Doodad(); res.writeHead(200,{'Content-Type':'text/doodad'}); res.end(doodad); }); @sh1mmer
  • 12. Knobs Screens Antennas & buttons @sh1mmer
  • 18. var http = require('http'), fs = require('fs'); var server = http.createServer(); server.listen(8000); server.on('request', function(req,res) { var screen = fs.readFileSync('/factory1/screen'); var dial = fs.readFileSync('/factory2/dial'); var doodad = new Doodad(screen, dial); res.writeHead(200,{'Content-Type':'text/doodad'}); res.end(doodad); }); @sh1mmer
  • 19. Improving the factory with streaming @sh1mmer
  • 23. var http = require('http'); var server = http.createServer(); server.listen(8000); server.on('request', function(req,res) { var parts = 0; http.get('factory1/screen/', function(res) { var screen = ""; res.on('data', function(d) { screen += d }); res.on('end', finish); parts++; }; http.get('factory2/dial', function(res) { var dial = "" res.on('data', function(d) { dial += d }); res.on('end', finish); parts++; } function finish() { if(parts == 2) { var doodad = new Doodad(screen, dial); res.writeHead(200,{'Content-Type':'text/doodad'}); res.end(doodad); } } }); @sh1mmer
  • 25. Streams • Readable • Writable • 'data' event • write() • 'end' event • end() • pause() • resume() • 'drain' event • destroy() • destroy() • pipe() • destroySoon() @sh1mmer
  • 26. var stream = require('stream'); var s = new stream.Stream(); //I am an EventEmitter s.readable = true; //now I implement read API s.emit('data', "my data"); s.emit('end'); //I'm done sending data @sh1mmer
  • 27. var stream = require('stream'); var s = new stream.Stream(); //I am an EventEmitter s.writable = true; //now I implement write API s.data = ""; s.write = function(d) { s.data += d; }; s.end = function() { if(s.data) { console.log(s.data) } }; s.destroy = function() { s.writable = false; } @sh1mmer
  • 28. The too many parts problem and why phone calls don't work @sh1mmer
  • 30. nextTick Event Loop Fail nextTick Run stuff TCP Conn node.cc FS Read add-ons v8 TCP Conn Timeout libuv TCP Interval Conn libev iocp FS Timeout Read FS Read
  • 32. nextTick Event Loop Fail nextTick stream.pause() TCP Conn node.cc FS Read add-ons v8 TCP Conn Timeout libuv TCP Interval Conn libev iocp FS Timeout Read FS Read
  • 33. Managing Backpressure • Manage Buffer sizes • Use pause() / resume() to control back pressure • Assume that 'data' event may happen after pause • Remember node buffer -> kernel buffer @sh1mmer
  • 34. //manage Node's write Buffers if(socket.bufferSize > maxSafe) { writeStream.pause(); } //Manage RS read stream Buffers fs.createReadStream('./path/to/file', { flags: 'r', encoding: null, fd: null, mode: 0666, bufferSize: 64 * 1024 }); @sh1mmer
  • 36. New Streams TBD • Writable streams • Same • Readable (https://github.com/isaacs/readable-stream) • configurable stream buffer waterline • 'readable' event • read(len) -> returns data • Pipe • Subscribers must implement readable stream • No more direct access with Pipe
  • 40. var fs = require('fs'); var rs = fs.createReadStream('/my/file/path'); rs.on('data', function(d) { console.log(d); }); @sh1mmer
  • 42. var fs = require('fs'); var rs = fs.createReadStream('/my/file/path'); rs.pipe(process.stdout); @sh1mmer
  • 44. var bot1 = new chatterBot(); var bot2 = new chatterBot(); bot1.pipe(bot2).pipe(bot1); @sh1mmer
  • 47. {"total_rows":129,"offset":0,"rows":[ { "id":"change1_0.6995461115147918" , "key":"change1_0.6995461115147918" , "value":{"rev":"1-e240bae28c7bb3667f02760f6398d508"} , "doc":{ "_id": "change1_0.6995461115147918" , "_rev": "1-e240bae28c7bb3667f02760f6398d508","hello":1} }, { "id":"change2_0.6995461115147918" , "key":"change2_0.6995461115147918" , "value":{"rev":"1-13677d36b98c0c075145bb8975105153"} , "doc":{ "_id":"change2_0.6995461115147918" , "_rev":"1-13677d36b98c0c075145bb8975105153" , "hello":2 } }, ]} @sh1mmer
  • 48. var stream = JSONStream.parse(['rows', true, 'doc']) //rows, ANYTHING, doc stream.on('data', function(data) { console.log('received:', data); }); stream.on('root', function(root, count) { if (!count) { console.log('no matches found:', root); } }); @sh1mmer