Getting Started
With Node.js

Mike Cantelon
April 18, 2012

Hi, I'm Mike

What this talk will cover

What is Node.js and why would I want to use it?

Node.js aka Node is...

I had a rather sudden epiphany that JavaScript was actually the perfect language for what I wanted: single threaded, without preconceived notions of "server-side" I/O, without existing libraries.
Ryan Dahl

What makes Node different?

What is Node best at?

Who uses Node?

How is event-driven programming different?

Event-driven programming characteristics

Cooking as a metaphor

The event-loop conceptually

What does event-driven programming in JavaScript look like?

JavaScript event-driven programming relies heavily on callbacks

What a JavaScript callback looks like

someFunction(function(result) {
  // callback logic
  // does something
  // with result
});
  1. someFunction spends time doing something
  2. One it's done it executes the function provided as an argument to it, providing its results as an argument

JavaScript callback examples

setTimeout(function() {
  console.log('I execute after a delay!');
}, 1000);
function displayMessage() {
  console.log('I execute after a delay!');
}

setTimeout(displayMessage, 1000);

Event-driven application flow

setTimeout(function() {
  console.log('I execute next!');
}, 1000);

console.log('I execute first!');

So what does programming in Node look like?

Node's REPL

After installing Node, you can start the REPL by entering the following into a command-line prompt.

$ node
> ■

Then enter the following to make Node say its first words. CTRL-d to exit.

> console.log('Hello World!');
Hello World!
> ■

Running Node scripts

Node scripts require no boilerplate for displaying output.

Place the following code in a file named "hello_world.js".

console.log('Hello World!');

You can then run this script by entering the following into the command-line.

$ node hello_world.js

hello_web.js

In code below we require the "http" module.

We then create a server with it that will listen for HTTP requests on TCP/IP port 8888.

We use an anonymous function to specify what should be done with each request.

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello Web!\n');
}).listen(8888);

Building a TCP/IP chat server

Building a chat server provides a more substantial example.

chat_server.js (part 1 of 2)

var net = require('net')
  , clients = {};

var server = net.createServer(function(conn) {
  var id = conn.remotePort;
  conn.on('connect', function() {
    clients[id] = conn;
  });
  conn.on('data', function(data) {
    broadcast(id, data);
  });
  conn.on('end', function(data) {
    delete clients[id];
  });
});

server.listen(3000);

chat_server.js (part 2 of 2)

function broadcast(fromId, message) {
  // if a message, not a control key, has been sent, broadcast it
  if (message.toString().slice(-1) == "\n") {
    // send to each client except sender
    for(var id in clients) {
      if (fromId != id) {
        clients[id].write(fromId + '> ' + message);
      }
    }
  }
}

Installing Node is easy

What tools and frameworks are available to extend Node's capabilities?

The Node package manager is super useful

Installing and publishing modules with NPM

An example installation of a module:

$ npm install socket.io

When publishing a module, you must include a "package.json" file that specifies the module's name, version, etc.

An example of publishing a module:

$ npm publish

Publishing to NPM

The package.json file must include, at the least, a name and version number.

{
  "name": "my_module",
  "version": "0.0.1"
}

The NPM repository exists online and can be browsed at search.npmjs.org. Thousands of modules exist for everything from automated testing to support for experimental TCP/IP protocols.

Data storage

Modules exist in NPM that allow Node to interface with common data stores.

Flow control tools

In normally asynchronous development events can occur in unpredictable sequences.

Tools exist to force asynchronous code to execute either in parallel or sequentially.

These tools are often called "flow control" tools.

Flow control example

var flow = require('nimble');

flow.series([
  function (callback) {
    setTimeout(function() {
      console.log('I execute first.');
        callback();
      }, 1000);
  },
  function (callback) {
    setTimeout(function() {
      console.log('I execute next.');
      callback();
    }, 500);
  }
]);

Some useful Node modules

n CLI tool to switch between Node versions
express Minimalist web framework
socket.io Client/server websockets support
mongoose MongoDB-backed data store
nimble Flow control

Resources

nodejs.org Node downloads and documentation
search.npmjs.org Search NPM repository
webchat.freenode.net Web interface to #node.js IRC channel
Google Group Online support
howtonode.org Blog with tutorials
Node Up Podcast featuring discussion among Node developers

Questions?

Twitter: @mcantelon
Forum: tinyurl.com/nodeinaction
Slides: mikecantelon.com/talks/rjug