SlideShare una empresa de Scribd logo
1 de 35
Descargar para leer sin conexión
cocktail d’expérience informatiques
             Genève 3 & 4 octobre 2011
                   Seconde édition




Auteur    M. LEMEE & R. MATON
  Track   Incubateur
Session   Node.js
Node.js

http://nodejs.org
Co-founder of Duchess France
http://www.java-freelance.fr
@MathildeLemee




                    Creator of Web Tambouille
                   http://www.web-tambouille.fr
                                     @rmat0n
Summary
•    What ? Why ?
•    Non blocking API example
•    Event programming model
•    Express, Socket.IO and modules
•    Mini Hands On
•    Unit Test
•    Limits
What is Node ?

                Server-side Javascript

  Node.js javascript implementation is V8 Javascript
              Engine (Google Chrome)

Provide an easy way to build scalable network programs

                   Non blocking I/O

                   Single Threaded

                Written by Ryah Dahl
What is Node ?




    http://codingrelic.geekhold.com/2010/08/nodejs-from-30000-feet.html
What is Node ?

var http = require('http');

http.createServer(function (request, response) {
    res.writeHead(200, {"Content-Type": "text/plain"});
    res.end("Hello Worldn");
}).listen(1337, "127.0.0.1");

console.log("Server running at http://127.0.0.1:1337/");

~$ node server.js
~$ curl http://127.0.0.1:1337/
Why using Node ?

•  Ryan Dahl: "Node.js project: To provide a purely evented,
   non-blocking infrastructure to script highly concurrent
   programs" (http://yuilibrary.com/theater/ryan-dahl/dahl-node/)
•  Scalable software
                    •  Non blocking I/O
•  Same language and share code between server side and
   client side

•  JSON friendly (web, server, database...)
Blocking API example



  print("hello");

  sleep(2000);      blocked!!

  print("world");
Non blocking API example



var data = File.read("file.txt");
...
// Here you have to wait... maybe a lot...
...
// And your thread is still alive... doing nothing...
...
parseResult(data);
Non blocking API example



var data = File.read("file.txt", function(data) {
    parseResult(data);
});

// Here, your thread is alive and continue working !!!
myOtherCode();
Event programming model



•  Events are the heart of Node.js


•  Everything is event based


•  You can create yours own events
Event programming model
              Sample


dummyEmitter.emit('myCustomEvent', 'myValue');



dummyReceiver.on('myCustomEvent', function(data){
    console.log(data);
});
Event programming model
                   Sample
SERVEUR
socket.emit('news', { hello: 'world' });

socket.on('event', function (data) {
    console.log(data);
});


CLIENT
socket.on('news', function (data) {
console.log(data);
socket.emit('event', { my: 'data' });
});
NPM
Modules

             Node Boilerplate

             Event Emitter 2

               Underscore

                  Vows

               Coffeemate

             Node Inspector

Spotify, Twitter, Gravatar, Dropbox, AWS,

https://github.com/joyent/node/wiki/modules
Express
              Web Framework

        Inspired by Sinatra (Ruby)

Systèmes de templates (jade, Haml, EJS...)


      var app = express.createServer();

      app.get('/', function(req, res) {
          res.send('Hello World');
      });

      app.listen(3000);
Express
app.configure('development', function() {
    server.set('views', __dirname + '/views');
    server.set('view engine', 'ejs');
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler({ dumpExceptions: true,
                                      showStack: true }));
});

app.configure('production', function() {
    server.set('views', __dirname + '/views');
    server.set('view engine', 'ejs');
    var aYear = 31557600000;
    app.use(express.static(__dirname + '/public', { 'maxAge': aYear }));
    app.use(express.errorHandler());
});
Express
app.get('/user/:id', function(req, res) {
    res.send('user' + req.params.id);
});

'/users/:id?'
   /users/5
   /users

'/user/:id.:format?'
   /user/12
   /user/12.json

'/user/:id/:operation?'
   /user/1
   /user/1/edit

'/files/*'
     /files/jquery.js
     /files/javascripts/jquery.js
Socket.IO - Why ?


