SlideShare a Scribd company logo
Intro to NodeJS
       Matthew Eernisse
 Toster Conference 2011-10-28
             2001
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

Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
Ansible fest Presentation slides
Ansible fest Presentation slidesAnsible fest Presentation slides
Ansible fest Presentation slides
Aaron Carey
 
Ansible roles done right
Ansible roles done rightAnsible roles done right
Ansible roles done right
Dan Vaida
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
Saša Tatar
 
Testing your infrastructure with litmus
Testing your infrastructure with litmusTesting your infrastructure with litmus
Testing your infrastructure with litmus
Bram Vogelaar
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxy
Ismael Celis
 
DevOps with Fabric
DevOps with FabricDevOps with Fabric
DevOps with Fabric
Simone Federici
 
RingoJS
RingoJSRingoJS
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Tom Croucher
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
async_io
 
Django Celery
Django Celery Django Celery
Django Celery
Mat Clayton
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 
Using Ansible Dynamic Inventory with Amazon EC2
Using Ansible Dynamic Inventory with Amazon EC2Using Ansible Dynamic Inventory with Amazon EC2
Using Ansible Dynamic Inventory with Amazon EC2
Brian Schott
 
Using Ansible for Deploying to Cloud Environments
Using Ansible for Deploying to Cloud EnvironmentsUsing Ansible for Deploying to Cloud Environments
Using Ansible for Deploying to Cloud Environments
ahamilton55
 
wwc start-launched
wwc start-launchedwwc start-launched
wwc start-launchedMat Schaffer
 
Ansible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife OrchestrationAnsible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife Orchestration
bcoca
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
Domenic Denicola
 

What's hot (20)

Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Ansible fest Presentation slides
Ansible fest Presentation slidesAnsible fest Presentation slides
Ansible fest Presentation slides
 
Ansible roles done right
Ansible roles done rightAnsible roles done right
Ansible roles done right
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Node.js
Node.jsNode.js
Node.js
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Testing your infrastructure with litmus
Testing your infrastructure with litmusTesting your infrastructure with litmus
Testing your infrastructure with litmus
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxy
 
DevOps with Fabric
DevOps with FabricDevOps with Fabric
DevOps with Fabric
 
RingoJS
RingoJSRingoJS
RingoJS
 
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Django Celery
Django Celery Django Celery
Django Celery
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Using Ansible Dynamic Inventory with Amazon EC2
Using Ansible Dynamic Inventory with Amazon EC2Using Ansible Dynamic Inventory with Amazon EC2
Using Ansible Dynamic Inventory with Amazon EC2
 
Using Ansible for Deploying to Cloud Environments
Using Ansible for Deploying to Cloud EnvironmentsUsing Ansible for Deploying to Cloud Environments
Using Ansible for Deploying to Cloud Environments
 
wwc start-launched
wwc start-launchedwwc start-launched
wwc start-launched
 
Ansible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife OrchestrationAnsible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife Orchestration
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 

Similar to Matthew Eernisse, NodeJs, .toster {webdev}

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
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
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
NodeJs
NodeJsNodeJs
NodeJs
dizabl
 
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
soft-shake.ch
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
Felix Geisendörfer
 
node.js dao
node.js daonode.js dao
node.js dao
Vladimir Miguro
 
Node js
Node jsNode js
Node jshazzaz
 
NodeJS
NodeJSNodeJS
NodeJS
Alok Guha
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
dion
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascriptEldar Djafarov
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
Pascal Rettig
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great again
Yana Gusti
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"EPAM Systems
 
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
FITC
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
Felix Geisendörfer
 

Similar to Matthew Eernisse, NodeJs, .toster {webdev} (20)

NodeJS
NodeJSNodeJS
NodeJS
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
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
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
NodeJs
NodeJsNodeJs
NodeJs
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
 
node.js dao
node.js daonode.js dao
node.js dao
 
Node js
Node jsNode js
Node js
 
NodeJS
NodeJSNodeJS
NodeJS
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great again
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао 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
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 

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

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 

Recently uploaded (20)

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 

Matthew Eernisse, NodeJs, .toster {webdev}

  • 1. Intro to NodeJS Matthew Eernisse Toster Conference 2011-10-28 2001
  • 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/