SlideShare una empresa de Scribd logo
1 de 36
Ricardo Silva

              Degree in Computer Science @ ISTEC
MSc Computation and Medical Instrumentation @ ISEP

                Software Developer @ Shortcut, Lda

                     (blog): http://blog.ricardosilva.pt

                      (email): nodejs@ricardosilva.pt
Event-driven I/O
    server-side
     JavaScript
environment based
   on V8 Engine
JavaScript
(examples)
JavaScript: Array vs Object
                                     Instantiation

• Array
var ar = []; /* ou new Array(); */




• Object
var carColors = {}; /* ou new Object();*/
JavaScript: Array vs Object
                              Add

• Array
var ar = [];
ar[0] = 'January';
Ou
ar.push(‘March’);


• Object
var carColors = {};
carColors['BMW'] = 'Red';
carColors['Audi'] = 'Blue';
JavaScript: Array vs Object
                            Remove

• Array
ar.splice(0,1);




• Object
delete carColors['BMW'];
JavaScript: Array vs Object
                                               Lookup

• Array
var ar = [];
for (var i = 0; i < carColors.length; i++) {
 alert( ar[i] );
};
Ou
var month = ar[0];
• Object
var carColors = {};
for (var i in carColors) {
 alert( carColors[i] );
};
Ou
var colorOfBWM = carColors[‘BMW’];
JavaScript: callback Functions

var state;

function setstate (pbool, difCallBack) {
         if (state != pbool)
                    return (state = pbool), difCallBack(state);
}

setstate(true, function(s){
          alert(s);
});




       “We can keep on doing other things while waiting for the callback to be called.”
JavaScript: Events
var eventHandlers = new Object();

 this.registerEvent=function(name,callback){
    var eh=(eventHandlers[name])?eventHandlers[name]:(eventHandlers[name]=[]);
    eh[eh.length]=callback;
 };

 this.unregisterEvent=function(name,callback){
    var eh=eventHandlers[name];
    if("object"==typeof eh)
        for(var h in eh)
           if(eh[h]===callback){
              delete eh[h];
              return;
           }
 };
JavaScript: Events

this.triggerEvent=function(name,args){
     var eh=eventHandlers[name];
     if("object"==typeof eh) for(var h in eh) eh[h](args);
  };



  this.ring=function(evDelegate){ xpto.registerEvent('ring',evDelegate); };



  function onRing(args){
    xpto.triggerEvent('ring',args);
  }
Node.js
Node.js: What is?


“   Node.js is a platform built on Chrome's JavaScript runtime for
    easily building fast, scalable network applications. Node.js uses
    an event-driven, non-blocking I/O model that makes it
    lightweight and efficient, perfect for data-intensive real-time
    applications that run across distributed devices.

                                                                   ”
Node.js: Companies using node!




•   LinkedIn(Mobile WebApp)      • Yahoo!Mail
•   Ebay(Data retrieval gateway) • Rackspace(Cloud kick monitoring)
•   GitHub(for Downloads)        • Voxxer(Push to Talk mobile app)
•   Palm/HP(in WebOS)
Node.js: How to install?

•   $ git clone  git://github.com/joyent/node.git
•   $ cd node
•   $ git checkout v0.6.0
•   $ ./configure
•   $ sudo make install


                   (windows users: download node.exe)
Node.js
     DEMO
Node.js


“ Come on…, server side
JS has been around since
        1996 …”
Node.js


“ …what is so special
   about node? ”
Node.js: Seep


                   Speed
• Node can do ~6000 http requests / sec per CPU core
• It is no problem to handle thousands of concurrent
  connections which are moderately active
Node.js: V8 JS Engine


    V8 JavaScript Engine
• Developed by Google in Aarhus, Denmark for Google
  Chrome
• Translates JavaScript in Assembly Code
• Crankshaft JIT (enabled in 0.6.0 by default)
Node.js: Non-Blocking I/O

                        Non-Blocking I/O
Blocking:
var fs = require('fs');
var one = fs.readFileSync('one.txt','utf-8');
console.log('Read file one');
var two = fs.readFileSync('two.txt','utf-8');
console.log('Read file two');

Non-Blocking:
var fs = require('fs');
fs.readFile('one.txt','utf-8',function(err,data) {
            console.log('Read file one');
});

fs.readFile('two.txt','utf-8',function(err,data) {
           console.log('Read file two');
});


                                                     DEMO
Node.js: Non-Blocking I/O


             Blocking I/O
Read one.txt (20ms)

                        Read two.txt (10ms)

Total duration (30ms)
Node.js: Non-Blocking I/O


        Non-Blocking I/O
Read one.txt (20ms)

Read two.txt (10ms)

Total duration (20ms)
Node.js: Non-Blocking I/O


         Non-Blocking I/O
