node.js

Andrew Clunis


[email protected]


https://github.com/orospakr


@orospakr


http://www.credil.org/

What is JavaScript?

Small, dynamic language designed at Netscape


C-esque syntax, dynamic like Ruby and Python, lends itself to functional style

Lexically scoped... closures!

          var func = function(arg) {
            var kept = arg + 6;
            return function() {
              return kept;
            };
          };

          var getter = func(7);
          getter() === 13;
        

Duck-typed/late bound

Everything is an object

... which is basically a hash

          var func = function() {
            console.log("Oooh, space! Spaaace!");
          };

          var hash = {"Eggs": "green"};
          var array = [1, 2, 3];

          (func instanceof Object) === true;
          (hash instanceof Object) === true;
          (array instanceof Object) === true;
        

Objects can delegate reads of nonexistent properties to a "prototype" object


Alas, no method_missing-like functionality, however; objects aren't message receivers

"this"


A facility of the special operator, "."

          var fluffy = {
            vocalization: "meow",
            giveMeat: function() {
              return this.vocalization;
            }
          };

          fluffy.giveMeat() === "meow";
          fluffy["giveMeat"]() === undefined;
        

Object Construction Pattern


          var Penguin = function(name) {
            this.giveFish = function() {
              // your filesystems are safe, this time.
              return name + " says, beep";
            };
          };
          
          var tux = new Penguin("tux");
          console.log(tux.giveFish());
        

Relatively simple but flexible set of core rules


Generally, you have to metaprogram up any higher-level concepts yourself

Not much of a standard library to speak of, though

Large variety of different ways of solving a problem (like object classing)

See Alex Russell's Google I/O 2011 talk on JavaScript

So, where does that leave us?

Python, Perl, Ruby, and such grew up with their own system programming runtime

... with JS, not so much.

Our story begins...

JS mostly lives in the Web Browser, which has a pretty limited scope

An Internet Explorer feature, an ActiveX control that lets JS execute HTTP requests, makes everyone suddenly start falling over themselves to write apps in these browser things

Various toolkits form, and include standard lib-like functionality, all incompatible


(By necessity!)

CommonJS emerges, wants to deal with this problem by defining standard library modules

JavaScript engine war was beginning!

So, this is where Node comes in

What is node.js?

Finally! A system-level programming environment for JavaScript, like Python, Perl, and Ruby


With a decent number of batteries included, especially for networking!

What's in it?

Google's V8

CommonJS-derived standard library

A convenient REPL, like irb

An integrated event queue/mainloop!


Implemented with libev

Integrated async-oriented networking libraries


Analagous to Twisted or EventMachine


In particular, includes a very nice HTTP library


Implemented with libeio

A community focus on high performance networking with non-blocking code, from the core runtime up

NPM: a package manager and repository similar to gems, cpan, or pypi

A burgeoning community that is writing a heck of a lot of code

So, let's begin!

Download tarball from


http://nodejs.org/


Or from git, if you like:


          git clone git://github.com/joyent/node.git
        

NB: It's still moving fast, so distro packages aren't useful yet

Install NPM:


Slightly worrying superfast install method:


          curl -s http://npmjs.org/install.sh | sudo sh
        

Or just go to http://npmjs.org/ and fetch the code.

Anatomy of a Node app:


          $ ls
          lib/  package.json  runspecs.js*  myapp.js*
        

package.json


          {
            "name": "myapp",
            "description": "Achieve nothing short of world domination",
            "version": "0.1.0",
            "homepage": "https://github.com/orospakr/myapp",
            "repository": "git://github.com/orospakr/myapp.git",
            "author": "Andrew Clunis <[email protected]>",
            "directories": {
              "lib": "lib"
            },
            "dependencies": {
              "warpdrive": "1.0.0rc1"
            },
            "engines": {
              "node": "*"
            },
            "scripts": {
              "test": "runspecs.js",
              "run": "myapp.js"
            },
          }
        

myapp.js


          #!/usr/bin/env node

          console.log("Welcome to your first node.js app!");
        

Runtime exits if control reaches end of file and there are no waiting external callbacks

Now let's make it do stuff

Simple TCP server


          #!/usr/bin/env node

          # mostly stolen from nodejs.org!

          var net = require('net');

          var server = net.createServer(function (socket) {
            socket.write("Echo server\r\n");
            
            socket.on("data", function(data) {
              console.log("Got '" + data + "'");
            });

            socket.on("error", function(e) {
              console.log("Yikes, hard error: " + e.message);
            });

            socket.on("close", function() {
              console.log("Goodbye!");
            });

            socket.pipe(socket);
          });

          server.listen(61234, "0.0.0.0");
        

Simple HTTP server


          #!/usr/bin/env node

          var http = require('http');
          var util = require('util');

          var HTTPHandler = function() {
            this.counter = 0;
          
            this.consumeRequest = function(req, response) {
              response.writeHead(200, {"Content-Type": "text/html"});
              // if you set the Content-Length field manually, chunked mode is disabled
              response.end("<html><body><h1>Req #" + ++this.counter + "</h1></body></head>");
              console.log("Request answered: " + util.inspect(req));
            };
          };

          var handler = new HTTPHandler();

          var server = http.createServer(handler.consumeRequest.bind(handler));

          server.listen(8081, "::");
        

Node libraries/frameworks: there are LOTS of tiny ones


A lot of duplication, particularly in the web middleware space: there are like 20 competing and different implementations for each analagous component of Rails


A few integrated stacks (like Rails) starting to gel together (Connect, Express)

I imagine winners will shake out before long...


Libraries are categorized at: https://github.com/joyent/node/wiki/modules


Seachable at: http://search.npmjs.org/

Still, great to see this happening on Node: you can innovate right down at the transport or application layer, without MRI or Apache/Passenger in your way

Testing has the same problem: 37 libs listed on Node wiki!


I use Jasmine at the moment, for what it's worth, since it's a little like RSpec


Haven't found (although it may exist!) a cukes equivalent yet

npm, though, is a little weird.


Doesn't really support global installations of modules very well.


It seems to be trying to clone Ruby's Bundler now; you install deps directly into your working tree

Anatomy of my own Node app, Stream Pump


(insert demo here!)


http://imladris.local:8086/streams/video

You can write bindings for native libs for Node, too


There aren't many yet, though


Basically, you have to bind against V8's extension API (which looks decent enough) and possibly libev if you have an event source


No UI bindings usable yet, though. I'd love to see Qt and GTK

So, node.js is:


Fast


JavaScript, all grown up


Promotes the event loop to a core language facility, something that's been sorely missing from other platforms


Awesome for networking


Community buy-in; lore is quickly developing. Fifty billion github projects can't be wrong?

Resources


NPM search


MDN Javascript


node.js docs


DailyJS blog


nodejitsu blog


Categorized list of modules on node.js wiki


jslint


nodejs' own source, particularly in the lib/ directory)

"I'm Cave Johnson. We're done here."


Questions, discussion?


Image stolen from Remy Scalza, http://www.insidevancouver.ca/2011/04/25/vancouver-craft-beer-week-is-almost-here-may-6-14/

Andrew Clunis <[email protected]>


http://www.credil.org/