SlideShare a Scribd company logo
node.js
JavaScript’s in your backend



            David Padbury
       http://davidpadbury.com
           @davidpadbury
Programming 101
static void Main()
{
    int result = Add(2, 2);
    Console.WriteLine("2+2 = {0}", result);
}

static int Add(int n1, int n2)
{
    return n1 + n2;
}
static void Main()
{
    string name = GetName();
    Console.WriteLine("Hi {0}", name);
}

static string GetName()
{
    return Console.ReadLine();
}
Looks pretty much the same?
static void Main()     Normal Method Call
{
    int result = Add(2, 2);
    Console.WriteLine("2+2 = {0}", result);
}

static int Add(int n1, int n2)
{
    return n1 + n2;
}
         Does some stuff in processor cache or RAM
static void Main()     Normal Method Call
{
    string name = GetName();
    Console.WriteLine("Hi {0}", name);
}

static string GetName()
{
    return Console.ReadLine();
}
                   Blocks until ready
What’s the big deal?

Well, let’s think about what we do in a web server...
public ActionResult View(int id)
{
    var product = northwindDataContext.Get(id);

    return View(product);
}



               Blocking Network Call (IO)
Think about what we really do on a web server...
Call Databases
    Grab Files


    Think about what we really do on a web server...


Pull from caches

                    Wait on other connections
It’s all I/O
CPU Cycles


     L1   3

     L2   14

   RAM    250

   Disk         41,000,000

Network                                                          240,000,000

          0      75,000,000        150,000,000          225,000,000   300,000,000

                         http://nodejs.org/jsconf.pdf
Comparatively,
 I/O pretty
 much takes
  forever...
And yet, we write code exactly the same.
“we’re doing it wrong”
                       - Ryan Dahl, node.js creator




http://www.yuiblog.com/blog/2010/05/20/video-dahl/
So I can guess what you’re thinking,
  “What about multi-threading?”
Yep, mainstream web servers like Apache and IIS* use a

                               Thread Per Connection




* Well, technically IIS doesn’t quite have a thread per connection as there’s some kernel level stuff which will talk to IIS/
 ASP.NET depending on your configuration and it’s all quite complicated. But for the sake of this presentation we’ll say
                          it’s a thread per connection as it’s pretty darn close in all practical terms.
  If you’d like to talk about this more feel free to chat to me afterwards, I love spending my spare time talking about
                                                       threading in IIS.
                                                           HONEST.
Threading ain’t free




Context Switching               Execution Stacks take Memory
Sure - but what else?
An Event Loop

Use a single thread - do little pieces of work, and do ‘em quickly
With an event loop, you ask it
to do something and it’ll get
 back to you when it’s done
But, a single thread?
nginx is event based




                 (higher is better)
http://blog.webfaction.com/a-little-holiday-present
(lower is better)
http://blog.webfaction.com/a-little-holiday-present
Being event based is actually a pretty good
 way of writing heavily I/O bound servers
So why don’t we?
We’d have to completely change how we write code

 public ActionResult View(int id)
 {
     var product = northwindDataContext.Get(id);

     return View(product);
                             Blocking Call
 }
To something where we could easily write non-blocking code
  public void View(HttpResponse response, int id)
  {                              Non-blocking Call
      northwindDataContext.Get(id, (product) => {
          response.View(product);
      });
  }
                                                   Anonymous Function
                 Callback
C
Most old school languages can’t do this
*cough*




Java
 *cough*
