SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
COSE CHE NON TI ASPETTI DA
   JAVASCRIPT: NODE.JS
Chi siamo

Luciano  Colosio  
SA  &  Dev  @  Save  The  Mom
@unlucio



Michele  Capra  
Dev  @  OrangeCode
@piccoloaiutante
Cosa vedremo oggi
Che  cos’è  Node.JS

Dove  nasce

 ContesB  in  cui  usarlo

Il  mondo  asincrono

Demo  Live

  Deploy  su  un  servizio  free  (Heroku)
Che cos’è Node.JS

 Javascirpt  runBme  basato  su  V8

  Event  Driven  I/O  server-­‐side
Da dove nasce

  Riprodurre  il  comportamento  in  “push”  mostrato  da  gmail
                  Superare  i  limit  del  one-­‐way  


             BONUS DERIVATO

Le  caraUerisBche  asincrone  di  JS  permeUono  una  gesBone  piu’  
               comoda  dell’I/O  che  costa  molto
Da dove nasce
             Costo  dell’  I/O
L1-­‐cache                         3  cicli

L2-­‐cache                        14  cicli

  RAM                            250  cicli

 Disco                      41x10^6  cicli

Network                     240x10^6  cicli
Gestire le richieste


        Sincrono:  gesBsco  una  richiesta  alla  volta



Contro: ogni richiesta può (e fa!) da tappo alle altre
Gestire le richieste

                Fork  del  processo

    Un  processo  nuovo  per  ogni  richiesta

Contro:  non  scala  su  migliaia  di  connessioni
 (ameno  di  non  usare  migliaia  di  servers  ;))
Gestire le richieste

     Un  Thread  nuovo  per  ogni  richiesta

Contro:  la  macchina  potrebbe  non  avere  
abbastanza  thread  disponibili,  
programmazione  concorrente  è  complessa,  
problemi  di  memoria
Gestire le richieste

          La  scelta  di  node:

           Singolo  Thread

 Niente  parallelizzazione  del  codice
Event Loop

La  logica  nell’eventloop  risulta  bloccante:


  Devo  aUendere  che  i  task  terminino
Soluzione:

  NON fare nulla nel maintherad

Tutte le chiamate di I/O sono gestite
 come eventi asincroni, quindi non
             bloccanti.


Utilizzare event driven development
Event loop

  non e' necessario pre carrozzarsi per le
               perfomarnces
(es: pre allocare thread per rispondere piu'
               velocemente).

     Minor spreco di memoria/risorse

Minor rischio che il server vada in oveload
Importante!


Rispondere velocemente al client delegando a task
attività che richiedono risorse ed i/o ad alta latenza


      Il focus è sulla risposta nel minor tempo
                        possibile
Async VS Sync


//  Good:  write  files  asynchronously
fs.writeFile('message.txt',  'Hello  Node',  funcBon  (err)  {
    console.log("It's  saved  and  the  server  remains  responsive!");
});

//  BAD:  write  files  synchronously
fs.writeFileSync('message.txt',  'Hello  Node');
console.log("It's  saved,  but  you  just  blocked  ALL  requests!");
Esempio Architettura
                              Database



    Client     Web Engine        DB




    User        NODE




                                NODE
                                                    Disk



                                               Mass storage
                            Logging facility
                                               (big slow disk)




Le scritture dei logs non sono piu’ un problema!
Esempio di contesti

                   Web API


Realtime web services (chat, push, peppertweet)
Chi lo usa:
                  37signals
            Ajax.org - Cloud9 IDE
                    eBay
                   Trello
                    Klout
                  Linkedin
                  Microsoft
                   Voxer
                   Yahoo!

https://github.com/joyent/node/wiki/Projects,-
   Applications,-and-Companies-Using-Node
JS: V8 in Node
Stesso motore del browser ma:


tutto gira nell’Event Loop

non c’è DOM

non c’è JQuery che tenga

programmazione asincrona
ESEMPI DI APPS


Menamo  le  mani  in  
    pasta  :)
App Esempio
       HUp  Hello  World,  la  piu’  semplice  node  app:

var http = require('http');

var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello Worldn");
});

server.listen(8000);

console.log("Server running at http://127.0.0.1:8000/");
App Esempio
Http Hello World, basta una lib ed ecco un servizio
                      REST
var  server  =  require('./lib/node-­‐router').getServer();