• Close to ideal for high concurrency / high through
  put, single execution stack
• Forces you to write more efficient code by
  parallelizing your I/O
• Feels pretty much like AJAX in the browser
Node - Modules
        DEMO
Websockets
Websockets: What is?

“The WebSocket specification—developed as part of the HTML5
initiative—introduced the WebSocket JavaScript interface, which
defines a full-duplex single socket connection over which
messages can be sent between client and server. The WebSocket
standard simplifies much of the complexity around bi-
directional web communication and connection management.

WebSocket represents the next evolutionary step in web
communication compared to Comet and Ajax. However, each
technology has its own unique capabilities. Learn how these
technologies vary so you can make the right choice.”
Websockets: What is?

• Persistent connection between browser / server
• The solution of the problem with RT at browser side
var ws = new WebSocket(url);
ws.onopen = function() {
          // When the connection opens
};

ws.onmessage = function() {
         // When the server sends data
};

ws.onclose = function() {
          // When the connection is closed
};

ws.send ('Hi all!');

ws.close();
Websockets: Compatibility
Websockets: Compatibility

•   We can use different transports:
•   HTML5 WebSockets
•   Flash Socket
•   AJAX Long Polling
•   Forever Iframe
Socket.io
Socket.io

“ Socket.io aims to make realtime apps possible in
   every browser and mobile device, blurring the
    differences between the different transport
    mechanism. It’s care-free realtime 100% in
                    JavaScript.”
Socket.io: transports?

•   Web Socket
•   Flash Socket
•   HTML File
•   XHR Polling
•   JSONP Polling
Socket.io: How to install?




  npm install socket.io
Socket.io
      DEMO
Socket.io: Other methods?

//broadcast a message to all sockets
socket.broadcast.emit('event');

//no need to internally buffer this msg
socket.volatile.emit('event');

//broadcast, nut only to people in this room
socket.broadcast.to('room').emit('event');

//broadcast to everyone
io.sockets.emit('event');
io.sockets.send('hello');
Questions?
      (blog): http://blog.ricardosilva.pt

      (email): nodejs@ricardosilva.pt

Más contenido relacionado

La actualidad más candente

Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & ExpressChristian Joudrey
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming Tom Croucher
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...Codemotion
 
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...Tom Croucher
 

La actualidad más candente (20)

Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 
NodeJS
NodeJSNodeJS
NodeJS
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
Node ppt
Node pptNode ppt
Node ppt
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
Node js beginner
Node js beginnerNode js beginner
Node js beginner
 
Node.js
Node.jsNode.js
Node.js
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
 
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
JavaScript is the new black - Why Node.js is going to rock your world - Web 2...
 

Similar a Event-driven IO server-side JavaScript environment based on V8 Engine

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.jssoft-shake.ch
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
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.Mike Brevoort
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
Introducing to node.js
Introducing to node.jsIntroducing to node.js
Introducing to node.jsJeongHun Byeon
 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureSimon Willison
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Asher Martin
 
Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiJackson Tian
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.jsguileen
 
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...GITS Indonesia
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 

