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

KEY
Writing robust Node.js applications
PDF
Building servers with Node.js
PDF
Node.js and How JavaScript is Changing Server Programming
PPTX
introduction to node.js
KEY
A million connections and beyond - Node.js at scale
KEY
NodeJS
PPTX
Introduction Node.js
PDF
NodeJS
Writing robust Node.js applications
Building servers with Node.js
Node.js and How JavaScript is Changing Server Programming
introduction to node.js
A million connections and beyond - Node.js at scale
NodeJS
Introduction Node.js
NodeJS

What's hot (20)

PDF
Node.js - A Quick Tour
PDF
NodeJS for Beginner
PDF
Non-blocking I/O, Event loops and node.js
PDF
Server Side Event Driven Programming
PDF
Nodejs Explained with Examples
PDF
Node.js Explained
PDF
Original slides from Ryan Dahl's NodeJs intro talk
PPTX
Java script at backend nodejs
PPT
Node js presentation
PDF
Getting started with developing Nodejs
PDF
Philly Tech Week Introduction to NodeJS
PDF
Nodejs in Production
PPT
RESTful API In Node Js using Express
PPT
Nodejs Event Driven Concurrency for Web Applications
KEY
Building a real life application in node js
PPTX
Node.js Workshop - Sela SDP 2015
PDF
Node.js
PDF
Node Architecture and Getting Started with Express
PPTX
Introduction to Node.js
PPTX
Node.js Patterns for Discerning Developers
Node.js - A Quick Tour
NodeJS for Beginner
Non-blocking I/O, Event loops and node.js
Server Side Event Driven Programming
Nodejs Explained with Examples
Node.js Explained
Original slides from Ryan Dahl's NodeJs intro talk
Java script at backend nodejs
Node js presentation
Getting started with developing Nodejs
Philly Tech Week Introduction to NodeJS
Nodejs in Production
RESTful API In Node Js using Express
Nodejs Event Driven Concurrency for Web Applications
Building a real life application in node js
Node.js Workshop - Sela SDP 2015
Node.js
Node Architecture and Getting Started with Express
Introduction to Node.js
Node.js Patterns for Discerning Developers

Viewers also liked (13)

PDF
JavaScript: From the ground up
PDF
HTML5 for the Silverlight Guy
KEY
Node.js - Best practices
PDF
Node.js Enterprise Middleware
ODP
Node.js architecture (EN)
PPTX
NodeJS - Server Side JS
PDF
Architecting large Node.js applications
PPTX
Nodejs intro
PDF
Modern UI Development With Node.js
PDF
Anatomy of a Modern Node.js Application Architecture
PDF
The 20 Worst Questions to Ask an Interviewer
PDF
Node.js and The Internet of Things
PPTX
6 basic steps of software development process
JavaScript: From the ground up
HTML5 for the Silverlight Guy
Node.js - Best practices
Node.js Enterprise Middleware
Node.js architecture (EN)
NodeJS - Server Side JS
Architecting large Node.js applications
Nodejs intro
Modern UI Development With Node.js
Anatomy of a Modern Node.js Application Architecture
The 20 Worst Questions to Ask an Interviewer
Node.js and The Internet of Things
6 basic steps of software development process

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

PPTX
Node.js: The What, The How and The When
PPTX
Node.js: A Guided Tour
PPTX
Introduction to node.js GDD
KEY
Practical Use of MongoDB for Node.js
PPTX
PPTX
GeekCampSG - Nodejs , Websockets and Realtime Web
PDF
Nodejs a-practical-introduction-oredev
KEY
Introduction to NodeJS with LOLCats
PDF
Why Node.js
PDF
Why Nodejs Guilin Shanghai
PPTX
NodeJS
PDF
Introduction to Node.js
PDF
Node azure
PDF
Node.js introduction
PPTX
Node.js on Azure
PPT
Ferrara Linux Day 2011
PPTX
Intro to node and mongodb 1
PDF
Developing realtime apps with Drupal and NodeJS
PDF
soft-shake.ch - Hands on Node.js
PDF
Node.js 101 with Rami Sayar
Node.js: The What, The How and The When
Node.js: A Guided Tour
Introduction to node.js GDD
Practical Use of MongoDB for Node.js
GeekCampSG - Nodejs , Websockets and Realtime Web
Nodejs a-practical-introduction-oredev
Introduction to NodeJS with LOLCats
Why Node.js
Why Nodejs Guilin Shanghai
NodeJS
Introduction to Node.js
Node azure
Node.js introduction
Node.js on Azure
Ferrara Linux Day 2011
Intro to node and mongodb 1
Developing realtime apps with Drupal and NodeJS
soft-shake.ch - Hands on Node.js
Node.js 101 with Rami Sayar

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
A Presentation on Artificial Intelligence
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Modernizing your data center with Dell and AMD
MYSQL Presentation for SQL database connectivity
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Encapsulation theory and applications.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Review of recent advances in non-invasive hemoglobin estimation
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
cuic standard and advanced reporting.pdf
Network Security Unit 5.pdf for BCA BBA.
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Weekly Chronicles - August'25 Week I
A Presentation on Artificial Intelligence
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Chapter 3 Spatial Domain Image Processing.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Modernizing your data center with Dell and AMD

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 <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/
  • 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