SlideShare une entreprise Scribd logo
1  sur  17
node.js - Eventful JavaScript on the Server
By David Ruiz - @wupsbr
Centro de Inovação do grupo Telefônica Brasil
What is node.js?
In a nutshell, it’s JavaScript on
the server side

Created by Ryan Dahl (@ryah) in
2009

Based on the Google V8
JavaScript engine + Evented I/O

Performance is king:

   Property access through hidden
   classes
   Machine code
   Garbage collection
Want a HTTP Server?
var http = require('http');
http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Welcome to the HTTP Server!');
}).listen(4000);
Want a TCP Server?
var tcp = require('net');
tcp.createServer(function(socket) {
  socket.addListener('connect', function() {
    socket.write('Welcome to the TCP Server!n>');
  });
}).listen(4000);
Evented I/O benchmarking
APACHE vs NGINX




                  http://blog.webfaction.com/a-little-holiday-present
Evented I/O + V8 Engine
   libeio: async I/O

   libev: event loop

   libuv: wrapper for libev and IOCP

   There is a single thread running

   No parallel execution... for YOUR code!

db.query().select('*').from('users').execute(function(){
  fs.readFile('settings.json', function () {
    // Block for five seconds :(
    var now = new Date().getTime();
    while(new Date().getTime() < now + 5000);
    // Response :)
  });
});
What about multiple cores?
  The load balancer approach

                                  :1337
                                  :1338
                                  :1339
  The OS approach

var http = require('http'), cluster = require('cluster');
var server = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('TID Rocks!');
});
cluster(server).listen(1337);
And about packages?




One line install:
# curl http://npmjs.org/install.sh | sh

Now, let’s install the node.js mysql client?
# npm install mysql
And about packages?




One line install:
# curl http://npmjs.org/install.sh | sh

Now, let’s install the node.js mysql client?
 There are more than 4900 packages,  and more
# npm install mysql
           than 15 are added each day!
Let’s check the performance
  PHP                                            NODE.JS
$a =   null;                                  var i, a, b, c, max;
$b =   null;
$c =   null;                                  max = 1e6;
$i =   null;
$max   = 1e6;                                 console.time('maths');

$start = microtime(true);                     for (i = 0; i < max; i++)
                                              {
for ($i = 0; $i   < $max; $i++)                   a = 1234 + 5678 + i;
{                                                 b = 1234 * 5678 + i;
    $a = 1234 +   5678 + $i;                      c = 1234 / 2 + i;
    $b = 1234 *   5678 + $i;                  }
    $c = 1234 /   2 + $i;
}                                             console.timeEnd('maths');

var_dump(microtime(true) - $start);




                                      http://www.matt-knight.co.uk/2011/node-js-vs-php-performance-maths/
Let’s check the performance
                                                              RESULTS IN SECONDS
  PHP                                             NODE.JS
$a =   null;    LOOP SIZE             PHP      var i, a, b, c, max; NODE.JS
$b =   null;
$c =   null;                                   max = 1e6;
$i =   null;
$max   = 1e6;                                  console.time('maths');
                   100.000            0,077                             0,002
$start = microtime(true);                      for (i = 0; i < max; i++)
                                               {
for ($i = 0; $i   < $max; $i++)                    a = 1234 + 5678 + i;
{                  1.000.000          0,759        b = 1234 * 5678 + 0,016
                                                                     i;
    $a = 1234 +   5678 + $i;                       c = 1234 / 2 + i;
    $b = 1234 *   5678 + $i;                   }
    $c = 1234 /   2 + $i;
}                                              console.timeEnd('maths');
                  10.000.000          7,605                             0,157
var_dump(microtime(true) - $start);



                  100.000.000         75,159                            1,567



                                       http://www.matt-knight.co.uk/2011/node-js-vs-php-performance-maths/
Who are using node.js?
linkedin (m.linkedin.com) - mobile stack
The improvements the team saw were staggering. They went from running 15
servers with 15 instances (virtual servers) on each physical machine, to just 4
instances that can handle double the traffic.
http://venturebeat.com/2011/08/16/linkedin-node/


