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?

WPO: Ottimizzazione step-by-step del front-end di un e-commerce
WPO: Ottimizzazione step-by-step del front-end di un e-commerceWPO: Ottimizzazione step-by-step del front-end di un e-commerce
WPO: Ottimizzazione step-by-step del front-end di un e-commerceFrancesco Terenzani
 
Il Web orientato al futuro: Express, Angular e nodeJS
Il Web orientato al futuro: Express, Angular e nodeJS Il Web orientato al futuro: Express, Angular e nodeJS
Il Web orientato al futuro: Express, Angular e nodeJS Eugenio Minardi
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automationDotNetCampus
 
Blazor ha vinto? Storie di casi reali
Blazor ha vinto? Storie di casi realiBlazor ha vinto? Storie di casi reali
Blazor ha vinto? Storie di casi realiAndrea Dottor
 
Agileday2013 pratiche agili applicate all'infrastruttura
Agileday2013 pratiche agili applicate all'infrastrutturaAgileday2013 pratiche agili applicate all'infrastruttura
Agileday2013 pratiche agili applicate all'infrastrutturaXPeppers
 
Sviluppo Web con React e Delphi - Seminario Delphi Day 2016, Piacenza
Sviluppo Web con React e Delphi - Seminario Delphi Day 2016, PiacenzaSviluppo Web con React e Delphi - Seminario Delphi Day 2016, Piacenza
Sviluppo Web con React e Delphi - Seminario Delphi Day 2016, PiacenzaMarco Breveglieri
 
Applicazioni Web ultra-performanti con Vue.js e Delphi
Applicazioni Web ultra-performanti con Vue.js e DelphiApplicazioni Web ultra-performanti con Vue.js e Delphi
Applicazioni Web ultra-performanti con Vue.js e DelphiMarco Breveglieri
 
Delphi & Dintorni Webinar - Diventa un mago del Testing
Delphi & Dintorni Webinar - Diventa un mago del TestingDelphi & Dintorni Webinar - Diventa un mago del Testing
Delphi & Dintorni Webinar - Diventa un mago del TestingMarco Breveglieri
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automationAntonio Liccardi
 
Phpday 2009 php e java
Phpday 2009 php e javaPhpday 2009 php e java
Phpday 2009 php e javaMatteo Baccan
 

Was ist angesagt? (14)

WPO: Ottimizzazione step-by-step del front-end di un e-commerce
WPO: Ottimizzazione step-by-step del front-end di un e-commerceWPO: Ottimizzazione step-by-step del front-end di un e-commerce
WPO: Ottimizzazione step-by-step del front-end di un e-commerce
 
Il Web orientato al futuro: Express, Angular e nodeJS
Il Web orientato al futuro: Express, Angular e nodeJS Il Web orientato al futuro: Express, Angular e nodeJS
Il Web orientato al futuro: Express, Angular e nodeJS
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automation
 
Making Chatbots
Making ChatbotsMaking Chatbots
Making Chatbots
 
Blazor ha vinto? Storie di casi reali
Blazor ha vinto? Storie di casi realiBlazor ha vinto? Storie di casi reali
Blazor ha vinto? Storie di casi reali
 
Web frameworks
Web frameworksWeb frameworks
Web frameworks
 
Agileday2013 pratiche agili applicate all'infrastruttura
Agileday2013 pratiche agili applicate all'infrastrutturaAgileday2013 pratiche agili applicate all'infrastruttura
Agileday2013 pratiche agili applicate all'infrastruttura
 
Sviluppo Web con React e Delphi - Seminario Delphi Day 2016, Piacenza
Sviluppo Web con React e Delphi - Seminario Delphi Day 2016, PiacenzaSviluppo Web con React e Delphi - Seminario Delphi Day 2016, Piacenza
Sviluppo Web con React e Delphi - Seminario Delphi Day 2016, Piacenza
 
Applicazioni Web ultra-performanti con Vue.js e Delphi
Applicazioni Web ultra-performanti con Vue.js e DelphiApplicazioni Web ultra-performanti con Vue.js e Delphi
Applicazioni Web ultra-performanti con Vue.js e Delphi
 
Delphi & Dintorni Webinar - Diventa un mago del Testing
Delphi & Dintorni Webinar - Diventa un mago del TestingDelphi & Dintorni Webinar - Diventa un mago del Testing
Delphi & Dintorni Webinar - Diventa un mago del Testing
 
Infrastructure as Data
Infrastructure as DataInfrastructure as Data
Infrastructure as Data
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automation
 
Phpday 2009 php e java
Phpday 2009 php e javaPhpday 2009 php e java
Phpday 2009 php e java
 
DevOps Jump Start
DevOps Jump StartDevOps Jump Start
DevOps Jump Start
 

Ä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
 
Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Martino Bordin
 
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
 
E suap - tecnologie client
E suap - tecnologie client E suap - tecnologie client
E suap - tecnologie client Sabino Labarile
 
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
 

Ä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
 
Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3
 
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)
 
Php mysql3
Php mysql3Php mysql3
Php mysql3
 
E suap - tecnologie client
E suap - tecnologie client E suap - tecnologie client
E suap - tecnologie client
 
Il web 2.0
Il web 2.0Il web 2.0
Il web 2.0
 
Many Designs Elements
Many Designs ElementsMany Designs Elements
Many Designs Elements
 
Hexagonal architecture ita
Hexagonal architecture itaHexagonal architecture ita
Hexagonal architecture ita
 
Applicazioni native in java
Applicazioni native in javaApplicazioni native in java
Applicazioni native in java
 
Yagwto
YagwtoYagwto
Yagwto
 
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
 

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