WebSocket : Firefox 4, Chrome 4, Opera 10.70, and Safari 5.

    Asynchronous communication from client to server.

                AJAX - XmlHttpRequest ?

                Flash / AJAX Long Polling
                      Disconnection
Socket.IO - How

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
   io.sockets.emit('info', 'a player join the game');

      socket.on('chat', function (msg) {
          console.log('send a chat', msg);
      });

      socket.on('disconnect', function () {
          sockets.emit('user disconnected');
      });
});
Socket.IO - How

<script>
 var socket = io.connect('http://localhost');

 socket.on('connect', function () {
    socket.on('info', function (data) {
       alert(data);
    });
 });

  socket.emit('chat',myMessage);
</script>
Socket.IO - How
•  custom messages :
       socket.emit('my custom event',{data:xxx});
•  volatile :
      socket.volatile.emit('tweet',tweet);
•  acknoledgements
•  broadcast :
      socket.broadcast.emit('hello','world');
•  room :
      socket.join('justin bieber fans')
•  send a message in a room :
      io.sockets.in('my room').emit('hello','world');
•  storing data :
      socket.set('name','Mathilde',function () { //callback });
Modules

Create yours !

hello.js
var world = function() {
   alert("helloworld");
};
exports.world = world;

server.js
var hello = require("./hello")
hello.world();
Mini Hands On




Go Mathilde o/
Tests
                                                          MLE
•  Unit tests
   o  Node.js provides its own assert module
         http://nodejs.org/docs/v0.5.6/api/assert.html

    o  QUnit (JQuery) http://docs.jquery.com/Qunit
    o  NodeUnit https://github.com/caolan/nodeunit
    o  Expresso https://github.com/visionmedia/expresso
•  Integration tests
    o  Zombie.js http://zombie.labnotes.org
•  Behavior Driven Development
    o  vowsjs http://vowsjs.org/
    o  jasmine-node https://github.com/mhevery/jasmine-node

•  https://github.com/joyent/node/wiki/modules#wiki-testing
Unit Tests with QUnit

<script>
$(document)
    .ready(
       function() {
         module("1. Game");
            test(
                "Connais la valeur du joueur suivant en fonction du joueur actuel",
                function() {
                     game = new Game();
                     game.take(3);
                     game.take(1);
                     equals(game.otherPlayer(), "O", "O est le joueur précédent");
            });
...
</script>
Unit Tests with QUnit
Limits


- Cryptic error messages
node.js:50 throw e; ^
 Error: ECONNREFUSED, Connection refused at
IOWatcher.callback (net:870:22) at node.js:607:9



client.on("error", function (err) {
    console.log("Error " + err);
});
Limits

- Cryptic error messages

- Only one thread (it is also an advantage)
- Can be difficult to read

- Non async lib/third party decrease perfs

- IDE, Tooling, Debugger, Profiler

- How to choose a good module ?
Node REPL


~$ node
> 1+2
  3
> [1, 2, 3].splice(1,2)
 [2, 3]
> process.pid
 2998
> ...
Links

Quick tour : http://www.slideshare.net/the_undefined/nodejs-a-quick-tour

Node + Websockets :
http://www.slideshare.net/the_undefined/nodejs-a-quick-tour

Node beginner : http://nodebeginner.org/

The Node Beginner Book :
https://github.com/ManuelKiessling/NodeBeginnerBook

Hands on Node.js : http://nodetuts.com/handson-nodejs-book.html

Node.js in Action (été 2012): http://www.manning.com/cantelon

Más contenido relacionado

La actualidad más candente

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
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
Tom Croucher
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 

La actualidad más candente (20)

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
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
What is nodejs
What is nodejsWhat is nodejs
What is nodejs
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
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
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 

Similar a soft-shake.ch - Hands on Node.js

09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
 
Server Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yetServer Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yet
Tom Croucher
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.js
guileen
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
Mohammad Qureshi
 

Similar a soft-shake.ch - Hands on Node.js (20)

Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
NodeJS
NodeJSNodeJS
NodeJS
 
Node azure
Node azureNode azure
Node azure
 
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
 
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.
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
5.node js
5.node js5.node js
5.node js
 
Node.js
Node.jsNode.js
Node.js
 
Server Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yetServer Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yet
 
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
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 

Más de soft-shake.ch

soft-shake.ch - Déploiement continu sur le cloud avec SlipStream
soft-shake.ch - Déploiement continu sur le cloud avec SlipStreamsoft-shake.ch - Déploiement continu sur le cloud avec SlipStream
soft-shake.ch - Déploiement continu sur le cloud avec SlipStream
soft-shake.ch
 
soft-shake.ch - An introduction to social architecture
soft-shake.ch - An introduction to social architecturesoft-shake.ch - An introduction to social architecture
soft-shake.ch - An introduction to social architecture
soft-shake.ch
 

Más de soft-shake.ch (20)

soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
 
soft-shake.ch - Introduction to HTML5
soft-shake.ch - Introduction to HTML5soft-shake.ch - Introduction to HTML5
soft-shake.ch - Introduction to HTML5
 
soft-shake.ch - WebMatrix: Your Web Made Easy
soft-shake.ch - WebMatrix: Your Web Made Easysoft-shake.ch - WebMatrix: Your Web Made Easy
soft-shake.ch - WebMatrix: Your Web Made Easy
 
soft-shake.ch - Domotique et robotique avec le micro Framework .NET
soft-shake.ch - Domotique et robotique avec le micro Framework .NETsoft-shake.ch - Domotique et robotique avec le micro Framework .NET
soft-shake.ch - Domotique et robotique avec le micro Framework .NET
 
soft-shake.ch - Clojure Values
soft-shake.ch - Clojure Valuessoft-shake.ch - Clojure Values
soft-shake.ch - Clojure Values
 
soft-shake.ch - Data grids and Data Grids
soft-shake.ch - Data grids and Data Gridssoft-shake.ch - Data grids and Data Grids
soft-shake.ch - Data grids and Data Grids
 
soft-shake.ch - Data grids and Data Caching
soft-shake.ch - Data grids and Data Cachingsoft-shake.ch - Data grids and Data Caching
soft-shake.ch - Data grids and Data Caching
 
soft-shake.ch - JBoss AS 7, la révolution
soft-shake.ch - JBoss AS 7, la révolutionsoft-shake.ch - JBoss AS 7, la révolution
soft-shake.ch - JBoss AS 7, la révolution
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
soft-shake.ch - Tests d'intégration JavaEE avec Arquillian
soft-shake.ch - Tests d'intégration JavaEE avec Arquilliansoft-shake.ch - Tests d'intégration JavaEE avec Arquillian
soft-shake.ch - Tests d'intégration JavaEE avec Arquillian
 
soft-shake.ch - Un zeste d’Erlang dans le shaker!
soft-shake.ch - Un zeste d’Erlang dans le shaker!soft-shake.ch - Un zeste d’Erlang dans le shaker!
soft-shake.ch - Un zeste d’Erlang dans le shaker!
 
soft-shake.ch - Déploiement continu sur le cloud avec SlipStream
soft-shake.ch - Déploiement continu sur le cloud avec SlipStreamsoft-shake.ch - Déploiement continu sur le cloud avec SlipStream
soft-shake.ch - Déploiement continu sur le cloud avec SlipStream
 
soft-shake.ch - An introduction to social architecture
soft-shake.ch - An introduction to social architecturesoft-shake.ch - An introduction to social architecture
soft-shake.ch - An introduction to social architecture
 
soft-shake.ch - De Hermes RUP à Hermes Scrum
soft-shake.ch - De Hermes RUP à Hermes Scrumsoft-shake.ch - De Hermes RUP à Hermes Scrum
soft-shake.ch - De Hermes RUP à Hermes Scrum
 
soft-shake.ch - Stewardship et motivation
soft-shake.ch - Stewardship et motivationsoft-shake.ch - Stewardship et motivation
soft-shake.ch - Stewardship et motivation
 
soft-shake.ch - Agile qu'es aco : scrum xp lean
soft-shake.ch - Agile qu'es aco : scrum xp leansoft-shake.ch - Agile qu'es aco : scrum xp lean
soft-shake.ch - Agile qu'es aco : scrum xp lean
 
soft-shake.ch - Documentation et agilité
soft-shake.ch - Documentation et agilitésoft-shake.ch - Documentation et agilité
soft-shake.ch - Documentation et agilité
 
soft-shake.ch - Agilité = discipline et rigueur ?
soft-shake.ch - Agilité = discipline et rigueur ?soft-shake.ch - Agilité = discipline et rigueur ?
soft-shake.ch - Agilité = discipline et rigueur ?
 
soft-shake.ch - Transition agile & Accompagnement au changement
soft-shake.ch - Transition agile & Accompagnement au changementsoft-shake.ch - Transition agile & Accompagnement au changement
soft-shake.ch - Transition agile & Accompagnement au changement
 
soft-shake.ch - Agilité et Testing: de l'intérêt d'une démarche structurée
soft-shake.ch - Agilité et Testing: de l'intérêt d'une démarche structuréesoft-shake.ch - Agilité et Testing: de l'intérêt d'une démarche structurée
soft-shake.ch - Agilité et Testing: de l'intérêt d'une démarche structurée
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 

soft-shake.ch - Hands on Node.js

  • 1. cocktail d’expérience informatiques Genève 3 & 4 octobre 2011 Seconde édition Auteur M. LEMEE & R. MATON Track Incubateur Session Node.js
  • 2.
  • 4. Co-founder of Duchess France http://www.java-freelance.fr @MathildeLemee Creator of Web Tambouille http://www.web-tambouille.fr @rmat0n
  • 5. Summary •  What ? Why ? •  Non blocking API example •  Event programming model •  Express, Socket.IO and modules •  Mini Hands On •  Unit Test •  Limits
  • 6. What is Node ? Server-side Javascript Node.js javascript implementation is V8 Javascript Engine (Google Chrome) Provide an easy way to build scalable network programs Non blocking I/O Single Threaded Written by Ryah Dahl
  • 7. What is Node ? http://codingrelic.geekhold.com/2010/08/nodejs-from-30000-feet.html
  • 8. What is Node ? var http = require('http'); http.createServer(function (request, response) { res.writeHead(200, {"Content-Type": "text/plain"}); res.end("Hello Worldn"); }).listen(1337, "127.0.0.1"); console.log("Server running at http://127.0.0.1:1337/"); ~$ node server.js ~$ curl http://127.0.0.1:1337/
  • 9. Why using Node ? •  Ryan Dahl: "Node.js project: To provide a purely evented, non-blocking infrastructure to script highly concurrent programs" (http://yuilibrary.com/theater/ryan-dahl/dahl-node/) •  Scalable software •  Non blocking I/O •  Same language and share code between server side and client side •  JSON friendly (web, server, database...)
  • 10. Blocking API example print("hello"); sleep(2000); blocked!! print("world");
  • 11. Non blocking API example var data = File.read("file.txt"); ... // Here you have to wait... maybe a lot... ... // And your thread is still alive... doing nothing... ... parseResult(data);
  • 12. Non blocking API example var data = File.read("file.txt", function(data) { parseResult(data); }); // Here, your thread is alive and continue working !!! myOtherCode();
  • 13.
  • 14. Event programming model •  Events are the heart of Node.js •  Everything is event based •  You can create yours own events
  • 15. Event programming model Sample dummyEmitter.emit('myCustomEvent', 'myValue'); dummyReceiver.on('myCustomEvent', function(data){ console.log(data); });
  • 16. Event programming model Sample SERVEUR socket.emit('news', { hello: 'world' }); socket.on('event', function (data) { console.log(data); }); CLIENT socket.on('news', function (data) { console.log(data); socket.emit('event', { my: 'data' }); });
  • 17. NPM
  • 18.
  • 19. Modules Node Boilerplate Event Emitter 2 Underscore Vows Coffeemate Node Inspector Spotify, Twitter, Gravatar, Dropbox, AWS, https://github.com/joyent/node/wiki/modules
  • 20. Express Web Framework Inspired by Sinatra (Ruby) Systèmes de templates (jade, Haml, EJS...) var app = express.createServer(); app.get('/', function(req, res) { res.send('Hello World'); }); app.listen(3000);
  • 21. Express app.configure('development', function() { server.set('views', __dirname + '/views'); server.set('view engine', 'ejs'); app.use(express.static(__dirname + '/public')); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function() { server.set('views', __dirname + '/views'); server.set('view engine', 'ejs'); var aYear = 31557600000; app.use(express.static(__dirname + '/public', { 'maxAge': aYear })); app.use(express.errorHandler()); });
  • 22. Express app.get('/user/:id', function(req, res) { res.send('user' + req.params.id); }); '/users/:id?' /users/5 /users '/user/:id.:format?' /user/12 /user/12.json '/user/:id/:operation?' /user/1 /user/1/edit '/files/*' /files/jquery.js /files/javascripts/jquery.js
  • 23. Socket.IO - Why ? WebSocket : Firefox 4, Chrome 4, Opera 10.70, and Safari 5. Asynchronous communication from client to server. AJAX - XmlHttpRequest ? Flash / AJAX Long Polling Disconnection
  • 24. Socket.IO - How var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { io.sockets.emit('info', 'a player join the game'); socket.on('chat', function (msg) { console.log('send a chat', msg); }); socket.on('disconnect', function () { sockets.emit('user disconnected'); }); });
  • 25. Socket.IO - How <script> var socket = io.connect('http://localhost'); socket.on('connect', function () { socket.on('info', function (data) { alert(data); }); }); socket.emit('chat',myMessage); </script>
  • 26. Socket.IO - How •  custom messages : socket.emit('my custom event',{data:xxx}); •  volatile : socket.volatile.emit('tweet',tweet); •  acknoledgements •  broadcast : socket.broadcast.emit('hello','world'); •  room : socket.join('justin bieber fans') •  send a message in a room : io.sockets.in('my room').emit('hello','world'); •  storing data : socket.set('name','Mathilde',function () { //callback });
  • 27. Modules Create yours ! hello.js var world = function() { alert("helloworld"); }; exports.world = world; server.js var hello = require("./hello") hello.world();
  • 28. Mini Hands On Go Mathilde o/
  • 29. Tests MLE •  Unit tests o  Node.js provides its own assert module http://nodejs.org/docs/v0.5.6/api/assert.html o  QUnit (JQuery) http://docs.jquery.com/Qunit o  NodeUnit https://github.com/caolan/nodeunit o  Expresso https://github.com/visionmedia/expresso •  Integration tests o  Zombie.js http://zombie.labnotes.org •  Behavior Driven Development o  vowsjs http://vowsjs.org/ o  jasmine-node https://github.com/mhevery/jasmine-node •  https://github.com/joyent/node/wiki/modules#wiki-testing
  • 30. Unit Tests with QUnit <script> $(document) .ready( function() { module("1. Game"); test( "Connais la valeur du joueur suivant en fonction du joueur actuel", function() { game = new Game(); game.take(3); game.take(1); equals(game.otherPlayer(), "O", "O est le joueur précédent"); }); ... </script>
  • 32. Limits - Cryptic error messages node.js:50 throw e; ^ Error: ECONNREFUSED, Connection refused at IOWatcher.callback (net:870:22) at node.js:607:9 client.on("error", function (err) { console.log("Error " + err); });
  • 33. Limits - Cryptic error messages - Only one thread (it is also an advantage) - Can be difficult to read - Non async lib/third party decrease perfs - IDE, Tooling, Debugger, Profiler - How to choose a good module ?
  • 34. Node REPL ~$ node > 1+2 3 > [1, 2, 3].splice(1,2) [2, 3] > process.pid 2998 > ...
  • 35. Links Quick tour : http://www.slideshare.net/the_undefined/nodejs-a-quick-tour Node + Websockets : http://www.slideshare.net/the_undefined/nodejs-a-quick-tour Node beginner : http://nodebeginner.org/ The Node Beginner Book : https://github.com/ManuelKiessling/NodeBeginnerBook Hands on Node.js : http://nodetuts.com/handson-nodejs-book.html Node.js in Action (été 2012): http://www.manning.com/cantelon