klout (klout.com) - frontend + api
In our tests, a single node.js process was able to handle thousands of
concurrent connections in a very CPU-efficient manner. Plus, using JavaScript
on both the server and the client made writing multi-purpose code very
straightforward. We knew of other companies using node.js at the time, but
most were using it to serve APIs.
http://corp.klout.com/blog/2011/10/the-tech-behind-klout-com/


and many others: HP Yahoo!, Nokia, Heroku, VMWare, Loopt ....
                   ,
Test Driven Development!
 TEST          RESULT
Cross platform socket
 About Socket.IO                             Supported languages
 Socket.IO aims to make realtime apps        Cocoa (iOS)
                                             - fpotter/socketio-cocoa
 possible in every browser and mobile        Erlang
 device, blurring the differences            - yrashk/socket.io-erlang
                                             Flash
 between the different transport             - simb/FlashSocket.IO
 mechanisms. It's care-free realtime         Go
                                             - madari/go-socket.io (Currently not compatible with 0.7+)
 100% in JavaScript.                         Java
 In order to provide realtime connectivity   - ibdknox/socket.io-netty
                                             - benkay/java-socket.io.client
 on every browser, Socket.IO selects         - Ovea/Socket.IO-Java
                                             Lua
 the most capable transport at runtime,      - ignacio/LuaNode-Socket.IO
 without it affecting the API:               MrJoes/tornadio (0.6)
                                             - gevent-socketio
 WebSocket, Adobe® Flash® Socket,            Perl
 AJAX long polling, AJAX multipart           - vti/pocketio
                                             Python
 streaming, Forever Iframe and JSONP         - MrJoes/tornadio2 (0.7+)

 Polling.                                    Ruby
                                             - markjeee/Socket.IO-rack
The node.js ecosystem
 Express                                     Cluster