Even if we had a language that made
writing callbacks easy (like C#), we’d need
    a platform that had minimal to no
         blocking I/O operations.
If only we had a language which was designed to
   be inherently single threaded, had first class
    functions and closures built in, and had no
        preconceived notions about I/O?

 Wouldn’t it also be really handy if half* of the
  developers in the world already knew it?


                     (you can probably guess where this is going...)

     *The guy speaking completely made that up for the sake of this slide. but he’s pretty sure there are quite a few
node.js: Javascript's in your backend
http://nodejs.org/
Node.js is a set of JavaScript bindings for
writing high-performance network servers
With the goal of making developing high-
 performance network servers easy
Built on Google’s
  V8 js engine
 (so it’s super quick)
Exposes only non-blocking I/O API’s
Stops us writing code that
      behaves badly
Demo
Basic node.js
console.log('Hello');

setTimeout(function() {
        console.log('World');
}, 2000);
Prints Immediately   $node app.js
                     Hello
                                    Waits two seconds
                     World
                     $   Exits as there’s nothing left to do
Node comes with a large set of libraries
Node comes with a large set of libraries

 Timers   Processes      Events      Buffers


Streams    Crypto      File System    REPL


  Net      HTTP          HTTPS       TLS/SSL


            DNS       UDP/Datagram
Libraries are ‘imported’ using the require function
Just a function call


  var http = require('http'),
      fs = require('fs');

Returns object exposing the API
Demo
Require and standard modules
Every request is just a callback
var http = require('http');

var server = http.createServer(function(req, res) {

      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('Hello from node.js!');
});

server.listen(3000);
console.log('Server started on 3000');
var fs = require('fs'),
                                             Doesn’t block to read file
        http = require('http');

var server = http.createServer(function(req, res) {

        fs.readFile('./data.txt', function(err, data) {

              if (err) {
                  res.writeHead(500, { 'Content-Type': 'text/plain' });
                  res.end(err.message);
              } else {
                  res.writeHead(200, { 'Content-Type': 'text/plain' });
                  res.end(data);
              }

        });

});   Server can deal with other requests while waiting for file
server.listen(3000);
console.log('Server listening on 3000');
Node libraries are structured as
     CommonJS modules




http://www.commonjs.org/specs/modules/1.0/
Libraries are evaluated in their own context

Only way to share API is to attach to exports
require function returns exports
Demo
Writing custom modules
/* people.js */

function Person(name) {
    this.name = name;
}

Person.prototype = {
    sayHi: function() {
        console.log("Hi, I'm " + this.name);
    }
}              Attaching API to exports

exports.createPerson = function(name) {
    return new Person(name);
};
exports from module are returned


var people = require('./people');                  File path

var barry = people.createPerson('Barry');

barry.sayHi();     // Hi, I'm Barry

console.log( typeof Person ); // undefined


     Internals of module don’t exist in this context
Despite being a relatively new runtime,
there are a massive number of open source libraries available
Official list alone has 718 released modules
        https://github.com/ry/node/wiki/modules

                     (as of Feb 2011)
Modules for just about everything you could think of,
          •Web Application Servers
          •Static File Servers
          •Web Middleware
          •Database (couchdb, mongodb, mysql, postgres, sqlite, etc..)
          •Templating
          •Build & Production
          •Security
          •SMTP
          •TCP/IP
          •Web Services
          •Message Queues
          •Testing
          •XML
          •Command Line Parsers
          •Parser Generators
          •Debugging tools
          •Compression
          •Graphics
          •Payment Gateways
          •Clients for many public API’s (facebook, flickr, last.fm, twitter, etc...)
          •Internationalization


 and probably a lot for things you’ve never heard of
So you can just pull them down and reference
              them on their files.

   However once libraries start depending on
other libraries, and we start installing quite a few,

        Well, we know how this ends up...
Messy
Established platforms have tools to help with this




              Node is no different
npm is a package manager for
node. You can use it to
install and publish your
node programs. It manages
dependencies and does other
cool stuff.
          http://npmjs.org/
$npm install <name>
Module details and dependencies are expressed
   in CommonJS standard package.json




         http://wiki.commonjs.org/wiki/Packages/1.0
{
  "name"          : "vows",
  "description"   : "Asynchronous BDD & continuous
integration for node.js",
  "url"           : "http://vowsjs.org",
  "keywords"      : ["testing", "spec", "test", "BDD"],
  "author"        : "Alexis Sellier <self@cloudhead.net>",
  "contributors" : [],
  "dependencies" : {"eyes": ">=0.1.6"},
  "main"          : "./lib/vows",
  "bin"           : { "vows": "./bin/vows" },
  "directories"   : { "test": "./test" },
  "version"       : "0.5.6",
  "engines"       : {"node": ">=0.2.6"}
}


                   https://github.com/cloudhead/vows/
Okay.

So node’s a nice idea in theory and there’s enough there to be
          compared to other established platforms.

                   But where does it rock?
Web apps are growing up
In my mind, there are two major challenges
facing the next generation of web applications.
Being real-time
Being everywhere
Most web application platforms struggle, or at
 least don’t much help with these challenges
Node.js does
Being everywhere
Although it’s nice to think about writing applications
 for just new versions of Chrome, Firefox and IE9.

 We should strive to get our applications working
                  everywhere*.




                    *to at least some degree
And I’m not just talking about
Browsers are everywhere
With traditional web applications
           there are two distinct sides




Client                                       Server
With node.js both sides speak the same
language making it easier to work together
The server can help the
browser fill out functionality
      that it’s missing
Demo
jQuery on the Server using jsdom
var jsdom = require('jsdom'),
        window = jsdom.jsdom().createWindow(),
        document = window.document,
        htmlEl = document.getElementsByTagName('html')[0];

jsdom.jQueryify(window, function() {
        var $ = window.jQuery;

        $('<div />').addClass('servermade').appendTo('body');

        $('.servermade').text('And selectors work fine!');

        console.log( htmlEl.outerHTML );
});
Demo
Sharing code between Server and Client
(function(exports) {

   exports.createChartOptions = function(data) {
       var values = parseData(data);

       return {
           ...
       };
   }

})(typeof window !== 'undefined' ? (window.demo = {}) : exports);


      Attaches API to              Attaches API to exports in node.js
  window.demo in browser               to be returned by require
Being real-time
HTTP


         Request

Client              Server
         Response
Not so good for pushing



Client                     Server
         Update. Erm....
             Fail
Web Sockets



Proper Duplex Communication!
But it’s only in very recent browsers




And due to protocol concerns it’s now disabled even in recent browsers
But you’ve probably noticed that
applications have been doing this for years




  We’ve got some pretty sophisticated
   methods of emulating it, even in IE
node.js: Javascript's in your backend
WebSockets

     Silverlight / Flash

IE HTML Document ActiveX

    AJAX Long Polling

 AJAX multipart streaming

     Forever IFrame

      JSONP Polling
All of those require a server holding open a
     connection for as long as possible.
Thread-per-connection web
 servers struggle with this
Node.js doesn’t even break a sweat
var socket = io.listen(server);
socket.on('connection', function(client){
  // new client is here!
  client.on('message', function(){ … })
  client.on('disconnect', function(){ … })
});
Demo
Real-time web using socket.io
var socket = io.listen(server),
        counter = 0;

socket.on('connection', function(client) {
                              No multithreading, so no
      counter = counter + 1;     race condition!
      socket.broadcast(counter);

      client.on('disconnect', function() {
          counter = counter - 1;
          socket.broadcast(counter);
      });

});
Node.js is young, but it’s
   growing up fast
So how do you get started with node?
If you’re on Mac or Linux then you’re good to go
                http://nodejs.org/
If you’re on Windows
you’re going to be a little
       disappointed
Currently the best way to get start on Windows is
     hosting inside a Linux VM and ssh’ing it.
http://www.lazycoder.com/weblog/2010/03/18/getting-started-with-node-js-on-windows/




  Proper Windows support will be coming soon.

                     http://nodejs.org/v0.4_announcement.html
I think that node is super exciting and that you
    should start experimenting with it today
But even if you don’t, other Web
Frameworks are watching and it will
  almost certainly influence them
http://nodejs.org/

http://groups.google.com/group/nodejs

      #nodejs on freenode.net

       http://howtonode.org/

https://github.com/alexyoung/nodepad
Questions?
// Thanks for listening!

return;
Image Attributions
Old man exmouth market, Daniel2005 - http://www.flickr.com/photos/loshak/530449376/
needle, Robert Parviainen - http://www.flickr.com/photos/rtv/256102280/
Skeptical, Gabi in Austin - http://www.flickr.com/photos/gabrielleinaustin/2454197457/
Javascript!=Woo(), Aaron Cole - http://www.flickr.com/photos/awcole72/1936225899/
Day 22 - V8 Kompressor, Fred - http://www.flickr.com/photos/freeed/5379562284/
The Finger, G Clement - http://www.flickr.com/photos/illumiquest/2749137895/
A Messy Tangle of Wires, Adam - http://www.flickr.com/photos/mr-numb/4753899767/
7-365 I am ready to pull my hair out..., Bram Cymet - http://www.flickr.com/photos/bcymet/3292063588/
Epic battle, Roger Mateo Poquet - http://www.flickr.com/photos/el_momento_i_sitio_apropiados/5166623452/
World's Tiniest, Angelina :) - http://www.flickr.com/photos/angelinawb/266143527/
A Helping Hand, Jerry Wong - http://www.flickr.com/photos/wongjunhao/4285302488/
[108/365] Ill-advised, Pascal - http://www.flickr.com/photos/pasukaru76/5268559005/
Gymnastics Artistic, Alan Chia - http://www.flickr.com/photos/seven13avenue/2758702332/
metal, Marc Brubaker - http://www.flickr.com/photos/hometownzero/136283072/
Quiet, or You'll see Father Christmas again, theirhistory - http://www.flickr.com/photos/
22326055@N06/3444756625/
Day 099, kylesteed - http://www.flickr.com/photos/kylesteeddesign/4507065826/
Spectators in the grandstand at the Royal Adelaide Show, State Library of South Australia - http://
www.flickr.com/photos/state_library_south_australia/3925493310/

More Related Content

What's hot (20)

PDF
Node.js - A Quick Tour
Felix Geisendörfer
 
PDF
NodeJS for Beginner
Apaichon Punopas
 
PDF
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
PDF
Server Side Event Driven Programming
Kamal Hussain
 
PDF
Nodejs Explained with Examples
Gabriele Lana
 
PDF
Node.js Explained
Jeff Kunkle
 
PDF
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
PPTX
Java script at backend nodejs
Amit Thakkar
 
PPT
Node js presentation
martincabrera
 
PDF
Getting started with developing Nodejs
Phil Hawksworth
 
PDF
Philly Tech Week Introduction to NodeJS
Ross Kukulinski
 
PDF
Nodejs in Production
William Bruno Moraes
 
PPT
RESTful API In Node Js using Express
Jeetendra singh
 
PPT
Nodejs Event Driven Concurrency for Web Applications
Ganesh Iyer
 
KEY
Building a real life application in node js
fakedarren
 
PPTX
Node.js Workshop - Sela SDP 2015
Nir Noy
 
PDF
Node.js
Jan Dillmann
 
PDF
Node Architecture and Getting Started with Express
jguerrero999
 
PPTX
Introduction to Node.js
Vikash Singh
 
PPTX
Node.js Patterns for Discerning Developers
cacois
 
Node.js - A Quick Tour
Felix Geisendörfer
 
NodeJS for Beginner
Apaichon Punopas
 
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
Server Side Event Driven Programming
Kamal Hussain
 
Nodejs Explained with Examples
Gabriele Lana
 
Node.js Explained
Jeff Kunkle
 
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Java script at backend nodejs
Amit Thakkar
 
Node js presentation
martincabrera
 
Getting started with developing Nodejs
Phil Hawksworth
 
Philly Tech Week Introduction to NodeJS
Ross Kukulinski
 
Nodejs in Production
William Bruno Moraes
 
RESTful API In Node Js using Express
Jeetendra singh
 
Nodejs Event Driven Concurrency for Web Applications
Ganesh Iyer
 
Building a real life application in node js
fakedarren
 
Node.js Workshop - Sela SDP 2015
Nir Noy
 
Node.js
Jan Dillmann
 
Node Architecture and Getting Started with Express
jguerrero999
 
Introduction to Node.js
Vikash Singh
 
Node.js Patterns for Discerning Developers
cacois
 

Viewers also liked (13)

PDF
JavaScript: From the ground up
David Padbury
 
PDF
HTML5 for the Silverlight Guy
David Padbury
 
KEY
Node.js - Best practices
Felix Geisendörfer
 
PDF
Node.js Enterprise Middleware
Behrad Zari
 
ODP
Node.js architecture (EN)
Timur Shemsedinov
 
PPTX
NodeJS - Server Side JS
Ganesh Kondal
 
PDF
Architecting large Node.js applications
Sergi Mansilla
 
PPTX
Nodejs intro
Ndjido Ardo BAR
 
PDF
Modern UI Development With Node.js
Ryan Anklam
 
PDF
Anatomy of a Modern Node.js Application Architecture
AppDynamics
 
PDF
The 20 Worst Questions to Ask an Interviewer
Robert Half
 
PDF
Node.js and The Internet of Things
Losant
 
PPTX
6 basic steps of software development process
Riant Soft
 
JavaScript: From the ground up
David Padbury
 
HTML5 for the Silverlight Guy
David Padbury
 
Node.js - Best practices
Felix Geisendörfer
 
Node.js Enterprise Middleware
Behrad Zari
 
Node.js architecture (EN)
Timur Shemsedinov
 
NodeJS - Server Side JS
Ganesh Kondal
 
Architecting large Node.js applications
Sergi Mansilla
 
Nodejs intro
Ndjido Ardo BAR
 
Modern UI Development With Node.js
Ryan Anklam
 
Anatomy of a Modern Node.js Application Architecture
AppDynamics
 
The 20 Worst Questions to Ask an Interviewer
Robert Half
 
Node.js and The Internet of Things
Losant
 
6 basic steps of software development process
Riant Soft
 

Similar to node.js: Javascript's in your backend (20)

PDF
Introduction to Node.js
Richard Lee
 
PPTX
Node.js: A Guided Tour
cacois
 
PDF
Node.js introduction
Prasoon Kumar
 
PPTX
Nodejs
Vinod Kumar Marupu
 
KEY
Node.js - A practical introduction (v2)
Felix Geisendörfer
 
PDF
Nodejs - A quick tour (v5)
Felix Geisendörfer
 
PDF
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
Ivan Loire
 
PDF
Nodejs - A quick tour (v6)
Felix Geisendörfer
 
PDF
Nodejs a-practical-introduction-oredev
Felix Geisendörfer
 
KEY
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
PPTX
Beginners Node.js
Khaled Mosharraf
 
ODP
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
PPTX
Proposal
Constantine Priemski
 
KEY
Node.js - As a networking tool
Felix Geisendörfer
 
PDF
Node.js - async for the rest of us.
Mike Brevoort
 
PDF
Nodejs - Should Ruby Developers Care?
Felix Geisendörfer
 
PPT
18_Node.js.ppt
KhalilSalhi7
 
KEY
Node.js
Ian Oxley
 
PDF
Nodejs - A quick tour (v4)
Felix Geisendörfer
 
PPT
18_Node.js.ppt
MaulikShah516542
 
Introduction to Node.js
Richard Lee
 
Node.js: A Guided Tour
cacois
 
Node.js introduction
Prasoon Kumar
 
Node.js - A practical introduction (v2)
Felix Geisendörfer
 
Nodejs - A quick tour (v5)
Felix Geisendörfer
 
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
Ivan Loire
 
Nodejs - A quick tour (v6)
Felix Geisendörfer
 
Nodejs a-practical-introduction-oredev
Felix Geisendörfer
 
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
Beginners Node.js
Khaled Mosharraf
 
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Node.js - As a networking tool
Felix Geisendörfer
 
Node.js - async for the rest of us.
Mike Brevoort
 
Nodejs - Should Ruby Developers Care?
Felix Geisendörfer
 
18_Node.js.ppt
KhalilSalhi7
 
Node.js
Ian Oxley
 
Nodejs - A quick tour (v4)
Felix Geisendörfer
 
18_Node.js.ppt
MaulikShah516542
 

Recently uploaded (20)

PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
Sound the Alarm: Detection and Response
VICTOR MAESTRE RAMIREZ
 
PDF
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PDF
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
PDF
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
Sound the Alarm: Detection and Response
VICTOR MAESTRE RAMIREZ
 
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
Practical Applications of AI in Local Government
OnBoard
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 

node.js: Javascript's in your backend

  • 1. node.js JavaScript’s in your backend David Padbury http://davidpadbury.com @davidpadbury
  • 3. static void Main() { int result = Add(2, 2); Console.WriteLine("2+2 = {0}", result); } static int Add(int n1, int n2) { return n1 + n2; }
  • 4. static void Main() { string name = GetName(); Console.WriteLine("Hi {0}", name); } static string GetName() { return Console.ReadLine(); }
  • 5. Looks pretty much the same?
  • 6. static void Main() Normal Method Call { int result = Add(2, 2); Console.WriteLine("2+2 = {0}", result); } static int Add(int n1, int n2) { return n1 + n2; } Does some stuff in processor cache or RAM
  • 7. static void Main() Normal Method Call { string name = GetName(); Console.WriteLine("Hi {0}", name); } static string GetName() { return Console.ReadLine(); } Blocks until ready
  • 8. What’s the big deal? Well, let’s think about what we do in a web server...
  • 9. public ActionResult View(int id) { var product = northwindDataContext.Get(id); return View(product); } Blocking Network Call (IO)
  • 10. Think about what we really do on a web server...
  • 11. Call Databases Grab Files Think about what we really do on a web server... Pull from caches Wait on other connections
  • 13. CPU Cycles L1 3 L2 14 RAM 250 Disk 41,000,000 Network 240,000,000 0 75,000,000 150,000,000 225,000,000 300,000,000 http://nodejs.org/jsconf.pdf
  • 14. Comparatively, I/O pretty much takes forever...
  • 15. And yet, we write code exactly the same.
  • 16. “we’re doing it wrong” - Ryan Dahl, node.js creator http://www.yuiblog.com/blog/2010/05/20/video-dahl/
  • 17. So I can guess what you’re thinking, “What about multi-threading?”
  • 18. Yep, mainstream web servers like Apache and IIS* use a Thread Per Connection * Well, technically IIS doesn’t quite have a thread per connection as there’s some kernel level stuff which will talk to IIS/ ASP.NET depending on your configuration and it’s all quite complicated. But for the sake of this presentation we’ll say it’s a thread per connection as it’s pretty darn close in all practical terms. If you’d like to talk about this more feel free to chat to me afterwards, I love spending my spare time talking about threading in IIS. HONEST.
  • 19. Threading ain’t free Context Switching Execution Stacks take Memory
  • 20. Sure - but what else?
  • 21. An Event Loop Use a single thread - do little pieces of work, and do ‘em quickly
  • 22. With an event loop, you ask it to do something and it’ll get back to you when it’s done
  • 23. But, a single thread?
  • 24. nginx is event based (higher is better) http://blog.webfaction.com/a-little-holiday-present
  • 26. Being event based is actually a pretty good way of writing heavily I/O bound servers
  • 28. We’d have to completely change how we write code public ActionResult View(int id) { var product = northwindDataContext.Get(id); return View(product); Blocking Call }
  • 29. To something where we could easily write non-blocking code public void View(HttpResponse response, int id) { Non-blocking Call northwindDataContext.Get(id, (product) => { response.View(product); }); } Anonymous Function Callback
  • 30. C Most old school languages can’t do this
  • 32. Even if we had a language that made writing callbacks easy (like C#), we’d need a platform that had minimal to no blocking I/O operations.
  • 33. If only we had a language which was designed to be inherently single threaded, had first class functions and closures built in, and had no preconceived notions about I/O? Wouldn’t it also be really handy if half* of the developers in the world already knew it? (you can probably guess where this is going...) *The guy speaking completely made that up for the sake of this slide. but he’s pretty sure there are quite a few
  • 36. Node.js is a set of JavaScript bindings for writing high-performance network servers
  • 37. With the goal of making developing high- performance network servers easy
  • 38. Built on Google’s V8 js engine (so it’s super quick)
  • 40. Stops us writing code that behaves badly
  • 42. console.log('Hello'); setTimeout(function() { console.log('World'); }, 2000);
  • 43. Prints Immediately $node app.js Hello Waits two seconds World $ Exits as there’s nothing left to do
  • 44. Node comes with a large set of libraries
  • 45. Node comes with a large set of libraries Timers Processes Events Buffers Streams Crypto File System REPL Net HTTP HTTPS TLS/SSL DNS UDP/Datagram
  • 46. Libraries are ‘imported’ using the require function
  • 47. Just a function call var http = require('http'), fs = require('fs'); Returns object exposing the API
  • 49. Every request is just a callback var http = require('http'); var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello from node.js!'); }); server.listen(3000); console.log('Server started on 3000');
  • 50. var fs = require('fs'), Doesn’t block to read file http = require('http'); var server = http.createServer(function(req, res) { fs.readFile('./data.txt', function(err, data) { if (err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end(err.message); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); } }); }); Server can deal with other requests while waiting for file server.listen(3000); console.log('Server listening on 3000');
  • 51. Node libraries are structured as CommonJS modules http://www.commonjs.org/specs/modules/1.0/
  • 52. Libraries are evaluated in their own context Only way to share API is to attach to exports
  • 55. /* people.js */ function Person(name) { this.name = name; } Person.prototype = { sayHi: function() { console.log("Hi, I'm " + this.name); } } Attaching API to exports exports.createPerson = function(name) { return new Person(name); };
  • 56. exports from module are returned var people = require('./people'); File path var barry = people.createPerson('Barry'); barry.sayHi(); // Hi, I'm Barry console.log( typeof Person ); // undefined Internals of module don’t exist in this context
  • 57. Despite being a relatively new runtime, there are a massive number of open source libraries available
  • 58. Official list alone has 718 released modules https://github.com/ry/node/wiki/modules (as of Feb 2011)
  • 59. Modules for just about everything you could think of, •Web Application Servers •Static File Servers •Web Middleware •Database (couchdb, mongodb, mysql, postgres, sqlite, etc..) •Templating •Build & Production •Security •SMTP •TCP/IP •Web Services •Message Queues •Testing •XML •Command Line Parsers •Parser Generators •Debugging tools •Compression •Graphics •Payment Gateways •Clients for many public API’s (facebook, flickr, last.fm, twitter, etc...) •Internationalization and probably a lot for things you’ve never heard of
  • 60. So you can just pull them down and reference them on their files. However once libraries start depending on other libraries, and we start installing quite a few, Well, we know how this ends up...
  • 61. Messy
  • 62. Established platforms have tools to help with this Node is no different
  • 63. npm is a package manager for node. You can use it to install and publish your node programs. It manages dependencies and does other cool stuff. http://npmjs.org/
  • 65. Module details and dependencies are expressed in CommonJS standard package.json http://wiki.commonjs.org/wiki/Packages/1.0
  • 66. { "name" : "vows", "description" : "Asynchronous BDD & continuous integration for node.js", "url" : "http://vowsjs.org", "keywords" : ["testing", "spec", "test", "BDD"], "author" : "Alexis Sellier <[email protected]>", "contributors" : [], "dependencies" : {"eyes": ">=0.1.6"}, "main" : "./lib/vows", "bin" : { "vows": "./bin/vows" }, "directories" : { "test": "./test" }, "version" : "0.5.6", "engines" : {"node": ">=0.2.6"} } https://github.com/cloudhead/vows/
  • 67. Okay. So node’s a nice idea in theory and there’s enough there to be compared to other established platforms. But where does it rock?
  • 68. Web apps are growing up
  • 69. In my mind, there are two major challenges facing the next generation of web applications.
  • 72. Most web application platforms struggle, or at least don’t much help with these challenges
  • 75. Although it’s nice to think about writing applications for just new versions of Chrome, Firefox and IE9. We should strive to get our applications working everywhere*. *to at least some degree
  • 76. And I’m not just talking about
  • 78. With traditional web applications there are two distinct sides Client Server
  • 79. With node.js both sides speak the same language making it easier to work together
  • 80. The server can help the browser fill out functionality that it’s missing
  • 81. Demo jQuery on the Server using jsdom
  • 82. var jsdom = require('jsdom'), window = jsdom.jsdom().createWindow(), document = window.document, htmlEl = document.getElementsByTagName('html')[0]; jsdom.jQueryify(window, function() { var $ = window.jQuery; $('<div />').addClass('servermade').appendTo('body'); $('.servermade').text('And selectors work fine!'); console.log( htmlEl.outerHTML ); });
  • 83. Demo Sharing code between Server and Client
  • 84. (function(exports) { exports.createChartOptions = function(data) { var values = parseData(data); return { ... }; } })(typeof window !== 'undefined' ? (window.demo = {}) : exports); Attaches API to Attaches API to exports in node.js window.demo in browser to be returned by require
  • 86. HTTP Request Client Server Response
  • 87. Not so good for pushing Client Server Update. Erm.... Fail
  • 88. Web Sockets Proper Duplex Communication!
  • 89. But it’s only in very recent browsers And due to protocol concerns it’s now disabled even in recent browsers
  • 90. But you’ve probably noticed that applications have been doing this for years We’ve got some pretty sophisticated methods of emulating it, even in IE
  • 92. WebSockets Silverlight / Flash IE HTML Document ActiveX AJAX Long Polling AJAX multipart streaming Forever IFrame JSONP Polling
  • 93. All of those require a server holding open a connection for as long as possible.
  • 94. Thread-per-connection web servers struggle with this
  • 95. Node.js doesn’t even break a sweat
  • 96. var socket = io.listen(server); socket.on('connection', function(client){ // new client is here! client.on('message', function(){ … }) client.on('disconnect', function(){ … }) });
  • 98. var socket = io.listen(server), counter = 0; socket.on('connection', function(client) { No multithreading, so no counter = counter + 1; race condition! socket.broadcast(counter); client.on('disconnect', function() { counter = counter - 1; socket.broadcast(counter); }); });
  • 99. Node.js is young, but it’s growing up fast
  • 100. So how do you get started with node?
  • 101. If you’re on Mac or Linux then you’re good to go http://nodejs.org/
  • 102. If you’re on Windows you’re going to be a little disappointed
  • 103. Currently the best way to get start on Windows is hosting inside a Linux VM and ssh’ing it. http://www.lazycoder.com/weblog/2010/03/18/getting-started-with-node-js-on-windows/ Proper Windows support will be coming soon. http://nodejs.org/v0.4_announcement.html
  • 104. I think that node is super exciting and that you should start experimenting with it today
  • 105. But even if you don’t, other Web Frameworks are watching and it will almost certainly influence them
  • 106. http://nodejs.org/ http://groups.google.com/group/nodejs #nodejs on freenode.net http://howtonode.org/ https://github.com/alexyoung/nodepad
  • 108. // Thanks for listening! return;
  • 109. Image Attributions Old man exmouth market, Daniel2005 - http://www.flickr.com/photos/loshak/530449376/ needle, Robert Parviainen - http://www.flickr.com/photos/rtv/256102280/ Skeptical, Gabi in Austin - http://www.flickr.com/photos/gabrielleinaustin/2454197457/ Javascript!=Woo(), Aaron Cole - http://www.flickr.com/photos/awcole72/1936225899/ Day 22 - V8 Kompressor, Fred - http://www.flickr.com/photos/freeed/5379562284/ The Finger, G Clement - http://www.flickr.com/photos/illumiquest/2749137895/ A Messy Tangle of Wires, Adam - http://www.flickr.com/photos/mr-numb/4753899767/ 7-365 I am ready to pull my hair out..., Bram Cymet - http://www.flickr.com/photos/bcymet/3292063588/ Epic battle, Roger Mateo Poquet - http://www.flickr.com/photos/el_momento_i_sitio_apropiados/5166623452/ World's Tiniest, Angelina :) - http://www.flickr.com/photos/angelinawb/266143527/ A Helping Hand, Jerry Wong - http://www.flickr.com/photos/wongjunhao/4285302488/ [108/365] Ill-advised, Pascal - http://www.flickr.com/photos/pasukaru76/5268559005/ Gymnastics Artistic, Alan Chia - http://www.flickr.com/photos/seven13avenue/2758702332/ metal, Marc Brubaker - http://www.flickr.com/photos/hometownzero/136283072/ Quiet, or You'll see Father Christmas again, theirhistory - http://www.flickr.com/photos/ 22326055@N06/3444756625/ Day 099, kylesteed - http://www.flickr.com/photos/kylesteeddesign/4507065826/ Spectators in the grandstand at the Royal Adelaide Show, State Library of South Australia - http:// www.flickr.com/photos/state_library_south_australia/3925493310/

Editor's Notes