SlideShare une entreprise Scribd logo
1  sur  95
Node.js
Grenoble JS - 2011/10/19
Who am I?
Who am I?
Jeff Mesnil
Who am I?
Jeff Mesnil
Software Developer at Bestofmedia
Who am I?
Jeff Mesnil
Software Developer at Bestofmedia
http://jmesnil.net/
Who am I?
Jeff Mesnil
Software Developer at Bestofmedia
http://jmesnil.net/
jmesnil@gmail.com
Who am I?
Jeff Mesnil
Software Developer at Bestofmedia
http://jmesnil.net/
jmesnil@gmail.com
twitter: @jmesnil
Previously
Previously
Red Hat / JBoss
Previously
Red Hat / JBoss
HornetQ messaging server
Previously
Red Hat / JBoss
HornetQ messaging server
Written in Java
Previously
Red Hat / JBoss
HornetQ messaging server
Written in Java
Concurrency
Previously
Red Hat / JBoss
HornetQ messaging server
Written in Java
Concurrency
Thousands of producers/consumers
Previously
Red Hat / JBoss
HornetQ messaging server
Written in Java
Concurrency
Thousands of producers/consumers
Hard to write correct multithreaded code
Previously
Red Hat / JBoss
HornetQ messaging server
Written in Java
Concurrency
Thousands of producers/consumers
Hard to write correct multithreaded code
Impossible to prove it is correct
«I've learned that you can never believe that a
 program using shared-memory concurrency (which
  is what threading uses) is working correctly - You
 can only discover that it's wrong, but you can never
                  prove that it's right.
                           ...
  you can never let yourself become too confident
 about your programming abilities when it comes to
     shared-memory concurrency. I would not be
surprised if, sometime in the future, someone comes
    up with a proof to show that shared-memory
     concurrency programming is only possible in
              theory, but not in practice.»

           -- Bruce Eckel, Thinking in Java
Multithreading is Hard
 Let’s Go Shopping!
• Erlang, Scala
• Erlang, Scala
 • Actor Model
• Erlang, Scala
 • Actor Model
• Clojure
• Erlang, Scala
 • Actor Model
• Clojure
 • Software Transaction Model (STM)
node.js ?
http://nodejs.org/
Evented I/O for V8 JavaScript
V8
V8
From Google
V8
From Google
Open Source JavaScript engine
V8
From Google
Open Source JavaScript engine
Used in Google Chrome
V8
From Google
Open Source JavaScript engine
Used in Google Chrome
Standalone or embedded into any C++
application
V8
From Google
Open Source JavaScript engine
Used in Google Chrome
Standalone or embedded into any C++
application
Fast (for a JavaScript Engine...)
JavaScript
JavaScript

Node applications are written in JavaScript
(or CoffeeScript...)
JavaScript

Node applications are written in JavaScript
(or CoffeeScript...)
Functions are 1st-class citizen
JavaScript

Node applications are written in JavaScript
(or CoffeeScript...)
Functions are 1st-class citizen
Well suited for event-driven applications
JavaScript

Node applications are written in JavaScript
(or CoffeeScript...)
Functions are 1st-class citizen
Well suited for event-driven applications
No standard I/O library...
Event Loop

while (true)
  ready_channels = select(io_channels)
  for channel in ready_channels
     performIO(channel)
Single thread (on a single core)
Single thread (on a single core)

Register interested I/O events and a callback
Single thread (on a single core)

Register interested I/O events and a callback

Called back when the event occurs
Asynchronous I/O
Read a File
var fs = require('fs');



fs.readFile('/usr/share/dict/words', 'utf8', function (err, data) {

 if (err) throw err;

 console.log(data);

});
TCP Echo Server
var net = require('net');


var server = net.createServer(function (socket) {
  socket.setEncoding('utf-8');
  socket.write("Echo serverrn");
  socket.on('data', function(data) {
    console.log(data);
    socket.write(data.toUpperCase());
  });
});


server.listen(1337, "127.0.0.1");
$ telnet localhost 1337

Echo server



hello, World!!