server.get("/json",  funcBon  (req,  res,  match)  {
    return  {hello:  "World"};
});

server.get(new  RegExp("^/(.*)$"),  funcBon  hello(req,  res,  match)  {
    return  "Hello  "  +  (match  ||  "World")  +  "!";
});


server.listen(8080);
App Esempio
                  Vi  ricordate  IRC?

                      NO?!?!?!

              Ok,  ce  l’aspeUavamo  ;P

Oggi  ci  ispireremo  al  passato  per  un  twiUer  bot:


               TWITVIA
App Esempio


        Get  the  code:

hUps://github.com/unlucio/tvitvia
App Esempio: Struttura

                    Moduli


Heroku  Process                 DescriUore
 File  (opBonal)                 per  npm


                   Main  File
App Esempio: npm install
     Moduli  installaB
                           {
                                "name":  "Twitvia",
                                "descripBon":  "Vintage  trivia  bot",
                                "version":  "0.0.1",
                                "dependencies":  {
                                    "twit"  :  "0.1.2",
                                    "underscore":  "1.3.1",
                                    "db-­‐mysql":  "0.7.6"
                                },
                                "engines":  {
                                    "node":  ">=  0.6.0"
                                }


Diamogli  un  nome  sensato  :)
App Esempio


      Ovviamente  possiamo
       aggiungere  directory
       a  nostro  piacimento
     per  parB  delle  nostra  app
App Esempio: def. lib

   var  Twit  =  require('twit');

   module.exports  =  (funcBon(twiUerClient)  {
     
      twiUerClient  =  funcBon(datas)  {};
     
      twiUerClient.prototype.publishTweet  =  funcBon  (message)  {};

        twiUerClient.prototype.sendMenBon  =  funcBon  (to,  message)  {};

         twiUerClient.prototype.sendDM  =  funcBon  (to,  message)  {};
     
         twiUerClient.prototype.followUser  =  funcBon  (user)  {};
     
         return  twiUerClient;
   })();
App Esempio: use lib
   var  TweUerClient  =  require('./lib/twiUerClient'),

   var  tClient  =  new  TweUerClient({
         consumer_key:                  'getItFromTwiUer',
         consumer_secret:            'getItFromTwiUer',
         access_token:                  'getItFromTwiUer',
         access_token_secret:    'getItFromTwiUer',
   });

   funcBon  getCommand(tweet)  {
   [...]
   }

   tClient.T.stream('user',[],  funcBon  (stream)  {
       stream.on('tweet',  funcBon  (tweet)  {
           getCommand(tweet)
       });
   });
App Esempio: model objs
     var  _  =  require('underscore');

     module.exports  =  (funcBon(quesBons)  {
       
            quesBons  =  funcBon(db,  tweeterClient)  {
                 this.db  =  db;
                 this.tweeterClient  =  tweeterClient;
            };
       
            quesBons.prototype.publishRandom  =  funcBon()  {};
       
            quesBons.prototype.getRandom  =  funcBon  (quesBonsList)  {};
       
            quesBons.prototype.selectAll  =  funcBon(callback)  {};
       
            quesBons.prototype.setAnswered  =  funcBon(refTweetID,  
     callback)  {}
       
            return  quesBons;
      })();
App Esempio: model objs

     module.exports  =  (funcBon(answers)  {
       
         answers  =  funcBon(db,  tweeterClient)  {
             this.db  =  db;
             this.tweeterClient  =  tweeterClient;
         };
       
         answers.prototype.checkMatch  =    funcBon  (refTweetID,  
     userAnswer,  callback)  {
         };

           return  answers;
     })();
App Esempio: model objs
    module.exports  =  (funcBon(users)  {
      
          users  =  funcBon(db,  tweeterClient)  {
               this.db  =  db;
               this.tweeterClient  =  tweeterClient;
          };
      
          users.prototype.find  =  funcBon(userName,  callback)  {};
      
          users.prototype.add  =  funcBon(userName,  callback)  {};
      
          users.prototype.capture  =  funcBon(userName,  callback)  {};
      
          users.prototype.scorePoint  =  funcBon(userName,  callback)  {};
      
          users.prototype._updateScore  =  funcBon(userID,  thePlayer,  callback){};
      
          return  users;
    })();