Similar a Event-driven IO server-side JavaScript environment based on V8 Engine (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
 
NodeJS
NodeJSNodeJS
NodeJS
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
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.
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
Introducing to node.js
Introducing to node.jsIntroducing to node.js
Introducing to node.js
 
Node azure
Node azureNode azure
Node azure
 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big Picture
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2
 
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
 
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...
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 

Último

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Último (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

Event-driven IO server-side JavaScript environment based on V8 Engine

  • 1. Ricardo Silva Degree in Computer Science @ ISTEC MSc Computation and Medical Instrumentation @ ISEP Software Developer @ Shortcut, Lda (blog): http://blog.ricardosilva.pt (email): nodejs@ricardosilva.pt
  • 2. Event-driven I/O server-side JavaScript environment based on V8 Engine
  • 4. JavaScript: Array vs Object Instantiation • Array var ar = []; /* ou new Array(); */ • Object var carColors = {}; /* ou new Object();*/
  • 5. JavaScript: Array vs Object Add • Array var ar = []; ar[0] = 'January'; Ou ar.push(‘March’); • Object var carColors = {}; carColors['BMW'] = 'Red'; carColors['Audi'] = 'Blue';
  • 6. JavaScript: Array vs Object Remove • Array ar.splice(0,1); • Object delete carColors['BMW'];
  • 7. JavaScript: Array vs Object Lookup • Array var ar = []; for (var i = 0; i < carColors.length; i++) { alert( ar[i] ); }; Ou var month = ar[0]; • Object var carColors = {}; for (var i in carColors) { alert( carColors[i] ); }; Ou var colorOfBWM = carColors[‘BMW’];
  • 8. JavaScript: callback Functions var state; function setstate (pbool, difCallBack) { if (state != pbool) return (state = pbool), difCallBack(state); } setstate(true, function(s){ alert(s); }); “We can keep on doing other things while waiting for the callback to be called.”
  • 9. JavaScript: Events var eventHandlers = new Object(); this.registerEvent=function(name,callback){ var eh=(eventHandlers[name])?eventHandlers[name]:(eventHandlers[name]=[]); eh[eh.length]=callback; }; this.unregisterEvent=function(name,callback){ var eh=eventHandlers[name]; if("object"==typeof eh) for(var h in eh) if(eh[h]===callback){ delete eh[h]; return; } };
  • 10. JavaScript: Events this.triggerEvent=function(name,args){ var eh=eventHandlers[name]; if("object"==typeof eh) for(var h in eh) eh[h](args); }; this.ring=function(evDelegate){ xpto.registerEvent('ring',evDelegate); }; function onRing(args){ xpto.triggerEvent('ring',args); }
  • 12. Node.js: What is? “ Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. ”
  • 13. Node.js: Companies using node! • LinkedIn(Mobile WebApp) • Yahoo!Mail • Ebay(Data retrieval gateway) • Rackspace(Cloud kick monitoring) • GitHub(for Downloads) • Voxxer(Push to Talk mobile app) • Palm/HP(in WebOS)
  • 14. Node.js: How to install? • $ git clone git://github.com/joyent/node.git • $ cd node • $ git checkout v0.6.0 • $ ./configure • $ sudo make install (windows users: download node.exe)
  • 15. Node.js DEMO
  • 16. Node.js “ Come on…, server side JS has been around since 1996 …”
  • 17. Node.js “ …what is so special about node? ”
  • 18. Node.js: Seep Speed • Node can do ~6000 http requests / sec per CPU core • It is no problem to handle thousands of concurrent connections which are moderately active
  • 19. Node.js: V8 JS Engine V8 JavaScript Engine • Developed by Google in Aarhus, Denmark for Google Chrome • Translates JavaScript in Assembly Code • Crankshaft JIT (enabled in 0.6.0 by default)
  • 20. Node.js: Non-Blocking I/O Non-Blocking I/O Blocking: var fs = require('fs'); var one = fs.readFileSync('one.txt','utf-8'); console.log('Read file one'); var two = fs.readFileSync('two.txt','utf-8'); console.log('Read file two'); Non-Blocking: var fs = require('fs'); fs.readFile('one.txt','utf-8',function(err,data) { console.log('Read file one'); }); fs.readFile('two.txt','utf-8',function(err,data) { console.log('Read file two'); }); DEMO
  • 21. Node.js: Non-Blocking I/O Blocking I/O Read one.txt (20ms) Read two.txt (10ms) Total duration (30ms)
  • 22. Node.js: Non-Blocking I/O Non-Blocking I/O Read one.txt (20ms) Read two.txt (10ms) Total duration (20ms)
  • 23. Node.js: Non-Blocking I/O Non-Blocking I/O • Close to ideal for high concurrency / high through put, single execution stack • Forces you to write more efficient code by parallelizing your I/O • Feels pretty much like AJAX in the browser
  • 26. Websockets: What is? “The WebSocket specification—developed as part of the HTML5 initiative—introduced the WebSocket JavaScript interface, which defines a full-duplex single socket connection over which messages can be sent between client and server. The WebSocket standard simplifies much of the complexity around bi- directional web communication and connection management. WebSocket represents the next evolutionary step in web communication compared to Comet and Ajax. However, each technology has its own unique capabilities. Learn how these technologies vary so you can make the right choice.”
  • 27. Websockets: What is? • Persistent connection between browser / server • The solution of the problem with RT at browser side var ws = new WebSocket(url); ws.onopen = function() { // When the connection opens }; ws.onmessage = function() { // When the server sends data }; ws.onclose = function() { // When the connection is closed }; ws.send ('Hi all!'); ws.close();
  • 29. Websockets: Compatibility • We can use different transports: • HTML5 WebSockets • Flash Socket • AJAX Long Polling • Forever Iframe
  • 31. Socket.io “ Socket.io aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanism. It’s care-free realtime 100% in JavaScript.”
  • 32. Socket.io: transports? • Web Socket • Flash Socket • HTML File • XHR Polling • JSONP Polling
  • 33. Socket.io: How to install? npm install socket.io
  • 34. Socket.io DEMO
  • 35. Socket.io: Other methods? //broadcast a message to all sockets socket.broadcast.emit('event'); //no need to internally buffer this msg socket.volatile.emit('event'); //broadcast, nut only to people in this room socket.broadcast.to('room').emit('event'); //broadcast to everyone io.sockets.emit('event'); io.sockets.send('hello');
  • 36. Questions? (blog): http://blog.ricardosilva.pt (email): nodejs@ricardosilva.pt