A Sinatra inspired node.js web development   Extensible multi-core server management for
framework.                                   nodejs.
Jade                                         Supervisor
Jade is a high performance template engine   A little supervisor script for nodejs. It runs
heavily influenced by Haml and implemented   your program, and watches for code
with JavaScript for node.                    changes, so you can have hot-code
Socket.io                                    reloading-ish behavior, without worrying
An simple HTTP Socket interface              about memory leaks.
implementation and server.                   Joyent (http://no.de)
Mongoose                                     Free SmartMachine hosting to delivery
Mongoose aims at solving the complexities    modern applications with nodejs.
associated with asynchronous data storage    Expresso
by providing a more intuitive API.           TDD for nodejs projects in express.
                                             Testosterone
                                             Another and simple TDD for nodejs.
great links:
http://nodejs.org/
http://no.de/
http://howtonode.org/
http://jade-lang.com/
http://www.commonjs.org/
https://github.com/ry/node/wiki
http://en.wikipedia.org/wiki/Event_loop
http://lse.sourceforge.net/io/aio.html
http://code.google.com/p/v8/
https://github.com/ry/node/wiki/modules
https://github.com/isaacs/npm
thanks!
http://www.davidruiz.eti.br/   http://www.tid.es/
wupsbr@gmail.com               @telefonicaid
@wupsbr

Contenu connexe

Tendances

Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
ConFoo
 

Tendances (20)

Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
NodeJS
NodeJSNodeJS
NodeJS
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Docker, Docker Swarm mangement tool - Gorae
Docker, Docker Swarm mangement tool - GoraeDocker, Docker Swarm mangement tool - Gorae
Docker, Docker Swarm mangement tool - Gorae
 
NodeJS: an Introduction
NodeJS: an IntroductionNodeJS: an Introduction
NodeJS: an Introduction
 
Future of NodeJS
Future of NodeJSFuture of NodeJS
Future of NodeJS
 
Philly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSPhilly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJS
 
Intro to node and non blocking io
Intro to node and non blocking ioIntro to node and non blocking io
Intro to node and non blocking io
 
Node js
Node jsNode js
Node js
 
실시간 서비스 플랫폼 개발 사례
실시간 서비스 플랫폼 개발 사례실시간 서비스 플랫폼 개발 사례
실시간 서비스 플랫폼 개발 사례
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Docker composeで開発環境をメンバに配布せよ
Docker composeで開発環境をメンバに配布せよDocker composeで開発環境をメンバに配布せよ
Docker composeで開発環境をメンバに配布せよ
 
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
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
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
 
Communication in Node.js
Communication in Node.jsCommunication in Node.js
Communication in Node.js
 

Similaire à node.js - Eventful JavaScript on the Server

Why Node.js
Why Node.jsWhy Node.js
Why Node.js
guileen
 
Reutov, yunusov, nagibin random numbers take ii
Reutov, yunusov, nagibin   random numbers take iiReutov, yunusov, nagibin   random numbers take ii
Reutov, yunusov, nagibin random numbers take ii
DefconRussia
 

Similaire à node.js - Eventful JavaScript on the Server (20)

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin Shanghai
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.js
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
(C)NodeJS
(C)NodeJS(C)NodeJS
(C)NodeJS
 
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.
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
 
Node azure
Node azureNode azure
Node azure
 
Node.js 1, 2, 3
Node.js 1, 2, 3Node.js 1, 2, 3
Node.js 1, 2, 3
 
NodeJS
NodeJSNodeJS
NodeJS
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
Reutov, yunusov, nagibin random numbers take ii
Reutov, yunusov, nagibin   random numbers take iiReutov, yunusov, nagibin   random numbers take ii
Reutov, yunusov, nagibin random numbers take ii
 
Random numbers
Random numbersRandom numbers
Random numbers
 
KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Node js
Node jsNode js
Node js
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
Introducing to node.js
Introducing to node.jsIntroducing to node.js
Introducing to node.js
 

Plus de David Ruiz

imax games - Desenvolvimento de Jogos
imax games - Desenvolvimento de Jogosimax games - Desenvolvimento de Jogos
imax games - Desenvolvimento de Jogos
David Ruiz
 
Modelagem 3D de personagens para jogos
Modelagem 3D de personagens para jogosModelagem 3D de personagens para jogos
Modelagem 3D de personagens para jogos
David Ruiz
 
Web 2.0 e AJAX - Parte 3 / 3
Web 2.0 e AJAX - Parte 3 / 3Web 2.0 e AJAX - Parte 3 / 3
Web 2.0 e AJAX - Parte 3 / 3
David Ruiz
 
Tendências de Search Egines - Microsoft
Tendências de Search Egines - MicrosoftTendências de Search Egines - Microsoft
Tendências de Search Egines - Microsoft
David Ruiz
 

Plus de David Ruiz (20)

Developer Experience - Escalando Negócios com a melhor experiência ao desenvo...
Developer Experience - Escalando Negócios com a melhor experiência ao desenvo...Developer Experience - Escalando Negócios com a melhor experiência ao desenvo...
Developer Experience - Escalando Negócios com a melhor experiência ao desenvo...
 
Plataformas de Inovação - Criando Conexões
Plataformas de Inovação - Criando ConexõesPlataformas de Inovação - Criando Conexões
Plataformas de Inovação - Criando Conexões
 
Containers com docker #CPRecife4
Containers com docker #CPRecife4Containers com docker #CPRecife4
Containers com docker #CPRecife4
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
 
Arduino Day 2014 - Cloud para Internet das Coisas & Intel Galileo
Arduino Day 2014 - Cloud para Internet das Coisas & Intel GalileoArduino Day 2014 - Cloud para Internet das Coisas & Intel Galileo
Arduino Day 2014 - Cloud para Internet das Coisas & Intel Galileo
 
Hoodie na Campus Party Brasil 2013
Hoodie na Campus Party Brasil 2013Hoodie na Campus Party Brasil 2013
Hoodie na Campus Party Brasil 2013
 
Workshop Kit de Desenvolvimento IoT
Workshop Kit de Desenvolvimento IoTWorkshop Kit de Desenvolvimento IoT
Workshop Kit de Desenvolvimento IoT
 
Workshop de Firefox OS
Workshop de Firefox OSWorkshop de Firefox OS
Workshop de Firefox OS
 
Desenvolvendo para Firefox OS
Desenvolvendo para Firefox OSDesenvolvendo para Firefox OS
Desenvolvendo para Firefox OS
 
Introdução ao Firefox OS
Introdução ao Firefox OSIntrodução ao Firefox OS
Introdução ao Firefox OS
 
livre.fm - keynote
livre.fm - keynotelivre.fm - keynote
livre.fm - keynote
 
GED - A caminho do conhecimento
GED - A caminho do conhecimentoGED - A caminho do conhecimento
GED - A caminho do conhecimento
 
imax games - Desenvolvimento de Jogos
imax games - Desenvolvimento de Jogosimax games - Desenvolvimento de Jogos
imax games - Desenvolvimento de Jogos
 
Modelagem 3D de personagens para jogos
Modelagem 3D de personagens para jogosModelagem 3D de personagens para jogos
Modelagem 3D de personagens para jogos
 
Ruby On Rails - Porque Utilizar?
Ruby On Rails - Porque Utilizar?Ruby On Rails - Porque Utilizar?
Ruby On Rails - Porque Utilizar?
 
Trabalhe na Abril Digital
Trabalhe na Abril DigitalTrabalhe na Abril Digital
Trabalhe na Abril Digital
 
Lua para Jogos
Lua para JogosLua para Jogos
Lua para Jogos
 
Web 2.0 e AJAX - Parte 3 / 3
Web 2.0 e AJAX - Parte 3 / 3Web 2.0 e AJAX - Parte 3 / 3
Web 2.0 e AJAX - Parte 3 / 3
 
Tendências de Search Egines - Microsoft
Tendências de Search Egines - MicrosoftTendências de Search Egines - Microsoft
Tendências de Search Egines - Microsoft
 
Web 2.0 e AJAX - Parte 2 / 3
Web 2.0 e AJAX - Parte 2 / 3Web 2.0 e AJAX - Parte 2 / 3
Web 2.0 e AJAX - Parte 2 / 3
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
Safe Software
 
+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...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
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...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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)
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
+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...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