App Esempio: together
         var  mysql  =  require('db-­‐mysql'),
               TweUerClient  =  require('./lib/twiUerClient'),
               Users  =  require('./model/users'),
               QuesBons  =  require('./model/quesBons'),
               Answers  =  require('./model/answers');

       var  myDb  =  new  mysql.Database({
            [connecBon  datas]
       });

       [...]

       var  tClient  =  new  TweUerClient({
            [api  datas]
       });

       var  users  =  new  Users(myDb,  tClient);
       var  quesBons  =  new  QuesBons(myDb,  tClient);
       var  answers  =  new  Answers(myDb,  tClient);

       tClient.T.stream('user',[],  funcBon  (stream)  {
           stream.on('tweet',  funcBon  (tweet)  {
                getCommand(tweet)
           });
        });
Deploy & hosting
            heroku  login
      Compiliamo  il  Procfile
  web:  node  <mainscript.js>
               git  init
              git  add  .
git  commit  -­‐m  “<commento>”
 heroku  create  -­‐-­‐stack  cedar
     git  push  heroku  master
     heroku  ps:scale  web=1
Nella realta’


Un  esempio  famoso  ed  eclatante  
       di  uBlizzo  di  node:

          Linkedin!
Dove lo usano?
Linkedin  usa  node  come  middle  layer  tra  i  server  di  backend  ed  i  
                           client  mobile


                Mobile client




                                     NodeJs           backend
                                    instances          server


               Mobile Client
I 10 consigli per node.js
Evitare  il  codice  sincorono
No  socket  polling!
Non  usare  node.js  per  servire  asset  staBci
Delegare  il  rendering  al  client
Usare  gzip  tra  i  vari  componenB
Parallelizzare  al  piu’  possibile!
Se  possibile:  NO  SESSIONS
Usare  moduli  binari  anzicche’  in  javascript
Usare  javascript  standard  anzicche’  librerie  faUe  per  i  client
Tenere  il  codice  piccolo  e  compaUo
Grazie per l’attenzione




se  volete,  trollateci  su  twiUer
@unlucio  -­‐  @piccoloaiutante
Un po’ di spam ;)




hUp://nodejsconf.it
hUp://www.webdebs.org/
Cerco Dev
Save the Mom cerca sviluppatori da integrare nel
                 nostro team! :)
                      Skills:
                       Web
                    MobileWeb
               Mobile applications
         (iOS, wp7, android, balckberry)

        Scrivi  a:
lucio@savethemom.com

Weitere ähnliche Inhalte

Was ist angesagt?

jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerMatteo Magni
 
ASP.NET MVC 3 - Presentare i dati nella View
ASP.NET MVC 3 - Presentare i dati nella ViewASP.NET MVC 3 - Presentare i dati nella View
ASP.NET MVC 3 - Presentare i dati nella ViewManuel Scapolan
 
jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerMatteo Magni
 
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...Davide Cerbo
 
Fare con Zend Framework 2 ciò che facevo con ZF1
Fare con Zend Framework 2 ciò che facevo con ZF1Fare con Zend Framework 2 ciò che facevo con ZF1
Fare con Zend Framework 2 ciò che facevo con ZF1Steve Maraspin
 
MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009Massimiliano Dessì
 
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case studyMantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case studyDrupalDay
 
Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Martino Bordin
 
ASP.NET MVC3 - Tutti i compiti del Controller
ASP.NET MVC3 - Tutti i compiti del ControllerASP.NET MVC3 - Tutti i compiti del Controller
ASP.NET MVC3 - Tutti i compiti del ControllerManuel Scapolan
 
Autenticazione delle api con jwt e symfony (Italian)
Autenticazione delle api con jwt e symfony (Italian)Autenticazione delle api con jwt e symfony (Italian)
Autenticazione delle api con jwt e symfony (Italian)Marco Albarelli
 

Was ist angesagt? (20)

jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesigner
 
Java lezione 17
Java lezione 17Java lezione 17
Java lezione 17
 
Java lezione 18
Java lezione 18Java lezione 18
Java lezione 18
 
ASP.NET MVC 3 - Presentare i dati nella View
ASP.NET MVC 3 - Presentare i dati nella ViewASP.NET MVC 3 - Presentare i dati nella View
ASP.NET MVC 3 - Presentare i dati nella View
 
jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesigner
 
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
The Hitchhiker's Guide to testable code: semplici regole per scrivere codice ...
 
Many Designs Elements
Many Designs ElementsMany Designs Elements
Many Designs Elements
 
Applicazioni native in java
Applicazioni native in javaApplicazioni native in java
Applicazioni native in java
 