HELLO, WORLD!!
node.js is good for
node.js is good for
• I/O-bound Code
node.js is good for
• I/O-bound Code
 • DB, Web Services connectivity
node.js is good for
• I/O-bound Code
 • DB, Web Services connectivity
 • Data Aggregation
node.js is good for
• I/O-bound Code
 • DB, Web Services connectivity
 • Data Aggregation
 • Non-blocking communication
node.js is good for
• I/O-bound Code
 • DB, Web Services connectivity
 • Data Aggregation
 • Non-blocking communication
• Do a bit of I/O and let the others play
node.js is not good for
node.js is not good for

• CPU-bound applications
node.js is not good for

• CPU-bound applications
 • Computation (Fibonacci...)
node.js is not good for

• CPU-bound applications
 • Computation (Fibonacci...)
 • Machine-Learning algorithm
node.js is not good for

• CPU-bound applications
 • Computation (Fibonacci...)
 • Machine-Learning algorithm
 • ...
node.js is not good for

• CPU-bound applications
 • Computation (Fibonacci...)
 • Machine-Learning algorithm
 • ...
• Everybody has to wait its turn
Workaround is to start new processes via
child_process.fork()
Workaround is to start new processes via
child_process.fork()

Data communication?
Workaround is to start new processes via
child_process.fork()

Data communication?

Load?
Workaround is to start new processes via
child_process.fork()

Data communication?

Load?

Web Workers API (or Isolates à la Dart)?
Google Scraper
Google Scraper
• For a query
Google Scraper
• For a query
 • Connect to Google and fetch a result
    page
Google Scraper
• For a query
 • Connect to Google and fetch a result
    page
   • Use JQuery to find all the anchors for
      the results
Google Scraper
• For a query
 • Connect to Google and fetch a result
    page
   • Use JQuery to find all the anchors for
      the results
     • Print their URLs
$ node scraper.js "node javascript"


http://nodejs.org/
http://www.theregister.co.uk/2011/03/01/
the_rise_and_rise_of_node_dot_js/
http://www.howtocreate.co.uk/tutorials/javascript/
dombasics
http://net.tutsplus.com/tutorials/javascript-ajax/learning-
serverside-javascript-with-node-js/
...
var request = require('request'),

    jsdom = require('jsdom');

var args = process.argv.slice(2);

if (args.length != 1) {

  console.log('Usage: node scraper.js <query sentence>');

  process.exit(1);

}

var query = escape(args[0]);

var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google'

