SlideShare a Scribd company logo
1 of 38
Intro to NodeJS
       Matthew Eernisse
 Toster Conference 2011-10-28
Who am I?
Matthew Eernisse
Work at Yammer
@mde on Twitter
JavaScript at Yammer
• Browsers (yammer.com Web UI)
• Adobe AIR Desktop
• V8 in Rails via TheRubyRacer
• NodeJS
NodeJS:
“Evented I/O for V8 JavaScript”
         http://nodejs.org/
Hello, NodeJS
var http = require('http');

http.createServer(function (req, res) {

 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/');
Server JS
History of SSJS
•   Netscape Enterprise Server (OG SSJS)
•   Microsoft IIS
•   Helma (now RingoJS)
•   Whitebeam
•   Zimki
•   Jaxer
•   Perservere
•   Nitro
•   Google App Engine
•   CouchDB
•   NodeJS
Why NodeJS now?
• Steve Yegge’s NBL post, 2007-02-10
• Competition in JavaScript interpreters
• Simple, POSIX API
• Non-blocking from the ground up; so
  are the libraries
What is NodeJS good for?
• Lightweight, networked apps
• Proxies with embedded logic
• Streaming data
• System scripting
• Evented realtime apps
NodeJS is not good at complex
   database-backed Web
         applications.
     You can use Rails.
Geddy Web framework:
https://github.com/mde/geddy
NodeJS at Yammer
•   Development proxy

•   Jake for build and test (https://github.com/mde/jake)

•   Upload service for files and images (Geddy v0.2)

•   Browserless tests with FooUnit
    (https://github.com/foobarfighter/foounit)

•   Realtime, collaborative document-editing service
Jake build tool
                   https://github.com/mde/jake

•   Similar to Make or Rake

•   Tasks, prerequisites

•   File tasks, directory tasks

•   Namespaces

•   PackageTasks

•   Async task execution

•   Just executable JavaScript
desc('This is the default task.');
task('default', function () {
  console.log('This is the default task.');
  console.dir(arguments);
});

namespace('foo', function () {
  desc('This the foo:bar task');
  task('bar', function () {
    console.log('doing foo:bar task');
    console.dir(arguments);
  });

  desc('This the foo:baz task');
  task('baz', ['default', 'foo:bar'], function () {
    console.log('doing foo:baz task');
    console.dir(arguments);
  });

});
desc('This is an asynchronous task.');
task('async', function () {
  setTimeout(function () {
    console.log('Hooray!');
    complete();
  }, 1000);
}, true);

desc('Calls the foo:bar task and its dependencies.');
task('invokeFooBar', function () {
  // Calls foo:bar and its deps
  jake.Task['foo:bar'].invoke();
  // Does nothing
  jake.Task['foo:bar'].invoke();
  // Only re-runs foo:bar, but not its dependencies
  jake.Task['foo:bar'].reenable();
  jake.Task['foo:bar'].invoke();
});
var fs = require('fs')
  , pkg = JSON.parse(
        fs.readFileSync('package.json').toString())
  , version = pkg.version

var t = new jake.PackageTask('jake', 'v' + version,
     function () {
  var fileList = [
     'Makefile'
  , 'Jakefile'
  , 'README.md'
  , 'package.json'
  , 'lib/*'
  , 'bin/*'
  , 'tests/*'
  ];
  this.packageFiles.include(fileList);
  this.needTarGz = true;
  this.needTarBz2 = true;
});
Remote upload service
•   Minimal v1 in prod, Nov. 2010

•   Redis, CORS XHR-push or JSONP for upload-progress
    reporting

•   Onboard thumbnailing, remote services for video and
    document post-processing

•   Three-machine cluster, not under a heavy load

•   Large file sizes (e.g., 1.5GB)
Realtime, collaborative
       doc-editing service
•   In beta Oct. 21, 2011 (last week)

•   NodeJS, Socket.io, PostgreSQL

•   No production metrics yet for perf/scalability
Coding JS for Node
Awesome:
JavaScript is simple and
     super-flexible
Horrible:
JavaScript is simple and
     super-flexible
Asynchronous code
• Even shelling out is async?
• “1, 3, 2, go!” development
• Evented and callback-based control-flow
• A familiar model?
• Async patterns and libraries
1, 3, 2, go!
var asyncFun = function () {
   console.log('1');
   setTimeout(function () {
     console.log('3');
   }, 0);
   console.log('2');
   console.log('go!');
};
Sync fetch-and-update
var fetchAndUpdate = function (params) {
   var items = db.fetch(someQuery);
   for (var i = 0, ii = items.length; i++) {
     item.update(params);
   }
   return true;
};
Async fetch-and-update
var fetchAndUpdate = function (params, callback) {
   db.fetch(someQuery, function (items) {
     var count = 0;
     for (var i = 0, ii = items.length; i++) {
       item.update(params, function () {
         count++;
         if (count == ii) {
           callback(true);
         }
       });
     }
   });
};
Is this familiar?
jQuery.ajax({
  url: '/foo/bar.json'
, success: function () {
    alert('yay!');
  }
});

jQuery('#foo').bind('click', function (e) {
  // Do some stuff
});
Async patterns and libs

• Queue
• Promise/deferred
• In-flight registry
Queue
var asyncQueueHandler = function (items,
     handler, callback) {
   var queue = items.slice()
     , handleNextItem = function () {
          var next = queue.pop();
          if (next) {
            handler(next, function () {
              handleNextItem();
            });
          }
          else {
            callback();
          }
       };
   handleNextItem();
};
Promise
var p = new yammer.util.Promise();
p.when('foo', 'bar', 'baz').then(
    function () {
  console.log('done!');
});
p.satisfy('foo');
p.satisfy('bar');
p.satisfy('baz');

p.then(function () {
  console.log('still done!');
});
NodeJS in production
App dependencies

• Third-party modules still may change
  rapidly
• Maintain forks, push back patches where
  appropriate
Debugging NodeJS
• Callbacks in global scope have no stack
• Assume you’re fucked
• Default condition is a preemptible error
• In-flight registry with uncaughtException
  handler
FlightCheck
              https://github.com/mde/flight_check


•   Add items to in-flight registry

•   Per-item timeout

•   Configurable polling-interval

•   Define a timeout-handler
In-flight registry
var FlightCheck = require('flight_check').FlightCheck;
var handler = function (req, resp) {
   var checker = new FlightCheck(function (key) {
         resp.writeHead(500);
         resp.end('Oops, something bad happened.');
   });
   checker.add('foo', 10000);
   doFoo(req, function (result) {
     if (result.ok) {
       checker.clear('foo');
       // Do some other stuff
       resp.writeHead(200);
       resp.end('Hooray!');
     }
   });
};

process.on('uncaughtException', function (err) {
  // Do some kind of logging
});
Visibility, metrics

• Measure everything
• Log everything
• https://github.com/mikejihbe/metrics
Ops

• Communicative, consultative dev
• Ask what is expected
• Play nicely with others
The future?
• JS interpreters will keep improving
• JS language will keep improving (see:
  JS.next)
• NodeJS ecosystem will grow and mature
• Try NodeJS, you’ll like it
Matthew Eernisse
   http://twitter.com/mde

 Yammer Developer Center
http://developer.yammer.com/

More Related Content

What's hot

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 Expressjguerrero999
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming Tom Croucher
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
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 Jeetendra singh
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
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 talkAarti Parikh
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js ExplainedJeff Kunkle
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 

What's hot (20)

NodeJS: an Introduction
NodeJS: an IntroductionNodeJS: an Introduction
NodeJS: an 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
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Node ppt
Node pptNode ppt
Node ppt
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
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
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
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
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 

Viewers also liked

Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)Valeri Karpov
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaJavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaNurul Ferdous
 
How to scale and deploy NodeJS app
How to scale and deploy NodeJS appHow to scale and deploy NodeJS app
How to scale and deploy NodeJS appYacobus Reinhart
 
Nodejs introduce - using Socket.io
Nodejs introduce - using Socket.ioNodejs introduce - using Socket.io
Nodejs introduce - using Socket.ioCaesar Chi
 
High Performance NodeJS
High Performance NodeJSHigh Performance NodeJS
High Performance NodeJSDicoding
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Dinh Pham
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginnersEnoch Joshua
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJSHüseyin BABAL
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsGanesh Iyer
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs Irfan Maulana
 
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.jsVikash Singh
 

Viewers also liked (15)

Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
Nimrod: MongoDB Shell in NodeJS (JSConfUY 2015)
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaJavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
 
How to scale and deploy NodeJS app
How to scale and deploy NodeJS appHow to scale and deploy NodeJS app
How to scale and deploy NodeJS app
 
Nodejs introduce - using Socket.io
Nodejs introduce - using Socket.ioNodejs introduce - using Socket.io
Nodejs introduce - using Socket.io
 
High Performance NodeJS
High Performance NodeJSHigh Performance NodeJS
High Performance NodeJS
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs
 
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
 
All about NodeJS
All about NodeJSAll about NodeJS
All about NodeJS
 
Express node js
Express node jsExpress node js
Express node js
 

Similar to NodeJS

Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
NodeJs
NodeJsNodeJs
NodeJsdizabl
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
Node js
Node jsNode js
Node jshazzaz
 
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
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great againYana Gusti
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...BradNeuberg
 

Similar to NodeJS (20)

Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Node.js
Node.jsNode.js
Node.js
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
NodeJs
NodeJsNodeJs
NodeJs
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
node.js dao
node.js daonode.js dao
node.js dao
 
Node js
Node jsNode js
Node js
 
NodeJS
NodeJSNodeJS
NodeJS
 
Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)
 
Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
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
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great again
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 

More from .toster

Native look and feel bbui & alicejs
Native look and feel bbui & alicejsNative look and feel bbui & alicejs
Native look and feel bbui & alicejs.toster
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby.toster
 
Sinatra: прошлое, будущее и настоящее
Sinatra: прошлое, будущее и настоящееSinatra: прошлое, будущее и настоящее
Sinatra: прошлое, будущее и настоящее.toster
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record.toster
 
Decyphering Rails 3
Decyphering Rails 3Decyphering Rails 3
Decyphering Rails 3.toster
 
Understanding the Rails web model and scalability options
Understanding the Rails web model and scalability optionsUnderstanding the Rails web model and scalability options
Understanding the Rails web model and scalability options.toster
 
Михаил Черномордиков
Михаил ЧерномордиковМихаил Черномордиков
Михаил Черномордиков.toster
 
Андрей Юношев
Андрей Юношев Андрей Юношев
Андрей Юношев .toster
 
Алексей Тарасенко - Zeptolab
Алексей Тарасенко - ZeptolabАлексей Тарасенко - Zeptolab
Алексей Тарасенко - Zeptolab.toster
 
Maximiliano Firtman - Разработка приложений с помощью PhoneGap
Maximiliano Firtman - Разработка приложений с помощью PhoneGap Maximiliano Firtman - Разработка приложений с помощью PhoneGap
Maximiliano Firtman - Разработка приложений с помощью PhoneGap .toster
 
Вадим Башуров
Вадим БашуровВадим Башуров
Вадим Башуров.toster
 
Вадим Башуров - Как откусить от яблока лимон
Вадим Башуров - Как откусить от яблока лимонВадим Башуров - Как откусить от яблока лимон
Вадим Башуров - Как откусить от яблока лимон.toster
 
Вадим Башуров - Как откусить от яблока лимон
Вадим Башуров - Как откусить от яблока лимонВадим Башуров - Как откусить от яблока лимон
Вадим Башуров - Как откусить от яблока лимон.toster
 
Pablo Villalba -
Pablo Villalba - Pablo Villalba -
Pablo Villalba - .toster
 
Jordi Romero Api for-the-mobile-era
Jordi Romero Api for-the-mobile-eraJordi Romero Api for-the-mobile-era
Jordi Romero Api for-the-mobile-era.toster
 
Презентация Юрия Ветрова (Mail.ru Group)
Презентация Юрия Ветрова (Mail.ru Group)Презентация Юрия Ветрова (Mail.ru Group)
Презентация Юрия Ветрова (Mail.ru Group).toster
 
Внутренняя архитектура и устройства соц. сети "Одноклассники"
Внутренняя архитектура и устройства соц. сети "Одноклассники"Внутренняя архитектура и устройства соц. сети "Одноклассники"
Внутренняя архитектура и устройства соц. сети "Одноклассники".toster
 
Reusable Code, for good or for awesome!
Reusable Code, for good or for awesome!Reusable Code, for good or for awesome!
Reusable Code, for good or for awesome!.toster
 
Wild wild web. html5 era
Wild wild web. html5 eraWild wild web. html5 era
Wild wild web. html5 era.toster
 
Web matrix
Web matrixWeb matrix
Web matrix.toster
 

More from .toster (20)

Native look and feel bbui & alicejs
Native look and feel bbui & alicejsNative look and feel bbui & alicejs
Native look and feel bbui & alicejs
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby
 
Sinatra: прошлое, будущее и настоящее
Sinatra: прошлое, будущее и настоящееSinatra: прошлое, будущее и настоящее
Sinatra: прошлое, будущее и настоящее
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
Decyphering Rails 3
Decyphering Rails 3Decyphering Rails 3
Decyphering Rails 3
 
Understanding the Rails web model and scalability options
Understanding the Rails web model and scalability optionsUnderstanding the Rails web model and scalability options
Understanding the Rails web model and scalability options
 
Михаил Черномордиков
Михаил ЧерномордиковМихаил Черномордиков
Михаил Черномордиков
 
Андрей Юношев
Андрей Юношев Андрей Юношев
Андрей Юношев
 
Алексей Тарасенко - Zeptolab
Алексей Тарасенко - ZeptolabАлексей Тарасенко - Zeptolab
Алексей Тарасенко - Zeptolab
 
Maximiliano Firtman - Разработка приложений с помощью PhoneGap
Maximiliano Firtman - Разработка приложений с помощью PhoneGap Maximiliano Firtman - Разработка приложений с помощью PhoneGap
Maximiliano Firtman - Разработка приложений с помощью PhoneGap
 
Вадим Башуров
Вадим БашуровВадим Башуров
Вадим Башуров
 
Вадим Башуров - Как откусить от яблока лимон
Вадим Башуров - Как откусить от яблока лимонВадим Башуров - Как откусить от яблока лимон
Вадим Башуров - Как откусить от яблока лимон
 
Вадим Башуров - Как откусить от яблока лимон
Вадим Башуров - Как откусить от яблока лимонВадим Башуров - Как откусить от яблока лимон
Вадим Башуров - Как откусить от яблока лимон
 
Pablo Villalba -
Pablo Villalba - Pablo Villalba -
Pablo Villalba -
 
Jordi Romero Api for-the-mobile-era
Jordi Romero Api for-the-mobile-eraJordi Romero Api for-the-mobile-era
Jordi Romero Api for-the-mobile-era
 
Презентация Юрия Ветрова (Mail.ru Group)
Презентация Юрия Ветрова (Mail.ru Group)Презентация Юрия Ветрова (Mail.ru Group)
Презентация Юрия Ветрова (Mail.ru Group)
 
Внутренняя архитектура и устройства соц. сети "Одноклассники"
Внутренняя архитектура и устройства соц. сети "Одноклассники"Внутренняя архитектура и устройства соц. сети "Одноклассники"
Внутренняя архитектура и устройства соц. сети "Одноклассники"
 
Reusable Code, for good or for awesome!
Reusable Code, for good or for awesome!Reusable Code, for good or for awesome!
Reusable Code, for good or for awesome!
 
Wild wild web. html5 era
Wild wild web. html5 eraWild wild web. html5 era
Wild wild web. html5 era
 
Web matrix
Web matrixWeb matrix
Web matrix
 

Recently uploaded

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Recently uploaded (20)

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

NodeJS

  • 1. Intro to NodeJS Matthew Eernisse Toster Conference 2011-10-28
  • 2. Who am I? Matthew Eernisse Work at Yammer @mde on Twitter
  • 3. JavaScript at Yammer • Browsers (yammer.com Web UI) • Adobe AIR Desktop • V8 in Rails via TheRubyRacer • NodeJS
  • 4. NodeJS: “Evented I/O for V8 JavaScript” http://nodejs.org/
  • 5. Hello, NodeJS var http = require('http'); http.createServer(function (req, res) { 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/');
  • 7. History of SSJS • Netscape Enterprise Server (OG SSJS) • Microsoft IIS • Helma (now RingoJS) • Whitebeam • Zimki • Jaxer • Perservere • Nitro • Google App Engine • CouchDB • NodeJS
  • 8. Why NodeJS now? • Steve Yegge’s NBL post, 2007-02-10 • Competition in JavaScript interpreters • Simple, POSIX API • Non-blocking from the ground up; so are the libraries
  • 9. What is NodeJS good for? • Lightweight, networked apps • Proxies with embedded logic • Streaming data • System scripting • Evented realtime apps
  • 10. NodeJS is not good at complex database-backed Web applications. You can use Rails.
  • 12. NodeJS at Yammer • Development proxy • Jake for build and test (https://github.com/mde/jake) • Upload service for files and images (Geddy v0.2) • Browserless tests with FooUnit (https://github.com/foobarfighter/foounit) • Realtime, collaborative document-editing service
  • 13. Jake build tool https://github.com/mde/jake • Similar to Make or Rake • Tasks, prerequisites • File tasks, directory tasks • Namespaces • PackageTasks • Async task execution • Just executable JavaScript
  • 14. desc('This is the default task.'); task('default', function () { console.log('This is the default task.'); console.dir(arguments); }); namespace('foo', function () { desc('This the foo:bar task'); task('bar', function () { console.log('doing foo:bar task'); console.dir(arguments); }); desc('This the foo:baz task'); task('baz', ['default', 'foo:bar'], function () { console.log('doing foo:baz task'); console.dir(arguments); }); });
  • 15. desc('This is an asynchronous task.'); task('async', function () { setTimeout(function () { console.log('Hooray!'); complete(); }, 1000); }, true); desc('Calls the foo:bar task and its dependencies.'); task('invokeFooBar', function () { // Calls foo:bar and its deps jake.Task['foo:bar'].invoke(); // Does nothing jake.Task['foo:bar'].invoke(); // Only re-runs foo:bar, but not its dependencies jake.Task['foo:bar'].reenable(); jake.Task['foo:bar'].invoke(); });
  • 16. var fs = require('fs') , pkg = JSON.parse( fs.readFileSync('package.json').toString()) , version = pkg.version var t = new jake.PackageTask('jake', 'v' + version, function () { var fileList = [ 'Makefile' , 'Jakefile' , 'README.md' , 'package.json' , 'lib/*' , 'bin/*' , 'tests/*' ]; this.packageFiles.include(fileList); this.needTarGz = true; this.needTarBz2 = true; });
  • 17. Remote upload service • Minimal v1 in prod, Nov. 2010 • Redis, CORS XHR-push or JSONP for upload-progress reporting • Onboard thumbnailing, remote services for video and document post-processing • Three-machine cluster, not under a heavy load • Large file sizes (e.g., 1.5GB)
  • 18. Realtime, collaborative doc-editing service • In beta Oct. 21, 2011 (last week) • NodeJS, Socket.io, PostgreSQL • No production metrics yet for perf/scalability
  • 20. Awesome: JavaScript is simple and super-flexible
  • 21. Horrible: JavaScript is simple and super-flexible
  • 22. Asynchronous code • Even shelling out is async? • “1, 3, 2, go!” development • Evented and callback-based control-flow • A familiar model? • Async patterns and libraries
  • 23. 1, 3, 2, go! var asyncFun = function () { console.log('1'); setTimeout(function () { console.log('3'); }, 0); console.log('2'); console.log('go!'); };
  • 24. Sync fetch-and-update var fetchAndUpdate = function (params) { var items = db.fetch(someQuery); for (var i = 0, ii = items.length; i++) { item.update(params); } return true; };
  • 25. Async fetch-and-update var fetchAndUpdate = function (params, callback) { db.fetch(someQuery, function (items) { var count = 0; for (var i = 0, ii = items.length; i++) { item.update(params, function () { count++; if (count == ii) { callback(true); } }); } }); };
  • 26. Is this familiar? jQuery.ajax({ url: '/foo/bar.json' , success: function () { alert('yay!'); } }); jQuery('#foo').bind('click', function (e) { // Do some stuff });
  • 27. Async patterns and libs • Queue • Promise/deferred • In-flight registry
  • 28. Queue var asyncQueueHandler = function (items, handler, callback) { var queue = items.slice() , handleNextItem = function () { var next = queue.pop(); if (next) { handler(next, function () { handleNextItem(); }); } else { callback(); } }; handleNextItem(); };
  • 29. Promise var p = new yammer.util.Promise(); p.when('foo', 'bar', 'baz').then( function () { console.log('done!'); }); p.satisfy('foo'); p.satisfy('bar'); p.satisfy('baz'); p.then(function () { console.log('still done!'); });
  • 31. App dependencies • Third-party modules still may change rapidly • Maintain forks, push back patches where appropriate
  • 32. Debugging NodeJS • Callbacks in global scope have no stack • Assume you’re fucked • Default condition is a preemptible error • In-flight registry with uncaughtException handler
  • 33. FlightCheck https://github.com/mde/flight_check • Add items to in-flight registry • Per-item timeout • Configurable polling-interval • Define a timeout-handler
  • 34. In-flight registry var FlightCheck = require('flight_check').FlightCheck; var handler = function (req, resp) { var checker = new FlightCheck(function (key) { resp.writeHead(500); resp.end('Oops, something bad happened.'); }); checker.add('foo', 10000); doFoo(req, function (result) { if (result.ok) { checker.clear('foo'); // Do some other stuff resp.writeHead(200); resp.end('Hooray!'); } }); }; process.on('uncaughtException', function (err) { // Do some kind of logging });
  • 35. Visibility, metrics • Measure everything • Log everything • https://github.com/mikejihbe/metrics
  • 36. Ops • Communicative, consultative dev • Ask what is expected • Play nicely with others
  • 37. The future? • JS interpreters will keep improving • JS language will keep improving (see: JS.next) • NodeJS ecosystem will grow and mature • Try NodeJS, you’ll like it
  • 38. Matthew Eernisse http://twitter.com/mde Yammer Developer Center http://developer.yammer.com/

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n