Fare con Zend Framework 2 ciò che facevo con ZF1
Fare con Zend Framework 2 ciò che facevo con ZF1Fare con Zend Framework 2 ciò che facevo con ZF1
Fare con Zend Framework 2 ciò che facevo con ZF1
 
Perl Template Toolkit
Perl Template ToolkitPerl Template Toolkit
Perl Template Toolkit
 
Logging
LoggingLogging
Logging
 
Amazon S3 in Perl
Amazon S3 in PerlAmazon S3 in Perl
Amazon S3 in Perl
 
MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009
 
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case studyMantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
 
Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3
 
ASP.NET MVC3 - Tutti i compiti del Controller
ASP.NET MVC3 - Tutti i compiti del ControllerASP.NET MVC3 - Tutti i compiti del Controller
ASP.NET MVC3 - Tutti i compiti del Controller
 
Django
DjangoDjango
Django
 
Java Advanced
Java AdvancedJava Advanced
Java Advanced
 
local::lib
local::liblocal::lib
local::lib
 
Autenticazione delle api con jwt e symfony (Italian)
Autenticazione delle api con jwt e symfony (Italian)Autenticazione delle api con jwt e symfony (Italian)
Autenticazione delle api con jwt e symfony (Italian)
 

Andere mochten auch

Mobile application
Mobile applicationMobile application
Mobile applicationenunmint
 
Biografia bryan mena 1 bachillerato b
Biografia bryan mena 1 bachillerato bBiografia bryan mena 1 bachillerato b
Biografia bryan mena 1 bachillerato bBryan100500
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppMichele Capra
 
Biografia bryan mena 1 bachillerato b
Biografia bryan mena 1 bachillerato bBiografia bryan mena 1 bachillerato b
Biografia bryan mena 1 bachillerato bBryan100500
 
Mobile application
Mobile applicationMobile application
Mobile applicationenunmint
 
Getting started with Windows Phone 7 and unit test
Getting started with Windows Phone 7 and unit testGetting started with Windows Phone 7 and unit test
Getting started with Windows Phone 7 and unit testMichele Capra
 
Building High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsBuilding High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsMichele Capra
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 

Andere mochten auch (8)

Mobile application
Mobile applicationMobile application
Mobile application
 
Biografia bryan mena 1 bachillerato b
Biografia bryan mena 1 bachillerato bBiografia bryan mena 1 bachillerato b
Biografia bryan mena 1 bachillerato b
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
Biografia bryan mena 1 bachillerato b
Biografia bryan mena 1 bachillerato bBiografia bryan mena 1 bachillerato b
Biografia bryan mena 1 bachillerato b
 
Mobile application
Mobile applicationMobile application
Mobile application
 
Getting started with Windows Phone 7 and unit test
Getting started with Windows Phone 7 and unit testGetting started with Windows Phone 7 and unit test
Getting started with Windows Phone 7 and unit test
 
Building High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsBuilding High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 Apps
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 

Ähnlich wie Introduzione a Node.js

MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBStefano Dindo
 
High specialized vm on open stack cloud
High specialized vm on open stack cloudHigh specialized vm on open stack cloud
High specialized vm on open stack cloudGabriele Baldoni
 
Node.js - Server Side Javascript
Node.js - Server Side JavascriptNode.js - Server Side Javascript
Node.js - Server Side JavascriptMatteo Napolitano
 
Working between the clouds (versione completa)
Working between the clouds (versione completa)Working between the clouds (versione completa)
Working between the clouds (versione completa)Davide Cerbo
 
Drupal Day 2011 - Node.js e Drupal
Drupal Day 2011 - Node.js e DrupalDrupal Day 2011 - Node.js e Drupal
Drupal Day 2011 - Node.js e DrupalDrupalDay
 
Twcrashcourse
TwcrashcourseTwcrashcourse
Twcrashcourserik0
 
Web base - Javascript (Node.js): Elementi di base
Web base - Javascript (Node.js): Elementi di baseWeb base - Javascript (Node.js): Elementi di base
Web base - Javascript (Node.js): Elementi di baseAnnalisa Vignoli
 
AngularJS – Reinventare le applicazioni web
AngularJS – Reinventare le applicazioni webAngularJS – Reinventare le applicazioni web
AngularJS – Reinventare le applicazioni webLuca Milan
 
