SlideShare a Scribd company logo
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!
Playing With Fire - An Introduction to Node.js
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

More Related Content

PPTX
ES6 is Nigh
PPTX
All you need to know about the JavaScript event loop
PPTX
JavaScript on the Desktop
PPTX
The State of JavaScript (2015)
PDF
Boom! Promises/A+ Was Born
PPTX
JavaScript Engines and Event Loop
PDF
World of Logging
PPTX
The jsdom
ES6 is Nigh
All you need to know about the JavaScript event loop
JavaScript on the Desktop
The State of JavaScript (2015)
Boom! Promises/A+ Was Born
JavaScript Engines and Event Loop
World of Logging
The jsdom

What's hot (20)

KEY
Node.js - Best practices
PPTX
The State of JavaScript
PDF
A Gentle Introduction to Event Loops
PPTX
PDF
RxJS 5 in Depth
PDF
Add Some Fun to Your Functional Programming With RXJS
KEY
W3C HTML5 KIG-How to write low garbage real-time javascript
PDF
Event loop
PDF
Coroutines for Kotlin Multiplatform in Practise
PDF
Asynchronous PHP and Real-time Messaging
PDF
Asynchronous programming patterns in Perl
PDF
Asynchronous Programming FTW! 2 (with AnyEvent)
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
PDF
You will learn RxJS in 2017
PDF
React PHP: the NodeJS challenger
PDF
Будь первым
PDF
Go Concurrency
PPTX
Perl: Coro asynchronous
PPT
Full-Stack JavaScript with Node.js
Node.js - Best practices
The State of JavaScript
A Gentle Introduction to Event Loops
RxJS 5 in Depth
Add Some Fun to Your Functional Programming With RXJS
W3C HTML5 KIG-How to write low garbage real-time javascript
Event loop
Coroutines for Kotlin Multiplatform in Practise
Asynchronous PHP and Real-time Messaging
Asynchronous programming patterns in Perl
Asynchronous Programming FTW! 2 (with AnyEvent)
Matthew Eernisse, NodeJs, .toster {webdev}
You will learn RxJS in 2017
React PHP: the NodeJS challenger
Будь первым
Go Concurrency
Perl: Coro asynchronous
Full-Stack JavaScript with Node.js
Ad

Similar to Playing With Fire - An Introduction to Node.js (20)

PDF
NodeJS for Beginner
PDF
Nodejs - A quick tour (v6)
PPTX
Introduction to Node.js
PDF
Introduction to Node.js
ODP
Introduce about Nodejs - duyetdev.com
PPTX
PDF
Nodejs - A quick tour (v5)
KEY
Node.js - A practical introduction (v2)
PDF
Intro to node.js - Ran Mizrahi (27/8/2014)
PDF
Intro to node.js - Ran Mizrahi (28/8/14)
KEY
Node.js
PPTX
Introduction to node.js GDD
PDF
Introduction to Node.js
KEY
Writing robust Node.js applications
PPTX
Node.js: A Guided Tour
KEY
node.js: Javascript's in your backend
PDF
Nodejs - A quick tour (v4)
PPTX
introduction to node.js
PDF
Nodejs - A-quick-tour-v3
PDF
Nodejs a-practical-introduction-oredev
NodeJS for Beginner
Nodejs - A quick tour (v6)
Introduction to Node.js
Introduction to Node.js
Introduce about Nodejs - duyetdev.com
Nodejs - A quick tour (v5)
Node.js - A practical introduction (v2)
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (28/8/14)
Node.js
Introduction to node.js GDD
Introduction to Node.js
Writing robust Node.js applications
Node.js: A Guided Tour
node.js: Javascript's in your backend
Nodejs - A quick tour (v4)
introduction to node.js
Nodejs - A-quick-tour-v3
Nodejs a-practical-introduction-oredev
Ad

More from Mike Hagedorn (6)

PDF
Experienced Cloud Engineer Looking for New Roles
PDF
Couchbase Talk
PDF
Hacking the Internet of Things
PDF
Using OpenStack With Fog
PPTX
Exploring the Internet of Things Using Ruby
KEY
2011 a grape odyssey
Experienced Cloud Engineer Looking for New Roles
Couchbase Talk
Hacking the Internet of Things
Using OpenStack With Fog
Exploring the Internet of Things Using Ruby
2011 a grape odyssey

Recently uploaded (20)

PPTX
TLE Review Electricity (Electricity).pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Empathic Computing: Creating Shared Understanding
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Tartificialntelligence_presentation.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Approach and Philosophy of On baking technology
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
Machine Learning_overview_presentation.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
A comparative study of natural language inference in Swahili using monolingua...
TLE Review Electricity (Electricity).pptx
Unlocking AI with Model Context Protocol (MCP)
Empathic Computing: Creating Shared Understanding
Reach Out and Touch Someone: Haptics and Empathic Computing
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Tartificialntelligence_presentation.pptx
Group 1 Presentation -Planning and Decision Making .pptx
OMC Textile Division Presentation 2021.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Heart disease approach using modified random forest and particle swarm optimi...
Approach and Philosophy of On baking technology
A comparative analysis of optical character recognition models for extracting...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Encapsulation_ Review paper, used for researhc scholars
SOPHOS-XG Firewall Administrator PPT.pptx
Machine Learning_overview_presentation.pptx
Network Security Unit 5.pdf for BCA BBA.
cloud_computing_Infrastucture_as_cloud_p
A comparative study of natural language inference in Swahili using monolingua...

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 [email protected] [email protected]
  • 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? •Slow Engines •Javascript’s Perception (until recently) •Much better alternatives
  • 7. Y IZ BETTR NAO? Lots of Competition •SpiderMonkey •JavascriptCore •Chakra Javascript is cool now!
  • 9. 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
  • 10. 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
  • 11. WHY SHOULD YOU CARE? •It can handle LOTS of concurrent transactions
  • 12. WHY SHOULD YOU CARE? • 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
  • 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. NON-BLOCKING I/O (asynchronous is the new black)
  • 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 EVERYONE USING NON-BLOCKING I/O? There are cultural and infrastructural reasons
  • 23. 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.
  • 24. CULTURAL BIAS This code: puts(“Enter your name:”) var name = gets(function(name){ puts(“Name: “)+name); }) is rejected as TOO COMPLICATED
  • 25. 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.
  • 26. 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
  • 27. JAVASCRIPT... •Has had event loops from the beginning •Anonymous functions, closures •Single threaded •The culture of Javascript embraces evented programming
  • 28. GREAT FOR •Single Page Apps •Realtime updates •Processors/Crawlers •Process Monitoring •File Uploading
  • 29. INSTALLING OSX $ brew install 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 function longFunction(){}; process.nextTick(longFunction); Call longfunction on next time through event loop
  • 34. 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!');
  • 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 var app = express.createServer(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000);
  • 39. COFFEESCRIPT •“Little language that compiles to javascript” •“It’s just javascript” • More ruby-like
  • 40. COFFEESCRIPT •“Little language that compiles to javascript” •“It’s just javascript” • More ruby-like square = (x) -> x * x
  • 41. COFFEESCRIPT •“Little language that compiles to javascript” •“It’s just javascript” • More ruby-like square = (x) -> x * x square = function(x){ return x * x; }
  • 42. DEMO
  • 43. QUESTIONS? http://spkr8.com/t/8178 Mike Hagedorn Anthony Broussard @mwhagedorn @quantumpotato [email protected] [email protected]

Editor's Notes