SlideShare a Scribd company logo
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
Ad

Recommended

Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Tom Croucher
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxy
Ismael Celis
 
Nodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
Node.js - Best practices
Node.js - Best practices
Felix Geisendörfer
 
Node.js - A Quick Tour
Node.js - A Quick Tour
Felix Geisendörfer
 
Ruby HTTP clients comparison
Ruby HTTP clients comparison
Hiroshi Nakamura
 
Beyond Phoenix
Beyond Phoenix
Gabriele Lana
 
Integrating icinga2 and the HashiCorp suite
Integrating icinga2 and the HashiCorp suite
Bram Vogelaar
 
Puppet and the HashiStack
Puppet and the HashiStack
Bram Vogelaar
 
Writing robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Devinsampa nginx-scripting
Devinsampa nginx-scripting
Tony Fabeen
 
Lua tech talk
Lua tech talk
Locaweb
 
Ubic
Ubic
Vyacheslav Matyukhin
 
Node js presentation
Node js presentation
martincabrera
 
Introduction to Nodejs
Introduction to Nodejs
Gabriele Lana
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stack
Bram Vogelaar
 
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 scale
Tom Croucher
 
Securing Prometheus exporters using HashiCorp Vault
Securing Prometheus exporters using HashiCorp Vault
Bram Vogelaar
 
Testing your infrastructure with litmus
Testing your infrastructure with litmus
Bram Vogelaar
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stack
Bram Vogelaar
 
Nginx-lua
Nginx-lua
Дэв Тим Афс
 
Creating Reusable Puppet Profiles
Creating Reusable Puppet Profiles
Bram Vogelaar
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Masahiro Nagano
 
Static Typing in Vault
Static Typing in Vault
GlynnForrest
 
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 another
Michele Orselli
 
Observability with Consul Connect
Observability with Consul Connect
Bram Vogelaar
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
Felix Geisendörfer
 
Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02
Sunny Gupta
 
About Node.js
About Node.js
Artemisa Yescas Engler
 

More Related Content

What's hot (20)

Puppet and the HashiStack
Puppet and the HashiStack
Bram Vogelaar
 
Writing robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Devinsampa nginx-scripting
Devinsampa nginx-scripting
Tony Fabeen
 
Lua tech talk
Lua tech talk
Locaweb
 
Ubic
Ubic
Vyacheslav Matyukhin
 
Node js presentation
Node js presentation
martincabrera
 
Introduction to Nodejs
Introduction to Nodejs
Gabriele Lana
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stack
Bram Vogelaar
 
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 scale
Tom Croucher
 
Securing Prometheus exporters using HashiCorp Vault
Securing Prometheus exporters using HashiCorp Vault
Bram Vogelaar
 
Testing your infrastructure with litmus
Testing your infrastructure with litmus
Bram Vogelaar
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stack
Bram Vogelaar
 
Nginx-lua
Nginx-lua
Дэв Тим Афс
 
Creating Reusable Puppet Profiles
Creating Reusable Puppet Profiles
Bram Vogelaar
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Masahiro Nagano
 
Static Typing in Vault
Static Typing in Vault
GlynnForrest
 
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 another
Michele Orselli
 
Observability with Consul Connect
Observability with Consul Connect
Bram Vogelaar
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
Felix Geisendörfer
 
Puppet and the HashiStack
Puppet and the HashiStack
Bram Vogelaar
 
Writing robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Devinsampa nginx-scripting
Devinsampa nginx-scripting
Tony Fabeen
 
Lua tech talk
Lua tech talk
Locaweb
 
Node js presentation
Node js presentation
martincabrera
 
Introduction to Nodejs
Introduction to Nodejs
Gabriele Lana
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stack
Bram Vogelaar
 
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 scale
Tom Croucher
 
Securing Prometheus exporters using HashiCorp Vault
Securing Prometheus exporters using HashiCorp Vault
Bram Vogelaar
 
Testing your infrastructure with litmus
Testing your infrastructure with litmus
Bram Vogelaar
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stack
Bram Vogelaar
 
Creating Reusable Puppet Profiles
Creating Reusable Puppet Profiles
Bram Vogelaar
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Masahiro Nagano
 
Static Typing in Vault
Static Typing in Vault
GlynnForrest
 
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 another
Michele Orselli
 
Observability with Consul Connect
Observability with Consul Connect
Bram Vogelaar
 

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

Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02
Sunny Gupta
 
About Node.js
About Node.js
Artemisa Yescas Engler
 
Node.js - As a networking tool
Node.js - As a networking tool
Felix Geisendörfer
 
Node js lecture
Node js lecture
Darryl Sherman
 
Real Time Web with Node
Real Time Web with Node
Tim Caswell
 
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
 
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
 
Introduction to Node.js
Introduction to Node.js
Richard Lee
 