Progettazione e sviluppo di applicazioni web 2.0 con PHP e Ajax
Progettazione e sviluppo di applicazioni web 2.0 con PHP e AjaxProgettazione e sviluppo di applicazioni web 2.0 con PHP e Ajax
Progettazione e sviluppo di applicazioni web 2.0 con PHP e AjaxGiovanni Cappellini
 
Web base-03-js-numeri stringearray
Web base-03-js-numeri stringearrayWeb base-03-js-numeri stringearray
Web base-03-js-numeri stringearrayStudiabo
 
AngularJS: server communication
AngularJS: server communicationAngularJS: server communication
AngularJS: server communicationVittorio Conte
 

Ähnlich wie Introduzione a Node.js (20)

MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDB
 
#dd12 grillo daniele_xpages_tips_tricks_rev2
#dd12 grillo daniele_xpages_tips_tricks_rev2#dd12 grillo daniele_xpages_tips_tricks_rev2
#dd12 grillo daniele_xpages_tips_tricks_rev2
 
#dd12 Applicazioni a tre voci (Android e Domino)
#dd12 Applicazioni a tre voci (Android e Domino)#dd12 Applicazioni a tre voci (Android e Domino)
#dd12 Applicazioni a tre voci (Android e Domino)
 
XPages Tips & Tricks, #dd13
XPages Tips & Tricks, #dd13XPages Tips & Tricks, #dd13
XPages Tips & Tricks, #dd13
 
High specialized vm on open stack cloud
High specialized vm on open stack cloudHigh specialized vm on open stack cloud
High specialized vm on open stack cloud
 
Node.js - Server Side Javascript
Node.js - Server Side JavascriptNode.js - Server Side Javascript
Node.js - Server Side Javascript
 
Working between the clouds (versione completa)
Working between the clouds (versione completa)Working between the clouds (versione completa)
Working between the clouds (versione completa)
 
Il web 2.0
Il web 2.0Il web 2.0
Il web 2.0
 
Hexagonal architecture ita
Hexagonal architecture itaHexagonal architecture ita
Hexagonal architecture ita
 
Yagwto
YagwtoYagwto
Yagwto
 
Web frameworks
Web frameworksWeb frameworks
Web frameworks
 
Drupal Day 2011 - Node.js e Drupal
Drupal Day 2011 - Node.js e DrupalDrupal Day 2011 - Node.js e Drupal
Drupal Day 2011 - Node.js e Drupal
 
Twcrashcourse
TwcrashcourseTwcrashcourse
Twcrashcourse
 
Ddive Xpage852
Ddive Xpage852Ddive Xpage852
Ddive Xpage852
 
Web base - Javascript (Node.js): Elementi di base
Web base - Javascript (Node.js): Elementi di baseWeb base - Javascript (Node.js): Elementi di base
Web base - Javascript (Node.js): Elementi di base
 
AngularJS – Reinventare le applicazioni web
AngularJS – Reinventare le applicazioni webAngularJS – Reinventare le applicazioni web
AngularJS – Reinventare le applicazioni web
 
Progettazione e sviluppo di applicazioni web 2.0 con PHP e Ajax
Progettazione e sviluppo di applicazioni web 2.0 con PHP e AjaxProgettazione e sviluppo di applicazioni web 2.0 con PHP e Ajax
Progettazione e sviluppo di applicazioni web 2.0 con PHP e Ajax
 
Novità di Asp.Net 4.0
Novità di Asp.Net 4.0Novità di Asp.Net 4.0
Novità di Asp.Net 4.0
 
Web base-03-js-numeri stringearray
Web base-03-js-numeri stringearrayWeb base-03-js-numeri stringearray
Web base-03-js-numeri stringearray
 
AngularJS: server communication
AngularJS: server communicationAngularJS: server communication
AngularJS: server communication
 

Mehr von Michele Capra

Nodeschool italy at codemotion
Nodeschool italy at codemotionNodeschool italy at codemotion
Nodeschool italy at codemotionMichele Capra
 
Little bits & node.js IOT for beginner
Little bits & node.js IOT for beginnerLittle bits & node.js IOT for beginner
Little bits & node.js IOT for beginnerMichele Capra
 
Testing Windows Phone 8.1 app with unit test and Coded UI test
Testing Windows Phone 8.1 app with unit test and Coded UI testTesting Windows Phone 8.1 app with unit test and Coded UI test
Testing Windows Phone 8.1 app with unit test and Coded UI testMichele Capra
 
