SlideShare a Scribd company logo
1 of 109
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
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
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

Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 

What's hot (20)

Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Getting started with developing Nodejs
Getting started with developing NodejsGetting started with developing Nodejs
Getting started with developing Nodejs
 
Philly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSPhilly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJS
 
Nodejs in Production
Nodejs in ProductionNodejs in Production
Nodejs in Production
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Node.js
Node.jsNode.js
Node.js
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 

Viewers also liked

Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise Middleware
Behrad Zari
 
6 basic steps of software development process
6 basic steps of software development process6 basic steps of software development process
6 basic steps of software development process
Riant Soft
 

Viewers also liked (14)

JavaScript: From the ground up
JavaScript: From the ground upJavaScript: From the ground up
JavaScript: From the ground up
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise Middleware
 
Node.js architecture (EN)
Node.js architecture (EN)Node.js architecture (EN)
Node.js architecture (EN)
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.js
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
The 20 Worst Questions to Ask an Interviewer
The 20 Worst Questions to Ask an InterviewerThe 20 Worst Questions to Ask an Interviewer
The 20 Worst Questions to Ask an Interviewer
 
Best Practices for Getting Started with AWS
Best Practices for Getting Started with AWSBest Practices for Getting Started with AWS
Best Practices for Getting Started with AWS
 
Node.js and The Internet of Things
Node.js and The Internet of ThingsNode.js and The Internet of Things
Node.js and The Internet of Things
 
6 basic steps of software development process
6 basic steps of software development process6 basic steps of software development process
6 basic steps of software development process
 

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

Why Node.js
Why Node.jsWhy Node.js
Why Node.js
guileen
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
Mohammad Qureshi
 

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

Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Proposal
ProposalProposal
Proposal
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin Shanghai
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.js
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node azure
Node azureNode azure
Node azure
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Node.js on Azure
Node.js on AzureNode.js on Azure
Node.js on Azure
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011Ferrara Linux Day 2011
Ferrara Linux Day 2011
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami Sayar
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

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
  • 34.
  • 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
  • 91.
  • 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

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. http://www.flickr.com/photos/loshak/530449376/\n
  17. \n
  18. \n
  19. http://www.flickr.com/photos/rtv/256102280/\n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. http://www.flickr.com/photos/gabrielleinaustin/2454197457/\n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. http://www.flickr.com/photos/awcole72/1936225899/\n
  37. \n
  38. \n
  39. \n
  40. http://www.flickr.com/photos/freeed/5379562284/\n
  41. \n
  42. http://www.flickr.com/photos/illumiquest/2749137895/\n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. http://www.flickr.com/photos/mr-numb/4753899767/\n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. http://www.flickr.com/photos/bcymet/3292063588/\n
  91. \n
  92. http://www.flickr.com/photos/el_momento_i_sitio_apropiados/5166623452/\n
  93. http://www.flickr.com/photos/angelinawb/266143527/\n
  94. http://www.flickr.com/photos/wongjunhao/4285302488/\n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n
  100. \n
  101. \n
  102. \n
  103. \n
  104. \n
  105. \n
  106. \n
  107. \n
  108. \n
  109. \n
  110. \n
  111. \n
  112. \n
  113. http://www.flickr.com/photos/pasukaru76/5268559005/\n
  114. http://www.flickr.com/photos/seven13avenue/2758702332/\n
  115. \n
  116. \n
  117. \n
  118. \n
  119. \n
  120. http://www.flickr.com/photos/hometownzero/136283072/\n
  121. http://www.flickr.com/photos/22326055@N06/3444756625/\n
  122. \n
  123. http://www.flickr.com/photos/kylesteeddesign/4507065826/\n
  124. http://www.flickr.com/photos/state_library_south_australia/3925493310/\n
  125. \n
  126. \n
  127. \n
  128. \n