KEMBAR78
Playing With Fire - An Introduction to Node.js
PLAYING WITH FIRE
  (ROCKET FUEL ACTUALLY)
    An introduction to node.js
Mike Hagedorn                  Anthony Broussard
   @mwhagedorn                      @quantumpotato
codemav.com/mwhagedorn          codemav.com/quantumpotato
mike@silverchairsolutions.com     anthony@chaione.com
IN THE BEGINNING...




    Server-side Javascript
IN THE BEGINNING...




    Server-side Javascript
          (it sucked)
SERVER-SIDE JAVASCRIPT




    •Netscape Livewire(1996)
    •Rhino(1997)
    •Several others since(like 50)
Y SO BAD?




•Slow Engines
•Javascript’s Perception (until recently)
•Much better alternatives
Y IZ BETTR NAO?




 Lots of Competition
 •SpiderMonkey
 •JavascriptCore
 •Chakra
                   Javascript is cool now!
WHAT IS NODE.JS?

•Created By Ryan Dahl
•Google’s V8 Engine (No DOM)
•Uses Nonblocking I/O
•Single Threaded
•A New Way To Build Scalable Network Platforms
WHY SHOULD YOU CARE?
                            •Its Fast
  > summary(node1$ttime)
      Min. 1st Qu.    Median      Mean   3rd Qu.     Max.
    0.0000   0.0000   1.0000    0.7437    1.0000 106.0000

  > summary(thin1$ttime)
     Min. 1st Qu. Median        Mean 3rd Qu.     Max.
    0.000   1.000   1.000      1.122   1.000   74.000

  > summary(narwhal1$ttime)
     Min. 1st Qu. Median     Mean 3rd Qu.        Max.
    15.00   22.00   23.00   23.74   24.00       88.00

  > summary(v8cgi1$ttime)
     Min. 1st Qu. Median        Mean 3rd Qu.     Max.
    12.00   13.00   13.00      14.49   18.00    39.00
WHY SHOULD YOU CARE?
•It can handle LOTS of concurrent transactions
WHY SHOULD YOU CARE?


  • Makes near real time things easy
  • Its small
  • Its Javascript
   •(Second most used language on Github)
WHO’S USING IT




Others:   http://doiop.com/rocket-node
HELLO WORLD
server.js
HELLO WORLD
server.js

 setTimeout(function(){
  console.log(“world”)
 },2000);
 console.log(“hello”);
HELLO WORLD
server.js

 setTimeout(function(){
  console.log(“world”)
 },2000);
 console.log(“hello”);




            $ node server.js
            hello
            world
HELLO WORLD
server.js

 setTimeout(function(){
  console.log(“world”)
 },2000);
 console.log(“hello”);
                               print(“hello”);
                               sleep(2000);
                               print(“world”);




            $ node server.js
            hello
            world
NON-BLOCKING I/O
 (asynchronous is the new black)
BLOCKING I/O

var a = db.query('SELECT A');
console.log('result a:', a);

var b = db.query('SELECT B');
console.log('result b:', b);

       Time = SUM(A, B)
NON-BLOCKING I/O

db.query('SELECT A', function(result) {
  console.log('result a:', result);
});

db.query('SELECT B', function(result) {
  console.log('result b:', result);
});

              Time = MAX(A, B)
SINGLE THREADED!
               You have to use callbacks!

db.query('SELECT A', function(result) {
    object.mySlowCall(result, function(){
        console.log(“my result”);
     })
});
WHY ISN’T EVERYONE USING
  NON-BLOCKING I/O?
  There are cultural and infrastructural
                  reasons
CULTURAL BIAS

We’re taught I/O with this:

puts(“Enter your name:”)
var name = gets()

We’re taught to demand input and do
       nothing until we have it.
CULTURAL BIAS

This code:
puts(“Enter your name:”)
var name = gets(function(name){
   puts(“Name: “)+name);
})

is rejected as TOO COMPLICATED
MISSING INFRASTRUCTURE
So why isn’t everyone using event loops?

Single threaded event loops require I/O to be non blocking

Most libraries are not.
OTHER APPROACHES?
•Twisted
•EventMachine
•Others
•Have lots of blocking libs to contend with
•From the start Node has never provided a blocking API
•Its a clean slate
•These approaches can be hard to use
JAVASCRIPT...

•Has had event loops from the beginning
•Anonymous functions, closures
•Single threaded
•The culture of Javascript embraces evented
programming
GREAT FOR

•Single Page Apps
•Realtime updates
•Processors/Crawlers
•Process Monitoring
•File Uploading
INSTALLING
OSX
 $ brew install node

Linux
$ git clone ....
 $ configure
 $ make

Windows
  Not Yet (version 0.6)
INSTALLING NPM



  •Node Package Manager
  •Similar to RubyGems, Python easy_install