Porting business apps to Windows Phone
Porting business apps to Windows PhonePorting business apps to Windows Phone
Porting business apps to Windows PhoneMichele Capra
 
The magic of Dynamic in Nancy Fx
The magic of Dynamic in Nancy FxThe magic of Dynamic in Nancy Fx
The magic of Dynamic in Nancy FxMichele Capra
 
Windows Phone 7 Development
Windows Phone 7 DevelopmentWindows Phone 7 Development
Windows Phone 7 DevelopmentMichele Capra
 
My Final Dissertation
My Final DissertationMy Final Dissertation
My Final DissertationMichele Capra
 

Mehr von Michele Capra (7)

Nodeschool italy at codemotion
Nodeschool italy at codemotionNodeschool italy at codemotion
Nodeschool italy at codemotion
 
Little bits & node.js IOT for beginner
Little bits & node.js IOT for beginnerLittle bits & node.js IOT for beginner
Little bits & node.js IOT for beginner
 
Testing Windows Phone 8.1 app with unit test and Coded UI test
Testing Windows Phone 8.1 app with unit test and Coded UI testTesting Windows Phone 8.1 app with unit test and Coded UI test
Testing Windows Phone 8.1 app with unit test and Coded UI test
 
Porting business apps to Windows Phone
Porting business apps to Windows PhonePorting business apps to Windows Phone
Porting business apps to Windows Phone
 
The magic of Dynamic in Nancy Fx
The magic of Dynamic in Nancy FxThe magic of Dynamic in Nancy Fx
The magic of Dynamic in Nancy Fx
 
Windows Phone 7 Development
Windows Phone 7 DevelopmentWindows Phone 7 Development
Windows Phone 7 Development
 
My Final Dissertation
My Final DissertationMy Final Dissertation
My Final Dissertation
 

Kürzlich hochgeladen

Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...Associazione Digital Days
 
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...Associazione Digital Days
 
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...Associazione Digital Days
 
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...Associazione Digital Days
 
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”Associazione Digital Days
 
ScrapeGraphAI: a new way to scrape context with AI
ScrapeGraphAI: a new way to scrape context with AIScrapeGraphAI: a new way to scrape context with AI
ScrapeGraphAI: a new way to scrape context with AIinfogdgmi
 

Kürzlich hochgeladen (6)

Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
 
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
 
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
 
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
 
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
 
ScrapeGraphAI: a new way to scrape context with AI
ScrapeGraphAI: a new way to scrape context with AIScrapeGraphAI: a new way to scrape context with AI
ScrapeGraphAI: a new way to scrape context with AI
 

