SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Fabien Potencier
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsVisual Engineering
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoojeresig
 
Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)Chris Adamson
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQueryKnoldus Inc.
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSVisual Engineering
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
 
Life in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoLife in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoTareque Hossain
 
Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)xMartin12
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextMugunth Kumar
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...andreaslubbe
 

Was ist angesagt? (20)

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
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
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
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
 
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter PilgrimJavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build tools
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
 
Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Celery
CeleryCelery
Celery
 
Life in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoLife in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with django
 
Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreText
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
 

Andere mochten auch (20)

Getting merged
Getting mergedGetting merged
Getting merged
 
Retiree sue
Retiree sueRetiree sue
Retiree sue
 
Microworlds pro
Microworlds proMicroworlds pro
Microworlds pro
 
2007 Web2.0 Service
2007 Web2.0 Service 2007 Web2.0 Service
2007 Web2.0 Service
 
Dojotoolkit Nedir?
Dojotoolkit Nedir?Dojotoolkit Nedir?
Dojotoolkit Nedir?
 
ONA I MÍRIAM
ONA I MÍRIAMONA I MÍRIAM
ONA I MÍRIAM
 
Sociale medier: Værktøjer og kategorier
Sociale medier: Værktøjer og kategorierSociale medier: Værktøjer og kategorier
Sociale medier: Værktøjer og kategorier
 
0311
03110311
0311
 
Final Presentation
Final PresentationFinal Presentation
Final Presentation
 
Cheeky Carbon Presentation
Cheeky Carbon PresentationCheeky Carbon Presentation
Cheeky Carbon Presentation
 
euskara kontsumitzeko motibazioak
euskara kontsumitzeko motibazioakeuskara kontsumitzeko motibazioak
euskara kontsumitzeko motibazioak
 
Diadrastikoi b senaria
Diadrastikoi b senariaDiadrastikoi b senaria
Diadrastikoi b senaria
 
4. prosegizontas tin ekpadeutiki omada
4. prosegizontas tin ekpadeutiki omada4. prosegizontas tin ekpadeutiki omada
4. prosegizontas tin ekpadeutiki omada
 
Annual Report Py08
Annual Report Py08Annual Report Py08
Annual Report Py08
 
1210
12101210
1210
 
Internet life skills wb
Internet life skills wbInternet life skills wb
Internet life skills wb
 
Management - a picturesque
Management - a picturesqueManagement - a picturesque
Management - a picturesque
 
Jornada de motivacion y busqueda de opciones
Jornada de motivacion y busqueda de opcionesJornada de motivacion y busqueda de opciones
Jornada de motivacion y busqueda de opciones
 
Airbnb Original Pitch Deck
Airbnb Original Pitch DeckAirbnb Original Pitch Deck
Airbnb Original Pitch Deck
 
Test Helping Rural Oregon Work
Test  Helping  Rural  Oregon  WorkTest  Helping  Rural  Oregon  Work
Test Helping Rural Oregon Work
 

Ähnlich wie Introduction to node.js by Ran Mizrahi @ Reversim Summit

Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA PresentationRob Tweed
 
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
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Christian Joudrey
 
Web Development Environments: Choose the best or go with the rest
Web Development Environments:  Choose the best or go with the restWeb Development Environments:  Choose the best or go with the rest
Web Development Environments: Choose the best or go with the restgeorge.james
 
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 backendDavid Padbury
 
Intro to PHP Testing
Intro to PHP TestingIntro to PHP Testing
Intro to PHP TestingRan Mizrahi
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureColin Mackay
 
Javascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and BackboneJavascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and BackboneDeepu S Nath
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
 
Introduction to node.js
Introduction to  node.jsIntroduction to  node.js
Introduction to node.jsMd. Sohel Rana
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS drupalcampest
 
Advanced Web Technology.pptx
Advanced Web Technology.pptxAdvanced Web Technology.pptx
Advanced Web Technology.pptxssuser35fdf2
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.jsAyush Mishra
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 

Ähnlich wie Introduction to node.js by Ran Mizrahi @ Reversim Summit (20)

Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
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)
 
Nodejs
NodejsNodejs
Nodejs
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
Web Development Environments: Choose the best or go with the rest
Web Development Environments:  Choose the best or go with the restWeb Development Environments:  Choose the best or go with the rest
Web Development Environments: Choose the best or go with the rest
 
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
 
Intro to PHP Testing
Intro to PHP TestingIntro to PHP Testing
Intro to PHP Testing
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
 
Javascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and BackboneJavascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Introduction to node.js
Introduction to  node.jsIntroduction to  node.js
Introduction to node.js
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
Advanced Web Technology.pptx
Advanced Web Technology.pptxAdvanced Web Technology.pptx
Advanced Web Technology.pptx
 
NodeJS
NodeJSNodeJS
NodeJS
 
Proposal
ProposalProposal
Proposal
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 

Kürzlich hochgeladen

UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
99.99% of Your Traces Are (Probably) Trash (SRECon NA 2024).pdf
99.99% of Your Traces  Are (Probably) Trash (SRECon NA 2024).pdf99.99% of Your Traces  Are (Probably) Trash (SRECon NA 2024).pdf
99.99% of Your Traces Are (Probably) Trash (SRECon NA 2024).pdfPaige Cruz
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
The Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementThe Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementNuwan Dias
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 

Kürzlich hochgeladen (20)

UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
99.99% of Your Traces Are (Probably) Trash (SRECon NA 2024).pdf
99.99% of Your Traces  Are (Probably) Trash (SRECon NA 2024).pdf99.99% of Your Traces  Are (Probably) Trash (SRECon NA 2024).pdf
99.99% of Your Traces Are (Probably) Trash (SRECon NA 2024).pdf
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
The Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementThe Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API Management
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 

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