$ curl http://npmjs.org/install.sh | sh
COMMON JS MODULES
hello.js

   exports.world = function(){
     return “Hello World”;
   }
main.js
 var hello = require(‘./hello’);
 var sys = require(‘sys’);
 sys.puts(hello.world());

   $ node main.js     #Hello World
EVENTS
 {EventEmitter} = require ‘events’
 emitter = new EventEmitter
 emitter.on ‘foo’, -> console.log ‘bar’
 emitter.emitusual new_monster event. And check out how much nicer our
      emitting the ‘foo’
         dependency graph has become!




http://pragprog.com/magazines/2011-08/content
       Imagine No Dependencies
         A lot of Node developers will tell you that attaching things to global rather
         than exports is a no-no. And if you’re packaging your code as a library, or trying
         to make your code reusable, then they’re right. But if you’re developing a
         standalone application, then go ahead and let yourself declare a few globals.
QUEUEING AN EVENT

function longFunction(){};
process.nextTick(longFunction);



Call longfunction on next time through event loop
EMITTING AN EVENT
var events = require('events');

var eventEmitter = new events.EventEmitter();

eventEmitter.on('someOccurence', function(message){
    console.log(message);
});

eventEmitter.emit('someOccurence', 'Something happened!');
MANAGING ASYNCHRONCITY
   A        B         C




         use async!
MANAGING ASYNCHRONCITY
        A                    B                        C