Real-Time with Flowdock
Real-Time with Flowdock
Flowdock
 
Functional Programming with Streams in node.js
Functional Programming with Streams in node.js
Adam Crabtree
 
Building and Scaling Node.js Applications
Building and Scaling Node.js Applications
Ohad Kravchick
 
Comet with node.js and V8
Comet with node.js and V8
amix3k
 
Into to Node.js: Building Fast, Scaleable Network Applications
Into to Node.js: Building Fast, Scaleable Network Applications
Flatiron School
 
Server side JavaScript: going all the way
Server side JavaScript: going all the way
Oleg Podsechin
 
Node.js web-based Example :Run a local server in order to start using node.js...
Node.js web-based Example :Run a local server in order to start using node.js...
Kongu Engineering College, Perundurai, Erode
 
Node Powered Mobile
Node Powered Mobile
Tim Caswell
 
Presentation.pptx
Presentation.pptx
Naor Tedgi
 
Node.js File system & Streams
Node.js File system & Streams
Eyal Vardi
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
Felix Geisendörfer
 
Node.js - A practical introduction (v2)
Node.js - A practical introduction (v2)
Felix Geisendörfer
 
Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02
Sunny Gupta
 
Real Time Web with Node
Real Time Web with Node
Tim Caswell
 
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
 
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
 
Introduction to Node.js
Introduction to Node.js
Richard Lee
 
Real-Time with Flowdock
Real-Time with Flowdock
Flowdock
 
Functional Programming with Streams in node.js
Functional Programming with Streams in node.js
Adam Crabtree
 
Building and Scaling Node.js Applications
Building and Scaling Node.js Applications
Ohad Kravchick
 
Comet with node.js and V8
Comet with node.js and V8
amix3k
 
Into to Node.js: Building Fast, Scaleable Network Applications
Into to Node.js: Building Fast, Scaleable Network Applications
Flatiron School
 
Server side JavaScript: going all the way
Server side JavaScript: going all the way
Oleg Podsechin
 
Node Powered Mobile
Node Powered Mobile
Tim Caswell
 
Presentation.pptx
Presentation.pptx
Naor Tedgi
 
Node.js File system & Streams
Node.js File system & Streams
Eyal Vardi
 
Node.js - A practical introduction (v2)
Node.js - A practical introduction (v2)
Felix Geisendörfer
 
Ad

More from 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 web
Tom Croucher
 
Creating 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
Tom Croucher
 
OSCON 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 @Media
Tom Croucher
 
Multi-tiered Node Architectures - JSConf 2011
Multi-tiered Node Architectures - JSConf 2011
Tom Croucher
 
How to stop writing spaghetti code
How to stop writing spaghetti code
Tom Croucher
 
Doing Horrible Things with DNS - Web Directions South
Doing Horrible Things with DNS - Web Directions South
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 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...
Tom Croucher
 
How to stop writing spaghetti code - JSConf.eu 2010
How to stop writing spaghetti code - JSConf.eu 2010
Tom Croucher
 
Sf perf
Sf perf
Tom Croucher
 
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 yet
Tom Croucher
 
JavaScript Everywhere! Creating a 100% JavaScript web stack
JavaScript Everywhere! Creating a 100% JavaScript web stack
Tom Croucher
 
Mobile Data: How to avoid the latency trap - SWDC 2010
Mobile Data: How to avoid the latency trap - SWDC 2010
Tom Croucher
 
Let's run JavaScript Everywhere
Let's run JavaScript Everywhere
Tom Croucher
 
Pirate yql
Pirate yql
Tom Croucher
 
YQL Tutorial
YQL Tutorial
Tom Croucher
 
How to avoid the latency trap and lessons about software design
How to avoid the latency trap and lessons about software design
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 web
Tom Croucher
 
Creating 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
Tom Croucher
 
OSCON 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 @Media
Tom Croucher
 
Multi-tiered Node Architectures - JSConf 2011
Multi-tiered Node Architectures - JSConf 2011
Tom Croucher
 
How to stop writing spaghetti code
How to stop writing spaghetti code
Tom Croucher
 
Doing Horrible Things with DNS - Web Directions South
Doing Horrible Things with DNS - Web Directions South
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 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...
Tom Croucher
 
How 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
Tom Croucher
 
Server Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yet
Tom Croucher
 
JavaScript Everywhere! Creating a 100% JavaScript web stack
JavaScript Everywhere! Creating a 100% JavaScript web stack
Tom Croucher
 
Mobile Data: How to avoid the latency trap - SWDC 2010
Mobile Data: How to avoid the latency trap - SWDC 2010
Tom Croucher
 
Let's run JavaScript Everywhere
Let's run JavaScript Everywhere
Tom Croucher
 
How to avoid the latency trap and lessons about software design
How to avoid the latency trap and lessons about software design
Tom Croucher
 
Ad

Recently uploaded (20)

The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 

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