Introduzione a Node.js

  • 1. COSE CHE NON TI ASPETTI DA JAVASCRIPT: NODE.JS
  • 2. Chi siamo Luciano  Colosio   SA  &  Dev  @  Save  The  Mom @unlucio Michele  Capra   Dev  @  OrangeCode @piccoloaiutante
  • 3. Cosa vedremo oggi Che  cos’è  Node.JS Dove  nasce ContesB  in  cui  usarlo Il  mondo  asincrono Demo  Live Deploy  su  un  servizio  free  (Heroku)
  • 4. Che cos’è Node.JS Javascirpt  runBme  basato  su  V8 Event  Driven  I/O  server-­‐side
  • 5. Da dove nasce Riprodurre  il  comportamento  in  “push”  mostrato  da  gmail Superare  i  limit  del  one-­‐way   BONUS DERIVATO Le  caraUerisBche  asincrone  di  JS  permeUono  una  gesBone  piu’   comoda  dell’I/O  che  costa  molto
  • 6. Da dove nasce Costo  dell’  I/O L1-­‐cache 3  cicli L2-­‐cache 14  cicli RAM 250  cicli Disco 41x10^6  cicli Network 240x10^6  cicli
  • 7. Gestire le richieste Sincrono:  gesBsco  una  richiesta  alla  volta Contro: ogni richiesta può (e fa!) da tappo alle altre
  • 8. Gestire le richieste Fork  del  processo Un  processo  nuovo  per  ogni  richiesta Contro:  non  scala  su  migliaia  di  connessioni (ameno  di  non  usare  migliaia  di  servers  ;))
  • 9. Gestire le richieste Un  Thread  nuovo  per  ogni  richiesta Contro:  la  macchina  potrebbe  non  avere   abbastanza  thread  disponibili,   programmazione  concorrente  è  complessa,   problemi  di  memoria
  • 10. Gestire le richieste La  scelta  di  node: Singolo  Thread Niente  parallelizzazione  del  codice
  • 11. Event Loop La  logica  nell’eventloop  risulta  bloccante: Devo  aUendere  che  i  task  terminino
  • 12. Soluzione: NON fare nulla nel maintherad Tutte le chiamate di I/O sono gestite come eventi asincroni, quindi non bloccanti. Utilizzare event driven development
  • 13. Event loop non e' necessario pre carrozzarsi per le perfomarnces (es: pre allocare thread per rispondere piu' velocemente). Minor spreco di memoria/risorse Minor rischio che il server vada in oveload
  • 14. Importante! Rispondere velocemente al client delegando a task attività che richiedono risorse ed i/o ad alta latenza Il focus è sulla risposta nel minor tempo possibile
  • 15. Async VS Sync //  Good:  write  files  asynchronously fs.writeFile('message.txt',  'Hello  Node',  funcBon  (err)  {    console.log("It's  saved  and  the  server  remains  responsive!"); }); //  BAD:  write  files  synchronously fs.writeFileSync('message.txt',  'Hello  Node'); console.log("It's  saved,  but  you  just  blocked  ALL  requests!");
  • 16. Esempio Architettura Database Client Web Engine DB User NODE NODE Disk Mass storage Logging facility (big slow disk) Le scritture dei logs non sono piu’ un problema!
  • 17. Esempio di contesti Web API Realtime web services (chat, push, peppertweet)
  • 18. Chi lo usa: 37signals Ajax.org - Cloud9 IDE eBay Trello Klout Linkedin Microsoft Voxer Yahoo! https://github.com/joyent/node/wiki/Projects,- Applications,-and-Companies-Using-Node
  • 19. JS: V8 in Node Stesso motore del browser ma: tutto gira nell’Event Loop non c’è DOM non c’è JQuery che tenga programmazione asincrona
  • 20. ESEMPI DI APPS Menamo  le  mani  in   pasta  :)
  • 21. App Esempio HUp  Hello  World,  la  piu’  semplice  node  app: var http = require('http'); var server = http.createServer(function (request, response) {   response.writeHead(200, {"Content-Type": "text/plain"});   response.end("Hello Worldn"); }); server.listen(8000); console.log("Server running at http://127.0.0.1:8000/");
  • 22. App Esempio Http Hello World, basta una lib ed ecco un servizio REST var  server  =  require('./lib/node-­‐router').getServer(); server.get("/json",  funcBon  (req,  res,  match)  {    return  {hello:  "World"}; }); server.get(new  RegExp("^/(.*)$"),  funcBon  hello(req,  res,  match)  {    return  "Hello  "  +  (match  ||  "World")  +  "!"; }); server.listen(8080);
  • 23. App Esempio Vi  ricordate  IRC? NO?!?!?! Ok,  ce  l’aspeUavamo  ;P Oggi  ci  ispireremo  al  passato  per  un  twiUer  bot: TWITVIA
  • 24. App Esempio Get  the  code: hUps://github.com/unlucio/tvitvia
  • 25. App Esempio: Struttura Moduli Heroku  Process DescriUore File  (opBonal) per  npm Main  File
  • 26. App Esempio: npm install Moduli  installaB {   "name":  "Twitvia",   "descripBon":  "Vintage  trivia  bot",   "version":  "0.0.1",   "dependencies":  {     "twit"  :  "0.1.2",     "underscore":  "1.3.1",     "db-­‐mysql":  "0.7.6"   },   "engines":  {     "node":  ">=  0.6.0"   } Diamogli  un  nome  sensato  :)
  • 27. App Esempio Ovviamente  possiamo aggiungere  directory a  nostro  piacimento per  parB  delle  nostra  app
  • 28. App Esempio: def. lib var  Twit  =  require('twit'); module.exports  =  (funcBon(twiUerClient)  {     twiUerClient  =  funcBon(datas)  {};     twiUerClient.prototype.publishTweet  =  funcBon  (message)  {};   twiUerClient.prototype.sendMenBon  =  funcBon  (to,  message)  {};   twiUerClient.prototype.sendDM  =  funcBon  (to,  message)  {};     twiUerClient.prototype.followUser  =  funcBon  (user)  {};     return  twiUerClient; })();
  • 29. App Esempio: use lib var  TweUerClient  =  require('./lib/twiUerClient'), var  tClient  =  new  TweUerClient({   consumer_key:                  'getItFromTwiUer',   consumer_secret:            'getItFromTwiUer',   access_token:                  'getItFromTwiUer',   access_token_secret:    'getItFromTwiUer', }); funcBon  getCommand(tweet)  { [...] } tClient.T.stream('user',[],  funcBon  (stream)  {    stream.on('tweet',  funcBon  (tweet)  {   getCommand(tweet)    }); });
  • 30. App Esempio: model objs var  _  =  require('underscore'); module.exports  =  (funcBon(quesBons)  {     quesBons  =  funcBon(db,  tweeterClient)  {     this.db  =  db;     this.tweeterClient  =  tweeterClient;   };     quesBons.prototype.publishRandom  =  funcBon()  {};     quesBons.prototype.getRandom  =  funcBon  (quesBonsList)  {};     quesBons.prototype.selectAll  =  funcBon(callback)  {};     quesBons.prototype.setAnswered  =  funcBon(refTweetID,   callback)  {}     return  quesBons; })();
  • 31. App Esempio: model objs module.exports  =  (funcBon(answers)  {     answers  =  funcBon(db,  tweeterClient)  {     this.db  =  db;     this.tweeterClient  =  tweeterClient;   };     answers.prototype.checkMatch  =    funcBon  (refTweetID,   userAnswer,  callback)  {   };   return  answers; })();
  • 32. App Esempio: model objs module.exports  =  (funcBon(users)  {     users  =  funcBon(db,  tweeterClient)  {     this.db  =  db;     this.tweeterClient  =  tweeterClient;   };     users.prototype.find  =  funcBon(userName,  callback)  {};     users.prototype.add  =  funcBon(userName,  callback)  {};     users.prototype.capture  =  funcBon(userName,  callback)  {};     users.prototype.scorePoint  =  funcBon(userName,  callback)  {};     users.prototype._updateScore  =  funcBon(userID,  thePlayer,  callback){};     return  users; })();
  • 33. App Esempio: together var  mysql  =  require('db-­‐mysql'),   TweUerClient  =  require('./lib/twiUerClient'),   Users  =  require('./model/users'),   QuesBons  =  require('./model/quesBons'),   Answers  =  require('./model/answers'); var  myDb  =  new  mysql.Database({ [connecBon  datas] }); [...] var  tClient  =  new  TweUerClient({ [api  datas] }); var  users  =  new  Users(myDb,  tClient); var  quesBons  =  new  QuesBons(myDb,  tClient); var  answers  =  new  Answers(myDb,  tClient); tClient.T.stream('user',[],  funcBon  (stream)  {    stream.on('tweet',  funcBon  (tweet)  {   getCommand(tweet)    }); });
  • 34. Deploy & hosting heroku  login Compiliamo  il  Procfile web:  node  <mainscript.js> git  init git  add  . git  commit  -­‐m  “<commento>” heroku  create  -­‐-­‐stack  cedar git  push  heroku  master heroku  ps:scale  web=1
  • 35. Nella realta’ Un  esempio  famoso  ed  eclatante   di  uBlizzo  di  node: Linkedin!
  • 36. Dove lo usano? Linkedin  usa  node  come  middle  layer  tra  i  server  di  backend  ed  i   client  mobile Mobile client NodeJs backend instances server Mobile Client
  • 37. I 10 consigli per node.js Evitare  il  codice  sincorono No  socket  polling! Non  usare  node.js  per  servire  asset  staBci Delegare  il  rendering  al  client Usare  gzip  tra  i  vari  componenB Parallelizzare  al  piu’  possibile! Se  possibile:  NO  SESSIONS Usare  moduli  binari  anzicche’  in  javascript Usare  javascript  standard  anzicche’  librerie  faUe  per  i  client Tenere  il  codice  piccolo  e  compaUo
  • 38. Grazie per l’attenzione se  volete,  trollateci  su  twiUer @unlucio  -­‐  @piccoloaiutante
  • 39. Un po’ di spam ;) hUp://nodejsconf.it hUp://www.webdebs.org/
  • 40. Cerco Dev Save the Mom cerca sviluppatori da integrare nel nostro team! :) Skills: Web MobileWeb Mobile applications (iOS, wp7, android, balckberry) Scrivi  a: lucio@savethemom.com