node.js - Eventful JavaScript on the Server

  • 1. node.js - Eventful JavaScript on the Server By David Ruiz - @wupsbr Centro de Inovação do grupo Telefônica Brasil
  • 2. What is node.js? In a nutshell, it’s JavaScript on the server side Created by Ryan Dahl (@ryah) in 2009 Based on the Google V8 JavaScript engine + Evented I/O Performance is king: Property access through hidden classes Machine code Garbage collection
  • 3. Want a HTTP Server? var http = require('http'); http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Welcome to the HTTP Server!'); }).listen(4000);
  • 4. Want a TCP Server? var tcp = require('net'); tcp.createServer(function(socket) { socket.addListener('connect', function() { socket.write('Welcome to the TCP Server!n>'); }); }).listen(4000);
  • 5. Evented I/O benchmarking APACHE vs NGINX http://blog.webfaction.com/a-little-holiday-present
  • 6. Evented I/O + V8 Engine libeio: async I/O libev: event loop libuv: wrapper for libev and IOCP There is a single thread running No parallel execution... for YOUR code! db.query().select('*').from('users').execute(function(){ fs.readFile('settings.json', function () { // Block for five seconds :( var now = new Date().getTime(); while(new Date().getTime() < now + 5000); // Response :) }); });
  • 7. What about multiple cores? The load balancer approach :1337 :1338 :1339 The OS approach var http = require('http'), cluster = require('cluster'); var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('TID Rocks!'); }); cluster(server).listen(1337);
  • 8. And about packages? One line install: # curl http://npmjs.org/install.sh | sh Now, let’s install the node.js mysql client? # npm install mysql
  • 9. And about packages? One line install: # curl http://npmjs.org/install.sh | sh Now, let’s install the node.js mysql client? There are more than 4900 packages, and more # npm install mysql than 15 are added each day!
  • 10. Let’s check the performance PHP NODE.JS $a = null; var i, a, b, c, max; $b = null; $c = null; max = 1e6; $i = null; $max = 1e6; console.time('maths'); $start = microtime(true); for (i = 0; i < max; i++) { for ($i = 0; $i < $max; $i++) a = 1234 + 5678 + i; { b = 1234 * 5678 + i; $a = 1234 + 5678 + $i; c = 1234 / 2 + i; $b = 1234 * 5678 + $i; } $c = 1234 / 2 + $i; } console.timeEnd('maths'); var_dump(microtime(true) - $start); http://www.matt-knight.co.uk/2011/node-js-vs-php-performance-maths/
  • 11. Let’s check the performance RESULTS IN SECONDS PHP NODE.JS $a = null; LOOP SIZE PHP var i, a, b, c, max; NODE.JS $b = null; $c = null; max = 1e6; $i = null; $max = 1e6; console.time('maths'); 100.000 0,077 0,002 $start = microtime(true); for (i = 0; i < max; i++) { for ($i = 0; $i < $max; $i++) a = 1234 + 5678 + i; { 1.000.000 0,759 b = 1234 * 5678 + 0,016 i; $a = 1234 + 5678 + $i; c = 1234 / 2 + i; $b = 1234 * 5678 + $i; } $c = 1234 / 2 + $i; } console.timeEnd('maths'); 10.000.000 7,605 0,157 var_dump(microtime(true) - $start); 100.000.000 75,159 1,567 http://www.matt-knight.co.uk/2011/node-js-vs-php-performance-maths/
  • 12. Who are using node.js? linkedin (m.linkedin.com) - mobile stack The improvements the team saw were staggering. They went from running 15 servers with 15 instances (virtual servers) on each physical machine, to just 4 instances that can handle double the traffic. http://venturebeat.com/2011/08/16/linkedin-node/ klout (klout.com) - frontend + api In our tests, a single node.js process was able to handle thousands of concurrent connections in a very CPU-efficient manner. Plus, using JavaScript on both the server and the client made writing multi-purpose code very straightforward. We knew of other companies using node.js at the time, but most were using it to serve APIs. http://corp.klout.com/blog/2011/10/the-tech-behind-klout-com/ and many others: HP Yahoo!, Nokia, Heroku, VMWare, Loopt .... ,
  • 14. Cross platform socket About Socket.IO Supported languages Socket.IO aims to make realtime apps Cocoa (iOS) - fpotter/socketio-cocoa possible in every browser and mobile Erlang device, blurring the differences - yrashk/socket.io-erlang Flash between the different transport - simb/FlashSocket.IO mechanisms. It's care-free realtime Go - madari/go-socket.io (Currently not compatible with 0.7+) 100% in JavaScript. Java In order to provide realtime connectivity - ibdknox/socket.io-netty - benkay/java-socket.io.client on every browser, Socket.IO selects - Ovea/Socket.IO-Java Lua the most capable transport at runtime, - ignacio/LuaNode-Socket.IO without it affecting the API: MrJoes/tornadio (0.6) - gevent-socketio WebSocket, Adobe® Flash® Socket, Perl AJAX long polling, AJAX multipart - vti/pocketio Python streaming, Forever Iframe and JSONP - MrJoes/tornadio2 (0.7+) Polling. Ruby - markjeee/Socket.IO-rack
  • 15. The node.js ecosystem Express Cluster A Sinatra inspired node.js web development Extensible multi-core server management for framework. nodejs. Jade Supervisor Jade is a high performance template engine A little supervisor script for nodejs. It runs heavily influenced by Haml and implemented your program, and watches for code with JavaScript for node. changes, so you can have hot-code Socket.io reloading-ish behavior, without worrying An simple HTTP Socket interface about memory leaks. implementation and server. Joyent (http://no.de) Mongoose Free SmartMachine hosting to delivery Mongoose aims at solving the complexities modern applications with nodejs. associated with asynchronous data storage Expresso by providing a more intuitive API. TDD for nodejs projects in express. Testosterone Another and simple TDD for nodejs.
  • 17. thanks! http://www.davidruiz.eti.br/ http://www.tid.es/ wupsbr@gmail.com @telefonicaid @wupsbr