request({ uri: url }, function (error, response, body) {

  if (error) {

    console.log('Error when contacting google.com: ' + error);

    process.exit(2);

  }

  if (response && response.statusCode !== 200) {

    console.log('Did not get a correct response from Google: ' + response);

    process.exit(2);

  }

  jsdom.env({

    html: body,

    scripts: [

      'http://code.jquery.com/jquery-1.5.min.js'

    ]

  }, function (err, window) {

    var $ = window.jQuery;

    $('a.l').each(function() {

      console.log($(this).attr('href'));

    });

  });
var request = require('request'),

    jsdom = require('jsdom');

var args = process.argv.slice(2);
                                                                                                        ica tion
if (args.length != 1) {
                                                                                                 a ppl
  console.log('Usage: node scraper.js <query sentence>');
                                                                                         p the
                                                                                     u
  process.exit(1);                                                              set
}

var query = escape(args[0]);

var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google'

request({ uri: url }, function (error, response, body) {

  if (error) {

    console.log('Error when contacting google.com: ' + error);

    process.exit(2);

  }

  if (response && response.statusCode !== 200) {

    console.log('Did not get a correct response from Google: ' + response);

    process.exit(2);

  }

  jsdom.env({

    html: body,

    scripts: [

      'http://code.jquery.com/jquery-1.5.min.js'

    ]

  }, function (err, window) {

    var $ = window.jQuery;

    $('a.l').each(function() {

      console.log($(this).attr('href'));

    });

  });
var request = require('request'),

    jsdom = require('jsdom');

var args = process.argv.slice(2);
                                                                                                        ica tion
if (args.length != 1) {
                                                                                                 a ppl
  console.log('Usage: node scraper.js <query sentence>');
                                                                                         p the
                                                                                     u
  process.exit(1);                                                              set
}

var query = escape(args[0]);

var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google'

request({ uri: url }, function (error, response, body) {

  if (error) {

    console.log('Error when contacting google.com: ' + error);

    process.exit(2);

  }

  if (response && response.statusCode !== 200) {

    console.log('Did not get a correct response from Google: ' + response);
                                                                                                         es ults
    process.exit(2);
                                                                                               og le r
  }
                                                                                     h Go
  jsdom.env({                                                                    fetc
    html: body,

    scripts: [

      'http://code.jquery.com/jquery-1.5.min.js'

    ]

  }, function (err, window) {

    var $ = window.jQuery;

    $('a.l').each(function() {

      console.log($(this).attr('href'));

    });

  });
var request = require('request'),

    jsdom = require('jsdom');

var args = process.argv.slice(2);
                                                                                                        ica tion
if (args.length != 1) {
                                                                                                  a ppl
  console.log('Usage: node scraper.js <query sentence>');
                                                                                          p the
                                                                                      u
  process.exit(1);                                                                 set
}

var query = escape(args[0]);

var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google'

request({ uri: url }, function (error, response, body) {

  if (error) {

    console.log('Error when contacting google.com: ' + error);

    process.exit(2);

  }

  if (response && response.statusCode !== 200) {

    console.log('Did not get a correct response from Google: ' + response);
                                                                                                          es ults
    process.exit(2);
                                                                                               og le r
  }
                                                                                       h Go
  jsdom.env({                                                                      fetc
                                                                                                                        y
    html: body,
                                                                                                                  JQ uer
                                                                                                              h
                                                                                                      wit
    scripts: [
                                                                                                   rs
                                                                                             cho
      'http://code.jquery.com/jquery-1.5.min.js'
                                                                                          an
                                                                                  the
    ]

  }, function (err, window) {
                                                                              find
    var $ = window.jQuery;

    $('a.l').each(function() {

      console.log($(this).attr('href'));

    });

  });
var request = require('request'),

    jsdom = require('jsdom');

var args = process.argv.slice(2);
                                                                                                        ica tion
if (args.length != 1) {
                                                                                                  a ppl
  console.log('Usage: node scraper.js <query sentence>');
                                                                                          p the
                                                                                      u
  process.exit(1);                                                                 set
}

var query = escape(args[0]);

var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google'

request({ uri: url }, function (error, response, body) {

  if (error) {

    console.log('Error when contacting google.com: ' + error);

    process.exit(2);

  }

  if (response && response.statusCode !== 200) {

    console.log('Did not get a correct response from Google: ' + response);
                                                                                                          es ults
    process.exit(2);
                                                                                               og le r
  }
                                                                                       h Go
  jsdom.env({                                                                      fetc
                                                                                                                        y
    html: body,
                                                                                                                  JQ uer
                                                                                                              h
                                                                                                      wit
    scripts: [
                                                                                                   rs
                                                                                             cho
      'http://code.jquery.com/jquery-1.5.min.js'
                                                                                          an                  s
                                                                                  the                 URL
    ]

  }, function (err, window) {
                                                                              find                 eir
                                                                                          t th
                                                                                     prin
    var $ = window.jQuery;

    $('a.l').each(function() {

      console.log($(this).attr('href'));

    });

  });
// Node.js modules required to run the scraper
// use npm to install them:
// $ `curl http://npmjs.org/install.sh | sh`


var request = require('request'),
    jsdom = require('jsdom');
// Node.js modules required to run the scraper
// use npm to install them:
// $ `curl http://npmjs.org/install.sh | sh`
                                                                ap per
                                                            wr
                                                    u   est
                                               P req
var request = require('request'),          HTT

    jsdom = require('jsdom');
// Node.js modules required to run the scraper
// use npm to install them:
// $ `curl http://npmjs.org/install.sh | sh`
                                                                     per
                                                               w rap
                                                         u est         ver
                                                     req           Ser
                                              TTP             the
var request = require('request'),           H           yo
                                                            n
                                                  Q uer
                                           u se j
    jsdom = require('jsdom');
// remove node and the file name from the arguments list

var args = process.argv.slice(2);

if (args.length != 1) {

  console.log('Usage: node scraper.js <query sentence>');

  process.exit(1);

}

// the query to search on Google

var query = escape(args[0]);

// Google URL that will be request and whose content will be scraped

var url = 'http://www.google.com/search?q=' + query;
request({ uri: url }, function (error, response, body) {

  // nothing to do if we get an error from Google

  if (error) {

    console.log('Error when contacting google.com: ' + error);

    process.exit(2);

  }

  // idem if the response is not OK

  if (response && response.statusCode !== 200) {

    console.log('Did not get a correct response from Google: ' + response);

    process.exit(2);

  }



  ...

});
po nse
request({ uri: url }, function (error, response, body) {                             a res
                                                                             e get
                                                                            w
  // nothing to do if we get an error from Google
                                                                    w hen
                                                            b ack
  if (error) {                                         call
    console.log('Error when contacting google.com: ' + error);

    process.exit(2);

  }

  // idem if the response is not OK

  if (response && response.statusCode !== 200) {

    console.log('Did not get a correct response from Google: ' + response);

    process.exit(2);

  }



  ...

});
po nse
request({ uri: url }, function (error, response, body) {                              a res
                                                                              e get
                                                                             w
  // nothing to do if we get an error from Google
                                                                     w hen
                                                             b ack
  if (error) {                                          call
    console.log('Error when contacting google.com: ' + error);

    process.exit(2);

  }

  // idem if the response is not OK

  if (response && response.statusCode !== 200) {

    console.log('Did not get a correct response from Google: ' + response);

    process.exit(2);

  }                                             b ody
                                       in the
                              li nks
                        the
                    find
             et’s
  ...
           l
});
// use jsdom and jQuery to manipulate the DOM corresponding to the response's body

  jsdom.env({

    html: body,

    scripts: [

       // jQuery is loaded directly from its web site.

       // We could instead cache it locally for efficiency

      'http://code.jquery.com/jquery-1.5.min.js'

    ]

  }, function (err, window) {

   ...

  });
// use jsdom and jQuery to manipulate the DOM corresponding to the response's body
                                                                            y
  jsdom.env({
                                                                      jQ uer
                                                                 up
                                                         o   set
    html: body,
                                                    do mt
                                                  s
    scripts: [                              use j

       // jQuery is loaded directly from its web site.

       // We could instead cache it locally for efficiency

      'http://code.jquery.com/jquery-1.5.min.js'

    ]

  }, function (err, window) {

   ...

  });
// use jsdom and jQuery to manipulate the DOM corresponding to the response's body
                                                                                 y
  jsdom.env({
                                                                           jQ uer
                                                                      up
                                                             o    set
    html: body,
                                                        do mt
                                                     s
    scripts: [                                  use j

       // jQuery is loaded directly from its web site.

       // We could instead cache it locally for efficiency

      'http://code.jquery.com/jquery-1.5.min.js'

    ]

  }, function (err, window) {
                                                         yc ode
                                                 uer
   ...                                   iliar jQ
                                       m
                                oe s fa
  });
                      he re g
// alias jQuery object to the more familiar '$'

var $ = window.jQuery;  

// print the URLS of the results listed by Google...

    $('a.l').each(function() {

      console.log($(this).attr('href'));

    });
Russian Dolls
Spaghetti Code?
No Silver Bullet...
Another arrow in your quiver!
«Ruby, Javascript, and Clojure are all general-purpose
 languages, but they each excel at certain use cases. Ruby's
 highly dynamic nature and emphasis on beauty makes it a
  natural fit for user-facing web apps. Node.js's evented
 concurrency makes it a great fit for the realtime
web. Clojure covers a new use case on the Heroku platform:
   components which demand correctness, performance,
composability; and optionally, access to the Java ecosystem.»

        -- http://blog.heroku.com/archives/2011/7/5/
                      clojure_on_heroku
https://github.com/jmesnil/node-samples

https://groups.google.com/forum/?hl=fr#!
forum/grenoblejs
Questions?
Thanks!

Contenu connexe

En vedette

Boas Praticas de Testes, Bad Smell e Outros Macetes
Boas Praticas de Testes, Bad Smell e Outros MacetesBoas Praticas de Testes, Bad Smell e Outros Macetes
Boas Praticas de Testes, Bad Smell e Outros MacetesIsmael
 
ASAS FOTOGRAFI
ASAS FOTOGRAFIASAS FOTOGRAFI
ASAS FOTOGRAFIRAJA NADIA
 
8 passos para mudança de John Kotter
8 passos para mudança de John Kotter8 passos para mudança de John Kotter
8 passos para mudança de John KotterIsmael
 
Kerja berpasukan dan lain lain
Kerja berpasukan dan lain lainKerja berpasukan dan lain lain
Kerja berpasukan dan lain lainAqmar Ayub
 

En vedette (7)

illness prevention
illness preventionillness prevention
illness prevention
 
Mphone
MphoneMphone
Mphone
 
Boas Praticas de Testes, Bad Smell e Outros Macetes
Boas Praticas de Testes, Bad Smell e Outros MacetesBoas Praticas de Testes, Bad Smell e Outros Macetes
Boas Praticas de Testes, Bad Smell e Outros Macetes
 
Umashankar Adha
Umashankar AdhaUmashankar Adha
Umashankar Adha
 
ASAS FOTOGRAFI
ASAS FOTOGRAFIASAS FOTOGRAFI
ASAS FOTOGRAFI
 
8 passos para mudança de John Kotter
8 passos para mudança de John Kotter8 passos para mudança de John Kotter
8 passos para mudança de John Kotter
 
Kerja berpasukan dan lain lain
Kerja berpasukan dan lain lainKerja berpasukan dan lain lain
Kerja berpasukan dan lain lain
 

Dernier

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
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 FresherRemote DBA Services
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
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 Takeoffsammart93
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 

Dernier (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Node.js Dojo

  • 1.
  • 4. Who am I? Jeff Mesnil
  • 5. Who am I? Jeff Mesnil Software Developer at Bestofmedia
  • 6. Who am I? Jeff Mesnil Software Developer at Bestofmedia http://jmesnil.net/
  • 7. Who am I? Jeff Mesnil Software Developer at Bestofmedia http://jmesnil.net/ jmesnil@gmail.com
  • 8. Who am I? Jeff Mesnil Software Developer at Bestofmedia http://jmesnil.net/ jmesnil@gmail.com twitter: @jmesnil
  • 11. Previously Red Hat / JBoss HornetQ messaging server
  • 12. Previously Red Hat / JBoss HornetQ messaging server Written in Java
  • 13. Previously Red Hat / JBoss HornetQ messaging server Written in Java Concurrency
  • 14. Previously Red Hat / JBoss HornetQ messaging server Written in Java Concurrency Thousands of producers/consumers
  • 15. Previously Red Hat / JBoss HornetQ messaging server Written in Java Concurrency Thousands of producers/consumers Hard to write correct multithreaded code
  • 16. Previously Red Hat / JBoss HornetQ messaging server Written in Java Concurrency Thousands of producers/consumers Hard to write correct multithreaded code Impossible to prove it is correct
  • 17.
  • 18. «I've learned that you can never believe that a program using shared-memory concurrency (which is what threading uses) is working correctly - You can only discover that it's wrong, but you can never prove that it's right. ... you can never let yourself become too confident about your programming abilities when it comes to shared-memory concurrency. I would not be surprised if, sometime in the future, someone comes up with a proof to show that shared-memory concurrency programming is only possible in theory, but not in practice.» -- Bruce Eckel, Thinking in Java
  • 19. Multithreading is Hard Let’s Go Shopping!
  • 20.
  • 22. • Erlang, Scala • Actor Model
  • 23. • Erlang, Scala • Actor Model • Clojure
  • 24. • Erlang, Scala • Actor Model • Clojure • Software Transaction Model (STM)
  • 27. Evented I/O for V8 JavaScript
  • 28. V8
  • 30. V8 From Google Open Source JavaScript engine
  • 31. V8 From Google Open Source JavaScript engine Used in Google Chrome
  • 32. V8 From Google Open Source JavaScript engine Used in Google Chrome Standalone or embedded into any C++ application
  • 33. V8 From Google Open Source JavaScript engine Used in Google Chrome Standalone or embedded into any C++ application Fast (for a JavaScript Engine...)
  • 35. JavaScript Node applications are written in JavaScript (or CoffeeScript...)
  • 36. JavaScript Node applications are written in JavaScript (or CoffeeScript...) Functions are 1st-class citizen
  • 37. JavaScript Node applications are written in JavaScript (or CoffeeScript...) Functions are 1st-class citizen Well suited for event-driven applications
  • 38. JavaScript Node applications are written in JavaScript (or CoffeeScript...) Functions are 1st-class citizen Well suited for event-driven applications No standard I/O library...
  • 39. Event Loop while (true) ready_channels = select(io_channels) for channel in ready_channels performIO(channel)
  • 40.
  • 41. Single thread (on a single core)
  • 42. Single thread (on a single core) Register interested I/O events and a callback
  • 43. Single thread (on a single core) Register interested I/O events and a callback Called back when the event occurs
  • 45. Read a File var fs = require('fs'); fs.readFile('/usr/share/dict/words', 'utf8', function (err, data) { if (err) throw err; console.log(data); });
  • 46. TCP Echo Server var net = require('net'); var server = net.createServer(function (socket) {   socket.setEncoding('utf-8');   socket.write("Echo serverrn");   socket.on('data', function(data) {     console.log(data);     socket.write(data.toUpperCase());   }); }); server.listen(1337, "127.0.0.1");
  • 47. $ telnet localhost 1337 Echo server hello, World!! HELLO, WORLD!!
  • 49. node.js is good for • I/O-bound Code
  • 50. node.js is good for • I/O-bound Code • DB, Web Services connectivity
  • 51. node.js is good for • I/O-bound Code • DB, Web Services connectivity • Data Aggregation
  • 52. node.js is good for • I/O-bound Code • DB, Web Services connectivity • Data Aggregation • Non-blocking communication
  • 53. node.js is good for • I/O-bound Code • DB, Web Services connectivity • Data Aggregation • Non-blocking communication • Do a bit of I/O and let the others play
  • 54. node.js is not good for
  • 55. node.js is not good for • CPU-bound applications
  • 56. node.js is not good for • CPU-bound applications • Computation (Fibonacci...)
  • 57. node.js is not good for • CPU-bound applications • Computation (Fibonacci...) • Machine-Learning algorithm
  • 58. node.js is not good for • CPU-bound applications • Computation (Fibonacci...) • Machine-Learning algorithm • ...
  • 59. node.js is not good for • CPU-bound applications • Computation (Fibonacci...) • Machine-Learning algorithm • ... • Everybody has to wait its turn
  • 60.
  • 61. Workaround is to start new processes via child_process.fork()
  • 62. Workaround is to start new processes via child_process.fork() Data communication?
  • 63. Workaround is to start new processes via child_process.fork() Data communication? Load?
  • 64. Workaround is to start new processes via child_process.fork() Data communication? Load? Web Workers API (or Isolates à la Dart)?
  • 67. Google Scraper • For a query • Connect to Google and fetch a result page
  • 68. Google Scraper • For a query • Connect to Google and fetch a result page • Use JQuery to find all the anchors for the results
  • 69. Google Scraper • For a query • Connect to Google and fetch a result page • Use JQuery to find all the anchors for the results • Print their URLs
  • 70. $ node scraper.js "node javascript" http://nodejs.org/ http://www.theregister.co.uk/2011/03/01/ the_rise_and_rise_of_node_dot_js/ http://www.howtocreate.co.uk/tutorials/javascript/ dombasics http://net.tutsplus.com/tutorials/javascript-ajax/learning- serverside-javascript-with-node-js/ ...
  • 71. var request = require('request'),     jsdom = require('jsdom'); var args = process.argv.slice(2); if (args.length != 1) {   console.log('Usage: node scraper.js <query sentence>');   process.exit(1); } var query = escape(args[0]); var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google' request({ uri: url }, function (error, response, body) {   if (error) {     console.log('Error when contacting google.com: ' + error);     process.exit(2);   }   if (response && response.statusCode !== 200) {     console.log('Did not get a correct response from Google: ' + response);     process.exit(2);   }   jsdom.env({     html: body,     scripts: [       'http://code.jquery.com/jquery-1.5.min.js'     ]   }, function (err, window) {     var $ = window.jQuery;     $('a.l').each(function() {       console.log($(this).attr('href'));     });   });
  • 72. var request = require('request'),     jsdom = require('jsdom'); var args = process.argv.slice(2); ica tion if (args.length != 1) { a ppl   console.log('Usage: node scraper.js <query sentence>'); p the u   process.exit(1); set } var query = escape(args[0]); var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google' request({ uri: url }, function (error, response, body) {   if (error) {     console.log('Error when contacting google.com: ' + error);     process.exit(2);   }   if (response && response.statusCode !== 200) {     console.log('Did not get a correct response from Google: ' + response);     process.exit(2);   }   jsdom.env({     html: body,     scripts: [       'http://code.jquery.com/jquery-1.5.min.js'     ]   }, function (err, window) {     var $ = window.jQuery;     $('a.l').each(function() {       console.log($(this).attr('href'));     });   });
  • 73. var request = require('request'),     jsdom = require('jsdom'); var args = process.argv.slice(2); ica tion if (args.length != 1) { a ppl   console.log('Usage: node scraper.js <query sentence>'); p the u   process.exit(1); set } var query = escape(args[0]); var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google' request({ uri: url }, function (error, response, body) {   if (error) {     console.log('Error when contacting google.com: ' + error);     process.exit(2);   }   if (response && response.statusCode !== 200) {     console.log('Did not get a correct response from Google: ' + response); es ults     process.exit(2); og le r   } h Go   jsdom.env({ fetc     html: body,     scripts: [       'http://code.jquery.com/jquery-1.5.min.js'     ]   }, function (err, window) {     var $ = window.jQuery;     $('a.l').each(function() {       console.log($(this).attr('href'));     });   });
  • 74. var request = require('request'),     jsdom = require('jsdom'); var args = process.argv.slice(2); ica tion if (args.length != 1) { a ppl   console.log('Usage: node scraper.js <query sentence>'); p the u   process.exit(1); set } var query = escape(args[0]); var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google' request({ uri: url }, function (error, response, body) {   if (error) {     console.log('Error when contacting google.com: ' + error);     process.exit(2);   }   if (response && response.statusCode !== 200) {     console.log('Did not get a correct response from Google: ' + response); es ults     process.exit(2); og le r   } h Go   jsdom.env({ fetc y     html: body, JQ uer h wit     scripts: [ rs cho       'http://code.jquery.com/jquery-1.5.min.js' an the     ]   }, function (err, window) { find     var $ = window.jQuery;     $('a.l').each(function() {       console.log($(this).attr('href'));     });   });
  • 75. var request = require('request'),     jsdom = require('jsdom'); var args = process.argv.slice(2); ica tion if (args.length != 1) { a ppl   console.log('Usage: node scraper.js <query sentence>'); p the u   process.exit(1); set } var query = escape(args[0]); var url = 'http://www.google.fr/search?hl=fr&source=hp&ie=ISO-8859-1&q=' + query + '&btnG=Recherche+Google' request({ uri: url }, function (error, response, body) {   if (error) {     console.log('Error when contacting google.com: ' + error);     process.exit(2);   }   if (response && response.statusCode !== 200) {     console.log('Did not get a correct response from Google: ' + response); es ults     process.exit(2); og le r   } h Go   jsdom.env({ fetc y     html: body, JQ uer h wit     scripts: [ rs cho       'http://code.jquery.com/jquery-1.5.min.js' an s the URL     ]   }, function (err, window) { find eir t th prin     var $ = window.jQuery;     $('a.l').each(function() {       console.log($(this).attr('href'));     });   });
  • 76. // Node.js modules required to run the scraper // use npm to install them: // $ `curl http://npmjs.org/install.sh | sh` var request = require('request'),     jsdom = require('jsdom');
  • 77. // Node.js modules required to run the scraper // use npm to install them: // $ `curl http://npmjs.org/install.sh | sh` ap per wr u est P req var request = require('request'), HTT     jsdom = require('jsdom');
  • 78. // Node.js modules required to run the scraper // use npm to install them: // $ `curl http://npmjs.org/install.sh | sh` per w rap u est ver req Ser TTP the var request = require('request'), H yo n Q uer u se j     jsdom = require('jsdom');
  • 79. // remove node and the file name from the arguments list var args = process.argv.slice(2); if (args.length != 1) {   console.log('Usage: node scraper.js <query sentence>');   process.exit(1); } // the query to search on Google var query = escape(args[0]); // Google URL that will be request and whose content will be scraped var url = 'http://www.google.com/search?q=' + query;
  • 80. request({ uri: url }, function (error, response, body) {   // nothing to do if we get an error from Google   if (error) {     console.log('Error when contacting google.com: ' + error);     process.exit(2);   }   // idem if the response is not OK   if (response && response.statusCode !== 200) {     console.log('Did not get a correct response from Google: ' + response);     process.exit(2);   } ... });
  • 81. po nse request({ uri: url }, function (error, response, body) { a res e get w   // nothing to do if we get an error from Google w hen b ack   if (error) { call     console.log('Error when contacting google.com: ' + error);     process.exit(2);   }   // idem if the response is not OK   if (response && response.statusCode !== 200) {     console.log('Did not get a correct response from Google: ' + response);     process.exit(2);   } ... });
  • 82. po nse request({ uri: url }, function (error, response, body) { a res e get w   // nothing to do if we get an error from Google w hen b ack   if (error) { call     console.log('Error when contacting google.com: ' + error);     process.exit(2);   }   // idem if the response is not OK   if (response && response.statusCode !== 200) {     console.log('Did not get a correct response from Google: ' + response);     process.exit(2);   } b ody in the li nks the find et’s ... l });
  • 83. // use jsdom and jQuery to manipulate the DOM corresponding to the response's body   jsdom.env({     html: body,     scripts: [        // jQuery is loaded directly from its web site.        // We could instead cache it locally for efficiency       'http://code.jquery.com/jquery-1.5.min.js'     ]   }, function (err, window) { ...   });
  • 84. // use jsdom and jQuery to manipulate the DOM corresponding to the response's body y   jsdom.env({ jQ uer up o set     html: body, do mt s     scripts: [ use j        // jQuery is loaded directly from its web site.        // We could instead cache it locally for efficiency       'http://code.jquery.com/jquery-1.5.min.js'     ]   }, function (err, window) { ...   });
  • 85. // use jsdom and jQuery to manipulate the DOM corresponding to the response's body y   jsdom.env({ jQ uer up o set     html: body, do mt s     scripts: [ use j        // jQuery is loaded directly from its web site.        // We could instead cache it locally for efficiency       'http://code.jquery.com/jquery-1.5.min.js'     ]   }, function (err, window) { yc ode uer ... iliar jQ m oe s fa   }); he re g
  • 86. // alias jQuery object to the more familiar '$' var $ = window.jQuery;   // print the URLS of the results listed by Google...     $('a.l').each(function() {       console.log($(this).attr('href'));     });
  • 87.
  • 91. Another arrow in your quiver!
  • 92. «Ruby, Javascript, and Clojure are all general-purpose languages, but they each excel at certain use cases. Ruby's highly dynamic nature and emphasis on beauty makes it a natural fit for user-facing web apps. Node.js's evented concurrency makes it a great fit for the realtime web. Clojure covers a new use case on the Heroku platform: components which demand correctness, performance, composability; and optionally, access to the Java ecosystem.» -- http://blog.heroku.com/archives/2011/7/5/ clojure_on_heroku

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n