JavaScript, On the SERVER?

A Brief Intro to Node.js

Bryce Baril @brycebaril

What is Node.js?

“Node's goal is to provide an easy way to build scalable network programs”
nodejs.org

JavaScript, on the server!?!

  • Chrome's V8 Engine
  • C++ Extensions
  • libuv
  • Cross Platform!

Ugh... JavaScript?

Ugh... JavaScript?

Actually... Turns out JS is a pretty neat language, and Node.js gives you:

  • A single target (no IE6!)
  • ES5 (with some ES6 features)

What makes Node different?

  • Asynchronous/Non-blocking IO
  • Js Everywhere!

Asynchronous/Non-blocking IO

This is the single most difficult thing to get used to when using Node.

Async vs Sync Code


printf("one\n");
sleep(2);
printf("two\n");

              
vs.

console.log("one")
setTimeout(function () {
  console.log("two")
}, 2000)
              

How does Node do this?

Magic & libuv

How does Node do this?

All IO operations are handled outside of the vertical process flow.

Huh?

Vertical process flow?

Process Flow in Node

... is really the same as in the browser.


function greet(who) {
  console.log("Hello")
  console.log("how")
  function sayWho() {
    console.log(who + "?")
  }
  setTimeout(sayWho, 0)
  console.log("are")
}
greet("you")
              

Callbacks

When functions are created, they contain the state context of where they were created.


function greet(who) {
  console.log("Hello")
  console.log("how")
  function sayWho() {
    console.log(who + "?")
  }
  process.nextTick(sayWho)
  console.log("are")
}
greet("you")
              

Callback functions as continuations

All of this relies on functions being first class variable types. This is the standard way of passing continuations in Node.

Process Flow in Node

Synchronous code tends to be vertical (top->bottom), and asynchronous: horizontal (left->right).


function greet(who) {
  console.log("Hello")
  console.log("how")
  function sayWho() {
    process.nextTick(function () {
      console.log("?")
    })
    console.log(who)
  }
  process.nextTick(sayWho)
  console.log("are")
}
greet("you")
              

Asynchronous Concepts

  • callbacks (Timers & IO libraries)
  • EventEmitters
  • Streams
  • Promises (not in core)
  • Generators (ES6, coming soon)

JavaScript Everywhere!

You can write a JavaScript file that will run in either Node or the browser. However, browsers don't have the same features as Node.

Browserify

Browserify will convert almost *any* Node.js code to be browser compatible. It will polyfill as much as possible with browser analogs.

Browserify

Single Language Stack!

Node.js finally fulfills the promise of a single-language stack. (Looking at you, GWT...)

So why is Node so compelling?

JavaScript

Odds are good you already know and use JavaScript.

Asynchronous IO = Fast

For typical web-based applications, the IO operations are the bottlenecks.

With Node, there is no need for external systems to scale or parallelize IO bandwidth. (e.g. Apache mod_php mod_perl, etc.)

Just the right stuff in Node core.

All the most common stuff you'll need is built delivered right with the language:

  • Socket Communication
  • Filesystem
  • HTTP(S) server/client
  • JSON
  • Crypto
  • Buffers (for binary data)
  • Streams
  • EventEmitters

Standing on the shoulders of giants

Every new technology that comes out incorporates lessons from the successes and failures of its predecessors.

Best-in-class package manager.

From modulecounts.com

It is young

While in some ways this can be a disadvantage it does bring a few great benefits:

  • Use cases are targeted around the most modern paradigm.
  • A favorable passion to burn-out ratio. Lots of talented, excited developers in the community.

What is Node not good at?

  • Heavy CPU Tasks
  • Memory intensive tasks

Cooperative Multitasking

If the CPU is pegged, the event loop gets blocked.

Synchronous == Blocking

If you intentionally block the event loop, the event loop gets blocked.

Don't Block the Event Loop

V8 Memory Limitations

By Default the V8 JavaScript heap is about 2gb. This can be configured higher, but beware of GC costs.

How To Node

After that short intro, let's delve into some key concepts.

JavaScript (again...)

When I started working with Node I thought I knew JavaScript. Node will help you actually learn it.

libuv & JavaScript

Node is single-process

libuv & JavaScript

libuv is the back-end that provides the asynchronous to Node.

It uses back-end threads to run the event loop and handle continuations.

libuv & JavaScript

Worth mentioning again: Any JavaScript code in a single context is Synchronous.

libuv event loop

Internal reference count

Node keeps track of "pending" things. Your application won't exit until this number is zero. (Open sockets, timers...)

Memory Model


process.memoryUsage()
{ rss: 10371072,
  heapTotal: 7195904,
  heapUsed: 2442752 }
              
  • rss -- Everything (Buffers, C++/libuv + Heap)
  • heapTotal -- Allocated JavaScript object memory
  • heapUsed -- Heap space currently in use

Core Modules

The node docs are pretty great.

NPM

npm is Node's package manager. It is packaged directly with Node. It is awesome.

Exception Handling

The Async nature of Node.js makes Exception Handling an even harder topic than usual.

Exception Handling


someAsyncThing(foo, function (err, reply) {
  if (err) {
    console.log(err)
    return // IMPORTANT
  }
  return doStuff(reply)
})

takesCallback(foo, callback) {
  someAsyncThing(foo, function (err, reply) {
    if (err) return callback(err)
    return doStuff(reply)
  })
}
              

Advanced Exception Handling

When you're ready, you can check out process.uncaughtException and Domains.

Common Beginner Mistakes

  • Never invoking callbacks
  • Invoking callbacks multiple times
  • Throwing errors in async code
  • Not checking for errors
  • Just because you're using a callback does not make it Async
  • Mixing Async & Sync in the same API

WARNING LIVE DEMOS

WARNING LIVE DEMOS

To play along:

  1. make sure you have node & git installed
  2. git clone git@github.com:brycebaril/nodeintro.git
  3. cd nodeintro
  4. npm install

Where to go from here?

Let me know how it goes! @brycebaril