Intro to Node.js

buzzwords ahoy!

Developer Demo

Warning!

Any presentation, article, blog post, conversation, or tweet is bound to be overrun by just a few of the following buzzwords:

Event Loop
Real-Time
Non-Blocking
Event-Driven I/O
Closure
NoSQL
Socket.io
Express
 Asynchronous
Etc.

RSNA 2012 & Dxlive!

What went wrong?!?

  • ColdFusion backend is not ideal for handling large amounts concurrent requests
  • Ajax polling lead to database bottleneck & subsequent issues converting to responses to JSON.
  • WEBSOCKETS!!!

wHAT aRE WEBSOCKETS?

  • Bi-directional communication between the client and the server
  • Traditional web communication is one way
  • Websockets allow for two way communication where the server can send data to the client without a request.
  • Baby monitor vs. Walkie Talkie

Enter Socket.io


Works in every browser and mobile device using a dead-simple javascript API

Extremely backwards compatible.

post Show analysis


We needed to a solution that:

  • Can be quickly deployed to a server
  • Can handle tons of concurrent traffic
  • Provides dependable websockets

Hello World, Hello Node


So what is Node.js?

  • Single-threaded event-driven javascript application server
  • Open Source project based on Google's V8  javascript engine (Chrome)
  • Offers high I/O performance on less than optimal hardware

Just the facts, ma'am


  • First appeared in 2009, created by Ryan Dahl and sponsored by Joyent
  • Initially called "web.js" and written in C++ because it was supposed to be an alternative to Apache
  • Today it is the most "starred" or watched back-end repo on github, surpassing Ruby on Rails
  1. Bootstrap: 45511
  2. Node.js: 20446
  3. jQuery: 19305
  4. Ruby On Rails: 17584
  • Only on version 0.8.14

Who is using Node.js?


Along with hundreds of smaller projects and companies, major adopters include:

  • LinkedIn - Mobile site
  • Yahoo! - Mojito/Cocktails & Manhattan
  • Microsoft - Tight Azure integration
  • Amazon - Node SDK for AWS

What is Event-driven I/o?


Receptionist / Fast Food analogy

  • Multi-threaded environments require a substantial footprint to account for a pool of threads
  • Non-blocking works with only a single thread requiring fewer resources
  • This single thread can service thousands of requests with extremely low latency


Web servers like Apache that are used to serve PHP and other CGI scripts are thread based because they spawn a system thread for every incoming request. While this is fine for many applications, the thread based model does not scale well with many long-lived connections like you would need in order to serve real-time applications like Friendfeed or Google Wave.

That's Nice, but what is it good for?


JSON API

Building light-weight REST / JSON api's is something where node.js really shines. Its non-blocking I/O model combined with JavaScript make it a great choice for wrapping other data sources such as databases or web services and exposing them via a JSON interface.


Single Page Apps

If you are planning to write an AJAX heavy single page app (think gmail), node.js is a great fit as well. The ability to process many requests / seconds with low response times, as well as sharing things like validation code between the client and server make it a great choice for modern web applications that do lots of processing on the client.


Shelling out to the command line tools

Node's ability to spawn thousands of child processes and treating their outputs as a stream makes it an ideal choice for those seeking to leverage existing software.


Streaming Data

Traditional web stacks often treat http requests and responses as atomic events. However, the truth is that they are streams, and many cool node.js applications can be built to take advantage of this fact. One great example is parsing file uploads in real time, as well as building proxies between different data layers.

Simply Put, shifting around data


Whereas traditional multithreaded systems are suited to heavy CPU work, event-driven systems are meant for network applications that involve heavy I/O.

There's a "but" right?


Node is definitely not suited for all tasks. Those particularly ill suited include:

  • CPU heavy apps - Since Node has only a single thread, processing intensive tasks would essentially block I/O and defeat the purpose
  • Simple CRUD, Serving static HTML - Simple tasks that could be easily accomplished any number of ways.

Quick Benchmark

Top Javascript, bottom PHP:
var i, a, b, c, max;
max = 1000000000;
var d = Date.now();
for (i = 0; i < max; i++) {
    a = 1234 + 5678 + i;
    b = 1234 * 5678 + i;
    c = 1234 / 2 + i;
}
console.log(Date.now() - d);
$a = null;
$b = null;
$c = null;
$i = null;
$max = 1000000000;
$start = microtime(true);
for ($i = 0; $i < $max; $i++) {
    $a = 1234 + 5678 + $i;
    $b = 1234 * 5678 + $i;
    $c = 1234 / 2 + $i;
}
var_dump(microtime(true) - $start);

Results (MS)



Number of iterationsNode.jsPHP1002.000.1410’0003.0010.531’000’00015.001119.2410’000’000143.0010621.461’000’000’00011118.001036272.19

Javascript, the four letter word


You're forced into this non-blocking style. Anytime you want to talk to this remote back end or something, you have to give a callback. You can't say 'Database give me the result and then in the next line use the result.' You have to somehow have a callback, so you get indented a bit or you jump into a different function. ~ Ryan Dahl



JavaScript is extremely well suited to event-based programming because it has anonymous functions and closures which make defining inline callbacks a cinch, and JavaScript developers already know how to program in this way.

cALLBACK hELL


  • It's easy to write tangled code with callback function within callback function
  • This requires a new approach to organizing JS code. Move inline callback functions to local variables
  • Use plugins (modules) like "Async" to more easily organize your flow.



It's an event loop, the right way to make a high-performance server. It's JavaScript, a high-level language. It has great support for closures, which you need for the callbacks in an event-based system. And you've got Google behind V8 in the JavaScript arms race.

One script to rule them all



Use the same language to code your web app and back-end! Share templates between the client and the server! Cuts through tin cans!

Buzzword alert! mongodb


  • Schemaless JSON objects (key-value pairs) rather than rigid database tables and columns
  • Allows for embedded objects - include an array of email addresses rather than creating a separate table
  • Omit data that would typically be a null or the default data
  • Indexes are stored in memory, resulting in single-millisecond responses
  • Easily integrates with Node since they both deal with Javascript objects

Cool Modules


  • Socket.io - client/server websockets
  • Express - Easy util for creating servers
  • Async - Helps wrangle asynchronous code
  • Underscore - Util full of common object/array functions
  • Templating Libraries - Share templates between the client and server
  • Mustache, Handlebars, Jade, etc.

Cool Projects


  • CSS Pre-processors (LESS, SASS)
  • CoffeeScript
  • Meteor

Reveal.js


This presentation was built using rvl.io

Cool HTML5 presentation library


Check it out!

Source Links


  • http://nodeguide.com/convincing_the_boss.html
  • http://en.wikipedia.org/wiki/Nodejs
  • http://readwrite.com/2010/10/20/why-developers-should-pay-atte
  • http://code.danyork.com/2011/01/25/node-js-doctors-offices-and-fast-food-restaurants-understanding-event-driven-programming/
  • http://www.theregister.co.uk/2011/03/01/the_rise_and_rise_of_node_dot_js/
  • http://net.tutsplus.com/tutorials/javascript-ajax/this-time-youll-learn-node-js/
  • http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/?search_index=9

The end





Thanks!

nodejs and mongodb

By jamesbasco

nodejs and mongodb

  • 613