var operation = function(a_data, b_data, callback){
  async.series([
        function(as_callback),
        function(as_callback),
        function(err,results){ //[resulta, resultb]       }
        ]);
        }
MANAGING ASYNCHRONCITY
                 A
                                               C

                 B

var operation = function(a_data, b_data, callback){
  async.parallel([
        function(as_callback),
        function(as_callback),
        function(err,results){ //[resulta, resultb]   }
        ]);
        }
EXPRESS WEB FRAMEWORK

var app = express.createServer();

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

app.listen(3000);
COFFEESCRIPT
•“Little language that compiles to javascript”
•“It’s just javascript”
• More ruby-like
COFFEESCRIPT
  •“Little language that compiles to javascript”
  •“It’s just javascript”
  • More ruby-like
square = (x) -> x * x
COFFEESCRIPT
  •“Little language that compiles to javascript”
  •“It’s just javascript”
  • More ruby-like
square = (x) -> x * x

square = function(x){
   return x * x;
}
DEMO
QUESTIONS?
                  http://spkr8.com/t/8178



   Mike Hagedorn                Anthony Broussard
    @mwhagedorn                     @quantumpotato
mike@silverchairsolutions.com     anthony@chaione.com

Playing With Fire - An Introduction to Node.js

  • 1.
    PLAYING WITH FIRE (ROCKET FUEL ACTUALLY) An introduction to node.js
  • 2.
    Mike Hagedorn Anthony Broussard @mwhagedorn @quantumpotato codemav.com/mwhagedorn codemav.com/quantumpotato mike@silverchairsolutions.com anthony@chaione.com
  • 3.
    IN THE BEGINNING... Server-side Javascript
  • 4.
    IN THE BEGINNING... Server-side Javascript (it sucked)
  • 5.
    SERVER-SIDE JAVASCRIPT •Netscape Livewire(1996) •Rhino(1997) •Several others since(like 50)
  • 6.
    Y SO BAD? •SlowEngines •Javascript’s Perception (until recently) •Much better alternatives
  • 7.
    Y IZ BETTRNAO? Lots of Competition •SpiderMonkey •JavascriptCore •Chakra Javascript is cool now!
  • 9.
    WHAT IS NODE.JS? •CreatedBy Ryan Dahl •Google’s V8 Engine (No DOM) •Uses Nonblocking I/O •Single Threaded •A New Way To Build Scalable Network Platforms
  • 10.
    WHY SHOULD YOUCARE? •Its Fast > summary(node1$ttime) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.0000 0.0000 1.0000 0.7437 1.0000 106.0000 > summary(thin1$ttime) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.000 1.000 1.000 1.122 1.000 74.000 > summary(narwhal1$ttime) Min. 1st Qu. Median Mean 3rd Qu. Max. 15.00 22.00 23.00 23.74 24.00 88.00 > summary(v8cgi1$ttime) Min. 1st Qu. Median Mean 3rd Qu. Max. 12.00 13.00 13.00 14.49 18.00 39.00
  • 11.
    WHY SHOULD YOUCARE? •It can handle LOTS of concurrent transactions
  • 12.
    WHY SHOULD YOUCARE? • Makes near real time things easy • Its small • Its Javascript •(Second most used language on Github)
  • 13.
    WHO’S USING IT Others: http://doiop.com/rocket-node
  • 14.
  • 15.
    HELLO WORLD server.js setTimeout(function(){ console.log(“world”) },2000); console.log(“hello”);
  • 16.
    HELLO WORLD server.js setTimeout(function(){ console.log(“world”) },2000); console.log(“hello”); $ node server.js hello world
  • 17.
    HELLO WORLD server.js setTimeout(function(){ console.log(“world”) },2000); console.log(“hello”); print(“hello”); sleep(2000); print(“world”); $ node server.js hello world
  • 18.
  • 19.
    BLOCKING I/O var a= db.query('SELECT A'); console.log('result a:', a); var b = db.query('SELECT B'); console.log('result b:', b); Time = SUM(A, B)
  • 20.
    NON-BLOCKING I/O db.query('SELECT A',function(result) { console.log('result a:', result); }); db.query('SELECT B', function(result) { console.log('result b:', result); }); Time = MAX(A, B)
  • 21.
    SINGLE THREADED! You have to use callbacks! db.query('SELECT A', function(result) { object.mySlowCall(result, function(){ console.log(“my result”); }) });
  • 22.
    WHY ISN’T EVERYONEUSING NON-BLOCKING I/O? There are cultural and infrastructural reasons
  • 23.
    CULTURAL BIAS We’re taughtI/O with this: puts(“Enter your name:”) var name = gets() We’re taught to demand input and do nothing until we have it.
  • 24.
    CULTURAL BIAS This code: puts(“Enteryour name:”) var name = gets(function(name){ puts(“Name: “)+name); }) is rejected as TOO COMPLICATED
  • 25.
    MISSING INFRASTRUCTURE So whyisn’t everyone using event loops? Single threaded event loops require I/O to be non blocking Most libraries are not.
  • 26.
    OTHER APPROACHES? •Twisted •EventMachine •Others •Have lotsof blocking libs to contend with •From the start Node has never provided a blocking API •Its a clean slate •These approaches can be hard to use
  • 27.
    JAVASCRIPT... •Has had eventloops from the beginning •Anonymous functions, closures •Single threaded •The culture of Javascript embraces evented programming
  • 28.
    GREAT FOR •Single PageApps •Realtime updates •Processors/Crawlers •Process Monitoring •File Uploading
  • 29.
    INSTALLING OSX $ brewinstall node Linux $ git clone .... $ configure $ make Windows Not Yet (version 0.6)
  • 30.
    INSTALLING NPM •Node Package Manager •Similar to RubyGems, Python easy_install $ curl http://npmjs.org/install.sh | sh
  • 31.
    COMMON JS MODULES hello.js exports.world = function(){ return “Hello World”; } main.js var hello = require(‘./hello’); var sys = require(‘sys’); sys.puts(hello.world()); $ node main.js #Hello World
  • 32.
    EVENTS {EventEmitter} =require ‘events’ emitter = new EventEmitter emitter.on ‘foo’, -> console.log ‘bar’ emitter.emitusual new_monster event. And check out how much nicer our emitting the ‘foo’ dependency graph has become! http://pragprog.com/magazines/2011-08/content Imagine No Dependencies A lot of Node developers will tell you that attaching things to global rather than exports is a no-no. And if you’re packaging your code as a library, or trying to make your code reusable, then they’re right. But if you’re developing a standalone application, then go ahead and let yourself declare a few globals.
  • 33.
    QUEUEING AN EVENT functionlongFunction(){}; process.nextTick(longFunction); Call longfunction on next time through event loop
  • 34.
    EMITTING AN EVENT varevents = require('events'); var eventEmitter = new events.EventEmitter(); eventEmitter.on('someOccurence', function(message){ console.log(message); }); eventEmitter.emit('someOccurence', 'Something happened!');
  • 35.
    MANAGING ASYNCHRONCITY A B C use async!
  • 36.
    MANAGING ASYNCHRONCITY A B C var operation = function(a_data, b_data, callback){ async.series([ function(as_callback), function(as_callback), function(err,results){ //[resulta, resultb] } ]); }
  • 37.
    MANAGING ASYNCHRONCITY A C B var operation = function(a_data, b_data, callback){ async.parallel([ function(as_callback), function(as_callback), function(err,results){ //[resulta, resultb] } ]); }
  • 38.
    EXPRESS WEB FRAMEWORK varapp = express.createServer(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000);
  • 39.
    COFFEESCRIPT •“Little language thatcompiles to javascript” •“It’s just javascript” • More ruby-like
  • 40.
    COFFEESCRIPT •“Littlelanguage that compiles to javascript” •“It’s just javascript” • More ruby-like square = (x) -> x * x
  • 41.
    COFFEESCRIPT •“Littlelanguage that compiles to javascript” •“It’s just javascript” • More ruby-like square = (x) -> x * x square = function(x){ return x * x; }
  • 42.
  • 43.
    QUESTIONS? http://spkr8.com/t/8178 Mike Hagedorn Anthony Broussard @mwhagedorn @quantumpotato mike@silverchairsolutions.com anthony@chaione.com

Editor's Notes