SlideShare a Scribd company logo
Monday, April 1, 13
Introduction to
                          node.js


     Ran Mizrahi (@ranm8)
     Open Source Dpt. Leader @ CodeOasis
Monday, April 1, 13
About CodeOasis

     • CodeOasis specializes in cutting-edge web solutions.
     • Large variety of customers (from startups to enterprises).
     • Technologies we love:
               •      PHP - Symfony2 and Drupal
               •      node.js (-:
               •      HTML5
               •      CSS3
               •      AngularJS

     • Our Microsoft department works with C#, WPF, etc.



Monday, April 1, 13
What is node.js??


     • Server-side JavaScript development platform.
     • Built on top of Chrome’s JavaScript runtime engine V8.
     • Aims for easy development of scalable, non-blocking I/O, real
           time and network applications.

     • Written in C/C++ and JavaScript.
     • CommonJS module system.
     • node.js is single-threaded and uses event-loop.



Monday, April 1, 13
What is V8??


      • V8 is Google Chrome's JavaScript runtime engine.
      • Implements ECMAScript specification (5th edition).
      • Standalone and can be embedded to any C++ application.
      • Compiles JavaScript to native machine code before executing it
           instead of interpreting.

      • Open sourced under the new BSD license.




Monday, April 1, 13
We all love burgers!




Monday, April 1, 13
We all love burgers!




Monday, April 1, 13
Thread per Connection Burgers
     Restaurant




Monday, April 1, 13
Thread per Connection Burgers
     Restaurant




Monday, April 1, 13
Thread per Connection Burgers
     Restaurant




Monday, April 1, 13
Monday, April 1, 13
Something is WRONG, we must
                do it BETTER!!!



Monday, April 1, 13
Event-driven Burgers Restaurant




Monday, April 1, 13
Event-driven Burgers Restaurant




Monday, April 1, 13
Apache vs. NGINX Performance

      Requests per second:




Monday, April 1, 13
Apache vs. NGINX Performance

      Memory usage:




Monday, April 1, 13
Apache vs. NGINX Performance

      So, what is the big difference between Apache and Nginx?


     • Apache uses one thread per connection.
       • Hard to scale.
       • Resource expensive.
     • NGINX is single-threaded and uses event-loop for handling
          requests.
          • Easy to scale.
          • Lower resources consumption.




Monday, April 1, 13
Blocking Code

     What is the software doing while it queries to the DB?!?

      var response = db.query('select * form users');
      // use the result




Monday, April 1, 13
Blocking Code

     What is the software doing while it queries to the DB?!?

      var response = db.query('select * form users');
      // use the result




      In most cases, nothing (/:




Monday, April 1, 13
Blocking Code

     What is the software doing while it queries to the DB?!?

      var response = db.query('select * form users');
      // use the result




      In most cases, nothing (/:

     • Better software should handle I/O differently! It should
           multitask.

     • Other tasks should be performed while waiting..



Monday, April 1, 13
Non-blocking Code

     Non-blocking code:

      db.query('select * form users', function(result){
        // Use the result
      });




Monday, April 1, 13
Non-blocking Code

     Non-blocking code:

      db.query('select * form users', function(result){
        // Use the result
      });




     This is how I/O should be handled in concurrency, when the
     DB will respond, the given function will be executed.




Monday, April 1, 13
So, Why Isn’t Everyone Using
    Non-blocking I/O

      This what we learn:
       puts('Enter you name:');
       var name = gets();
       puts('Hello ' + name);




Monday, April 1, 13
So, Why Isn’t Everyone Using
    Non-blocking I/O

      This what we learn:
       puts('Enter you name:');
       var name = gets();
       puts('Hello ' + name);




      Considered too complicated (:/

      puts('Enter you name here:');
      gets(function(name) {
        puts('Hello ' + name);
      });




Monday, April 1, 13
Why JavaScript?!

     JavaScript is designed specifically to be used with an event-loop:

     • Anonymous functions, closures.
     • Only one callback at a time.
     • I/O through DOM event callbacks.
     • Web developers already know JavaScript (Makes the learning
           curve much smaller).




Monday, April 1, 13
The node.js project

     • Provides purely event-driven, non-blocking infrastructure to
           write high concurrency applications.

     • Uses JavaScript for easy development of asynchronies apps.
     • Open source and extendable module system.




                                                  https://github.com/popular/starred


Monday, April 1, 13
Some Examples




Monday, April 1, 13
Hello Reversim Summit!

      setTimeout(function() {
        console.log('Reversim Summit!');
      }, 2000);

      console.log('Hello');


       • The program outputs “Hello”, then waits two seconds and
          outputs “Reversim Summit!”.

       • While waiting for the timeout to complete, node.js will keep
          adjusting other tasks.

       • Node exits automatically when nothing is left to do.



Monday, April 1, 13
Streaming HTTP Server

      var http = require('http');

      var server = http.createServer(function(request, response) {
        response.writeHead(200, { 'Content-Type': 'text/plain' });
        setTimeout(function() {
           response.end('Reversim Summit!n');
        }, 2000);

        response.write('Hellon');
      });

      server.listen(8000);




Monday, April 1, 13
Streaming HTTP Server

      var http = require('http');

      var server = http.createServer(function(request, response) {
        response.writeHead(200, { 'Content-Type': 'text/plain' });
        setTimeout(function() {
           response.end('Reversim Summit!n');
        }, 2000);

        response.write('Hellon');
      });

      server.listen(8000);

     Let’s benchmark that... and see the results..




Monday, April 1, 13
Streaming HTTP Server

      var http = require('http');

      var server = http.createServer(function(request, response) {
        response.writeHead(200, { 'Content-Type': 'text/plain' });
        setTimeout(function() {
           response.end('Reversim Summit!n');
        }, 2000);

        response.write('Hellon');
      });

      server.listen(8000);

     Let’s benchmark that... and see the results..

      20 secs, with single thread is the result of non-blocking structure.




Monday, April 1, 13
DNS Resolver

      var dns = require('dns');

      console.log('resolving google.com...');

      dns.resolve('google.com', function(error, addresses) {
        if (error) throw error;

        console.log('found: ' + addresses.join(', '));
      });




     Resolves “google.com” and outputs the result.




Monday, April 1, 13
Common Frameworks and
                              Tools




Monday, April 1, 13
NPM (Node.js package manager)


     npm is a package and dependency
     manager for node.js.

     Some of npm features:

     • Easy installation and publishing of node.js modules.
     • Manages module dependancies.
     • Easy to use.
     • Works in both global and local scope.



Monday, April 1, 13
NPM (Node.js package manager)


        npm usage:

        Installs package in the current local directory:
       $ npm install express


       Installs package globally
       $ npm install express -g




Monday, April 1, 13
Express

     Express is a minimal and flexible node.js web framework,
     providing robust set of features for building web applications.
     Taken from http://expressjs.com




     Some of express features:

     • Robust routing.
     • Redirection helpers.
     • View rendering and partials support.
     • Built on top of connect.



Monday, April 1, 13
Express

       Web Server example:

       var express = require('express');

       var app = express.createServer();
       app.get('/', function(request, response) {
         // Return JSON encoded response
         response.json({
            code: 200,
            message: 'OK',
            payload: null
         });
       });


       • Creates new express HTTP server with route for path “/”.
       • Returns JSON formatted response.


Monday, April 1, 13
Socket.IO
     Socket.IO aims to make real-time apps possible in every browser
     and mobile device, blurring the differences between transport
     mechanisms.
     Taken from http://socket.io




     Some of socket.io main features:

     • Supports multiple transport mechanisms (WebSocket, Flash
           and AJAX long-polling fallback, etc.).

     • Management of sockets rooms and namespaces.
     • Disconnections detection through heartbeats.
     • Reconnection support with buffering.


Monday, April 1, 13
Socket.IO - Simple notification example
      Server:
      var io = require('socket.io').listen(3000);

      io.on('connection', function(socket) {
        var notification = { body: 'Hello Reversim Summit!' };

        socket.emit('notification', notification, function(response) {
          console.log(response);
        });
      });


      Client:
      var socket = io.connect('http://localhost:3000');
      socket.on('notification', function(data, callback) {
        console.log(data.body);

        callback('Hello to you too!');
      });




Monday, April 1, 13
Mongoose


     Mongoose aims to provide elegant MongoDB object modeling
     (ODM) for node.js.

     Some of mongoose main features:

     • Allows creating DB schemas.
     • Management of sockets rooms and namespaces.
     • Disconnections detection through heartbeats.
     • Reconnection support with buffering.



Monday, April 1, 13
Mongoose

     Mongoose cat document example:
      var mongoose = require('mongoose');
      mongoose.connect('localhost', 'my_db');

      var CatSchema = mongoose.Schema({
        name: {
           required: true,
           default: 'My cat'
        }
      });

      var Cat = mongoose.model('Cat', CatSchema);

      var kitty = new Cat({ name: 'Kati' });
      kitty.save(function(err) {
        if (err) throw err;
        console.log('Saved!')
      });




Monday, April 1, 13
TDD/BDD using Mocha and Expect.js
     Mocha
     Mocha is a feature-rich JavaScript test frameworks running on
     node and the browser, making asynchronies tests easy.
     Main features:

      • Supports both TDD and BDD styles.
      • Both browser and node support.
      • Proper exit status for CI support.
      • Really easy async tests.
      • node.js debugger support.
      • Highly flexible, choose and join the pieces yourself (spy library,
           assertion library, etc.).
Monday, April 1, 13
TDD/BDD using Mocha and Expect.js

     Expect.js
     Expect.js is a minimalistic assertion library based on should.js

      Main features:

      • BDD style.
      • Compatible with all test frameworks.
      • Both node.js and browser compatible.
      • Standalone assertion library.




Monday, April 1, 13
TDD/BDD using Mocha and Expect.js
      “Normal” test:
      var expect = require('expect.js');

      describe('Array', function() {
        describe('#indexOf()', function() {
           it('Expect -1 when the value is not present', function() {
             var array = [1, 2, 3];

            expect(array.indexOf(4)).to.be(-1);
          });
        });
      });


      Run it..
      $ mocha --reporter spec
        Array
          #indexOf()
            ✓ Expect -1 when the value is not present


           1 test complete (5 ms)


Monday, April 1, 13
TDD/BDD using Mocha and Expect.js
      “Async” test:
       var expect = require('expect.js');

       function asyncCall(val ,callback) {
           var prefix = ' - ';

               setTimeout(function() {
                   var newString = val + prefix + 'OK';

                   callback(newString);
               }, 500);
       }

       describe('asyncCall', function() {
           it('Add suffix that prefixed with - to the given string', function(done) {
               var testVal = 'Foo';

                      asyncCall(testVal, function(response) {
                          expect(response).to.contain(testVal + ' - OK');
                          done();
                      });
               });
       });



       Let’s run it...


Monday, April 1, 13
Use Case

     FXP

     • Real-time notifications, forum threads and posts.
     • 30,000 concurrency connections!
     • We started with version 0.4 )-: and moved to 0.6..
     • Today, runs on one web server for serving all those concurrent
           connections..




Monday, April 1, 13
Thank you!

                      Questions?




Monday, April 1, 13

More Related Content

PDF
Intro to JavaScript Testing
PDF
Dependency Injection @ AngularJS
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
PDF
How AngularJS Embraced Traditional Design Patterns
PDF
Intro to node.js - Ran Mizrahi (28/8/14)
PDF
JavaScript Library Overview
PDF
Javascript Best Practices
PPT
Javascript and Jquery Best practices
Intro to JavaScript Testing
Dependency Injection @ AngularJS
Intro To JavaScript Unit Testing - Ran Mizrahi
How AngularJS Embraced Traditional Design Patterns
Intro to node.js - Ran Mizrahi (28/8/14)
JavaScript Library Overview
Javascript Best Practices
Javascript and Jquery Best practices

What's hot (20)

KEY
Building a real life application in node js
PPTX
Good karma: UX Patterns and Unit Testing in Angular with Karma
PDF
How to build to do app using vue composition api and vuex 4 with typescript
PDF
Design patterns revisited with PHP 5.3
PDF
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
PDF
Workshop 3: JavaScript build tools
PDF
Secrets of JavaScript Libraries
PDF
Workshop 14: AngularJS Parte III
PDF
The DOM is a Mess @ Yahoo
PDF
Advanced AV Foundation (CocoaConf, Aug '11)
PDF
Javascript Module Patterns
ODP
Jquery- One slide completing all JQuery
PDF
Workshop 8: Templating: Handlebars, DustJS
PDF
Workshop 13: AngularJS Parte II
PDF
Celery
PDF
Life in a Queue - Using Message Queue with django
PDF
Asynchronous Module Definition (AMD)
PPTX
Javascript basics for automation testing
PDF
Hi performance table views with QuartzCore and CoreText
PDF
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Building a real life application in node js
Good karma: UX Patterns and Unit Testing in Angular with Karma
How to build to do app using vue composition api and vuex 4 with typescript
Design patterns revisited with PHP 5.3
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
Workshop 3: JavaScript build tools
Secrets of JavaScript Libraries
Workshop 14: AngularJS Parte III
The DOM is a Mess @ Yahoo
Advanced AV Foundation (CocoaConf, Aug '11)
Javascript Module Patterns
Jquery- One slide completing all JQuery
Workshop 8: Templating: Handlebars, DustJS
Workshop 13: AngularJS Parte II
Celery
Life in a Queue - Using Message Queue with django
Asynchronous Module Definition (AMD)
Javascript basics for automation testing
Hi performance table views with QuartzCore and CoreText
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Ad

Viewers also liked (20)

PDF
Getting merged
PPTX
Retiree sue
PDF
2007 Web2.0 Service
ODP
Dojotoolkit Nedir?
PDF
ONA I MÍRIAM
PPT
Sociale medier: Værktøjer og kategorier
PPT
PPT
Final Presentation
PPS
Cheeky Carbon Presentation
PPS
euskara kontsumitzeko motibazioak
PDF
PDF
4. prosegizontas tin ekpadeutiki omada
PPT
Annual Report Py08
PPT
PPTX
Internet life skills wb
PPS
Management - a picturesque
PPT
Jornada de motivacion y busqueda de opciones
PDF
Airbnb Original Pitch Deck
PPTX
Test Helping Rural Oregon Work
Getting merged
Retiree sue
2007 Web2.0 Service
Dojotoolkit Nedir?
ONA I MÍRIAM
Sociale medier: Værktøjer og kategorier
Final Presentation
Cheeky Carbon Presentation
euskara kontsumitzeko motibazioak
4. prosegizontas tin ekpadeutiki omada
Annual Report Py08
Internet life skills wb
Management - a picturesque
Jornada de motivacion y busqueda de opciones
Airbnb Original Pitch Deck
Test Helping Rural Oregon Work
Ad

Similar to Introduction to node.js by Ran Mizrahi @ Reversim Summit (20)

PPTX
Introduction to Node.js
PDF
Intro to node.js - Ran Mizrahi (27/8/2014)
ODP
Introduce about Nodejs - duyetdev.com
PDF
Developing realtime apps with Drupal and NodeJS
KEY
node.js: Javascript's in your backend
PDF
Node JS
PDF
Nodejs a-practical-introduction-oredev
PPTX
introduction to node.js
KEY
Node.js - As a networking tool
PDF
Comet with node.js and V8
PPTX
GeekCampSG - Nodejs , Websockets and Realtime Web
PDF
Introduction to Node.js
KEY
Node.js - A practical introduction (v2)
KEY
A language for the Internet: Why JavaScript and Node.js is right for Internet...
PDF
Node Up and Running Scalable Server Side Code with JavaScript 1st Edition Tom...
PDF
Introduction to Node.js
PDF
Nodejs - A quick tour (v5)
PPTX
PPTX
PDF
Introduction to Node.js: What, why and how?
Introduction to Node.js
Intro to node.js - Ran Mizrahi (27/8/2014)
Introduce about Nodejs - duyetdev.com
Developing realtime apps with Drupal and NodeJS
node.js: Javascript's in your backend
Node JS
Nodejs a-practical-introduction-oredev
introduction to node.js
Node.js - As a networking tool
Comet with node.js and V8
GeekCampSG - Nodejs , Websockets and Realtime Web
Introduction to Node.js
Node.js - A practical introduction (v2)
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Node Up and Running Scalable Server Side Code with JavaScript 1st Edition Tom...
Introduction to Node.js
Nodejs - A quick tour (v5)
Introduction to Node.js: What, why and how?

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Cloud computing and distributed systems.
PDF
Modernizing your data center with Dell and AMD
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Encapsulation theory and applications.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
MYSQL Presentation for SQL database connectivity
20250228 LYD VKU AI Blended-Learning.pptx
Cloud computing and distributed systems.
Modernizing your data center with Dell and AMD
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Unlocking AI with Model Context Protocol (MCP)
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Understanding_Digital_Forensics_Presentation.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Encapsulation theory and applications.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Network Security Unit 5.pdf for BCA BBA.
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Weekly Chronicles - August'25 Week I
Review of recent advances in non-invasive hemoglobin estimation
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Introduction to node.js by Ran Mizrahi @ Reversim Summit

  • 2. Introduction to node.js Ran Mizrahi (@ranm8) Open Source Dpt. Leader @ CodeOasis Monday, April 1, 13
  • 3. About CodeOasis • CodeOasis specializes in cutting-edge web solutions. • Large variety of customers (from startups to enterprises). • Technologies we love: • PHP - Symfony2 and Drupal • node.js (-: • HTML5 • CSS3 • AngularJS • Our Microsoft department works with C#, WPF, etc. Monday, April 1, 13
  • 4. What is node.js?? • Server-side JavaScript development platform. • Built on top of Chrome’s JavaScript runtime engine V8. • Aims for easy development of scalable, non-blocking I/O, real time and network applications. • Written in C/C++ and JavaScript. • CommonJS module system. • node.js is single-threaded and uses event-loop. Monday, April 1, 13
  • 5. What is V8?? • V8 is Google Chrome's JavaScript runtime engine. • Implements ECMAScript specification (5th edition). • Standalone and can be embedded to any C++ application. • Compiles JavaScript to native machine code before executing it instead of interpreting. • Open sourced under the new BSD license. Monday, April 1, 13
  • 6. We all love burgers! Monday, April 1, 13
  • 7. We all love burgers! Monday, April 1, 13
  • 8. Thread per Connection Burgers Restaurant Monday, April 1, 13
  • 9. Thread per Connection Burgers Restaurant Monday, April 1, 13
  • 10. Thread per Connection Burgers Restaurant Monday, April 1, 13
  • 12. Something is WRONG, we must do it BETTER!!! Monday, April 1, 13
  • 15. Apache vs. NGINX Performance Requests per second: Monday, April 1, 13
  • 16. Apache vs. NGINX Performance Memory usage: Monday, April 1, 13
  • 17. Apache vs. NGINX Performance So, what is the big difference between Apache and Nginx? • Apache uses one thread per connection. • Hard to scale. • Resource expensive. • NGINX is single-threaded and uses event-loop for handling requests. • Easy to scale. • Lower resources consumption. Monday, April 1, 13
  • 18. Blocking Code What is the software doing while it queries to the DB?!? var response = db.query('select * form users'); // use the result Monday, April 1, 13
  • 19. Blocking Code What is the software doing while it queries to the DB?!? var response = db.query('select * form users'); // use the result In most cases, nothing (/: Monday, April 1, 13
  • 20. Blocking Code What is the software doing while it queries to the DB?!? var response = db.query('select * form users'); // use the result In most cases, nothing (/: • Better software should handle I/O differently! It should multitask. • Other tasks should be performed while waiting.. Monday, April 1, 13
  • 21. Non-blocking Code Non-blocking code: db.query('select * form users', function(result){ // Use the result }); Monday, April 1, 13
  • 22. Non-blocking Code Non-blocking code: db.query('select * form users', function(result){ // Use the result }); This is how I/O should be handled in concurrency, when the DB will respond, the given function will be executed. Monday, April 1, 13
  • 23. So, Why Isn’t Everyone Using Non-blocking I/O This what we learn: puts('Enter you name:'); var name = gets(); puts('Hello ' + name); Monday, April 1, 13
  • 24. So, Why Isn’t Everyone Using Non-blocking I/O This what we learn: puts('Enter you name:'); var name = gets(); puts('Hello ' + name); Considered too complicated (:/ puts('Enter you name here:'); gets(function(name) { puts('Hello ' + name); }); Monday, April 1, 13
  • 25. Why JavaScript?! JavaScript is designed specifically to be used with an event-loop: • Anonymous functions, closures. • Only one callback at a time. • I/O through DOM event callbacks. • Web developers already know JavaScript (Makes the learning curve much smaller). Monday, April 1, 13
  • 26. The node.js project • Provides purely event-driven, non-blocking infrastructure to write high concurrency applications. • Uses JavaScript for easy development of asynchronies apps. • Open source and extendable module system. https://github.com/popular/starred Monday, April 1, 13
  • 28. Hello Reversim Summit! setTimeout(function() { console.log('Reversim Summit!'); }, 2000); console.log('Hello'); • The program outputs “Hello”, then waits two seconds and outputs “Reversim Summit!”. • While waiting for the timeout to complete, node.js will keep adjusting other tasks. • Node exits automatically when nothing is left to do. Monday, April 1, 13
  • 29. Streaming HTTP Server var http = require('http'); var server = http.createServer(function(request, response) { response.writeHead(200, { 'Content-Type': 'text/plain' }); setTimeout(function() { response.end('Reversim Summit!n'); }, 2000); response.write('Hellon'); }); server.listen(8000); Monday, April 1, 13
  • 30. Streaming HTTP Server var http = require('http'); var server = http.createServer(function(request, response) { response.writeHead(200, { 'Content-Type': 'text/plain' }); setTimeout(function() { response.end('Reversim Summit!n'); }, 2000); response.write('Hellon'); }); server.listen(8000); Let’s benchmark that... and see the results.. Monday, April 1, 13
  • 31. Streaming HTTP Server var http = require('http'); var server = http.createServer(function(request, response) { response.writeHead(200, { 'Content-Type': 'text/plain' }); setTimeout(function() { response.end('Reversim Summit!n'); }, 2000); response.write('Hellon'); }); server.listen(8000); Let’s benchmark that... and see the results.. 20 secs, with single thread is the result of non-blocking structure. Monday, April 1, 13
  • 32. DNS Resolver var dns = require('dns'); console.log('resolving google.com...'); dns.resolve('google.com', function(error, addresses) { if (error) throw error; console.log('found: ' + addresses.join(', ')); }); Resolves “google.com” and outputs the result. Monday, April 1, 13
  • 33. Common Frameworks and Tools Monday, April 1, 13
  • 34. NPM (Node.js package manager) npm is a package and dependency manager for node.js. Some of npm features: • Easy installation and publishing of node.js modules. • Manages module dependancies. • Easy to use. • Works in both global and local scope. Monday, April 1, 13
  • 35. NPM (Node.js package manager) npm usage: Installs package in the current local directory: $ npm install express Installs package globally $ npm install express -g Monday, April 1, 13
  • 36. Express Express is a minimal and flexible node.js web framework, providing robust set of features for building web applications. Taken from http://expressjs.com Some of express features: • Robust routing. • Redirection helpers. • View rendering and partials support. • Built on top of connect. Monday, April 1, 13
  • 37. Express Web Server example: var express = require('express'); var app = express.createServer(); app.get('/', function(request, response) { // Return JSON encoded response response.json({ code: 200, message: 'OK', payload: null }); }); • Creates new express HTTP server with route for path “/”. • Returns JSON formatted response. Monday, April 1, 13
  • 38. Socket.IO Socket.IO aims to make real-time apps possible in every browser and mobile device, blurring the differences between transport mechanisms. Taken from http://socket.io Some of socket.io main features: • Supports multiple transport mechanisms (WebSocket, Flash and AJAX long-polling fallback, etc.). • Management of sockets rooms and namespaces. • Disconnections detection through heartbeats. • Reconnection support with buffering. Monday, April 1, 13
  • 39. Socket.IO - Simple notification example Server: var io = require('socket.io').listen(3000); io.on('connection', function(socket) { var notification = { body: 'Hello Reversim Summit!' }; socket.emit('notification', notification, function(response) { console.log(response); }); }); Client: var socket = io.connect('http://localhost:3000'); socket.on('notification', function(data, callback) { console.log(data.body); callback('Hello to you too!'); }); Monday, April 1, 13
  • 40. Mongoose Mongoose aims to provide elegant MongoDB object modeling (ODM) for node.js. Some of mongoose main features: • Allows creating DB schemas. • Management of sockets rooms and namespaces. • Disconnections detection through heartbeats. • Reconnection support with buffering. Monday, April 1, 13
  • 41. Mongoose Mongoose cat document example: var mongoose = require('mongoose'); mongoose.connect('localhost', 'my_db'); var CatSchema = mongoose.Schema({ name: { required: true, default: 'My cat' } }); var Cat = mongoose.model('Cat', CatSchema); var kitty = new Cat({ name: 'Kati' }); kitty.save(function(err) { if (err) throw err; console.log('Saved!') }); Monday, April 1, 13
  • 42. TDD/BDD using Mocha and Expect.js Mocha Mocha is a feature-rich JavaScript test frameworks running on node and the browser, making asynchronies tests easy. Main features: • Supports both TDD and BDD styles. • Both browser and node support. • Proper exit status for CI support. • Really easy async tests. • node.js debugger support. • Highly flexible, choose and join the pieces yourself (spy library, assertion library, etc.). Monday, April 1, 13
  • 43. TDD/BDD using Mocha and Expect.js Expect.js Expect.js is a minimalistic assertion library based on should.js Main features: • BDD style. • Compatible with all test frameworks. • Both node.js and browser compatible. • Standalone assertion library. Monday, April 1, 13
  • 44. TDD/BDD using Mocha and Expect.js “Normal” test: var expect = require('expect.js'); describe('Array', function() { describe('#indexOf()', function() { it('Expect -1 when the value is not present', function() { var array = [1, 2, 3]; expect(array.indexOf(4)).to.be(-1); }); }); }); Run it.. $ mocha --reporter spec Array #indexOf() ✓ Expect -1 when the value is not present 1 test complete (5 ms) Monday, April 1, 13
  • 45. TDD/BDD using Mocha and Expect.js “Async” test: var expect = require('expect.js'); function asyncCall(val ,callback) { var prefix = ' - '; setTimeout(function() { var newString = val + prefix + 'OK'; callback(newString); }, 500); } describe('asyncCall', function() { it('Add suffix that prefixed with - to the given string', function(done) { var testVal = 'Foo'; asyncCall(testVal, function(response) { expect(response).to.contain(testVal + ' - OK'); done(); }); }); }); Let’s run it... Monday, April 1, 13
  • 46. Use Case FXP • Real-time notifications, forum threads and posts. • 30,000 concurrency connections! • We started with version 0.4 )-: and moved to 0.6.. • Today, runs on one web server for serving all those concurrent connections.. Monday, April 1, 13
  • 47. Thank you! Questions? Monday, April 1, 13