The JavaScript blog.


libraries web node modules express middleware

Node Roundup: io.js 1.6.4, npm Semver Calculator, mongots, Join-io

Posted on .

io.js 1.6.4, npm Semver Calculator

io.js 1.6.4 is out, as always check the io.js changelog for more details. According to the changelog, the notable changes in this version are fixes for openssl, timers, and some changes to make it build for Android devices.

Understanding semantic versions

In npm Weekly, #11, a really cool semantic versioning calculator is mentioned. If you've been writing versions like ~1.1.0 but don't completely understand what this means, the calculator will show you which versions the string refers to. The source is available here: GitHub: npm/semver.npmjs.com, and works using Browserify, Angular, and npm build scripts.

It uses npm-registry-cors-proxy.herokuapp.com to fetch package metadata rather than directly hitting npm. Presumably that's because npm's web API doesn't have JSONP or CORS (yet?).


If you're interested in MongoDB and TypeScript, then take a look at Prabhu Subramanian's mongots (GitHub: prabhu/mongots, License: MIT). The author says it supports everything MongoJS does and passes the same tests. It's not yet available on npm -- he's working on a stable version before releasing it.


Most of us concatenate scripts to reduce request counts, but what about piping them? Join-io (GitHub: coderaiser/join-io, License: MIT, npm: join-io) is a middleware component that allows you to specify script or link paths like this: /join:/lib/client.js:/lib/util.js:/lib/jquery.js. When this hits your Express server, join-io will stream each file to the browser.

The author has built this module on top of files-io, which is a more generalised API for piping collections of files. And, naturally, files-io is written with pipe-io!


JSON web node modules xml urls

Node Roundup: 0.8.24, 0.10.10, speakingurl, node-xmljson

Posted on .

You can send in your Node projects for review through our contact form.

Node 0.8.24 and 0.10.10

Node 0.8.24 and Node 0.10.10 have been released. The 0.8 (maintenance) release gets an updated npm, and some fixes for the url and http core modules.

Meanwhile, 0.10.10 has a new version of the internal uv library, and unshift('') now behaves like a noop.


Sascha Droste sent in speakingurl (GitHub: pid / speakingurl, License: BSD, npm: speakingurl), a module for generating clean URL slugs:

slug = getSlug('Apple & Pear!');  
// Output: apple-and-pear

slug = getSlug('Foo ♥ Bar');  
// Output: foo-love-bar

It has tests, localisation support, and works in browsers.


node-xmljson (GitHub: ExactTarget / node-xmljson, License: MIT, npm: xmljson) from Adam Alexander and Benjamin Dean of ExactTarget was just released, providing quick and simple bi-directional translation between XML and JSON formats.

// Load the module
var to_json = require('xmljson').to_json;

// An XML string
var xml = '' +  
    '<data>' +
        '<prop1>val1</prop1>' +
        '<prop2>val2</prop2>' +
        '<prop3>val3</prop3>' +

to_json(xml, function (error, data) {  
    // Module returns a JS object
    // -> { prop1: 'val1', prop2: 'val2', prop3: 'val3' }

    // Format as a JSON string
    // -> {"prop1":"val1","prop2":"val2","prop3":"val3"}
// Load the module
var to_xml = require('xmljson').to_xml;

// A JSON string
var json = '' +  
    '{' +
        '"prop1":"val1",' +
        '"prop2":"val2",' +
        '"prop3":"val3"' +

to_xml(json, function (error, xml) {  
    // Module returns an XML string
    // -> <data><prop1>val1</prop1><prop2>val2</prop2><prop3>val3</prop3></data>

ExactTarget has also released Fuel UX (GitHub: ExactTarget / fuelux, License: MIT) a lightweight web UI library that extends Twitter Bootstrap with additional JavaScript controls.


frameworks web node modules

Node Roundup: 0.8.19, 0.9.9, Peer Dependencies, hapi, node-treap

Posted on .

You can send in your Node projects for review through our contact form.

Node 0.8.19, 0.9.9, and Peer Dependencies

Node 0.8.19 was released last week and this version includes an update for npm that supports peer dependencies. I'm excited about this feature, and I'll be interested to see how it pans out over time. Basically, you can now specify dependencies for "plugins". Think jQuery plugins, or in a Node project Grunt plugins are a good example.

This will require plugin authors to update their package.json files with a peerDependencies property, but it should make managing things like Express middleware and Grunt easier in the future. I already find npm's dependency management relatively stress-free, and this seems like a step in the right direction.

Also, Node 0.9.9 was also released last week, which now features a streams2-powered tls module.



hapi (GitHub: walmartlabs / hapi, License: LICENSE, npm: hapi) from Walmart Labs is a framework for building RESTful API services. There are already a few solid RESTful API modules for Node (like restify), so hapi looks to be building on that concept rather than being an MVC web framework.

There's a basic example that provides an overview of the API:

var Hapi = require('hapi');

// Create a server with a host, port, and options
var server = new Hapi.Server('localhost', 8080);

// Define the route
var hello = {  
  handler: function(request) {
    request.reply({ greeting: 'hello world' });

// Add the route
  method : 'GET',
  path : '/hello',
  config : hello

// Start the server

Gone is the req, res pattern (which comes from Node's core modules, not Connect). The hapi API documentation is extremely detailed, and includes examples for the main features. The routing API does seem extremely flexible, but it's hard to judge it without seeing a large hapi application.

hapi, a Prologue by Eran Hammer is a detailed post that compares hapi to Express, which is useful if you're familiar with Express. Eran writes:

We also had some bad experience with Express' lack of true extensibility model. Express was a pleasure and easy to use 2 years ago with a limited set of middleware and very little interdependencies among them. But with a long list of chained middleware, we found hard to debug problems when we simply changed the order in which middleware modules were being loaded.

I've always thought the answer to this was to make smaller, interconnected services. Rather than a large Express application with complex middleware, shouldn't we be using multiple Express applications that communicate with each other? Technically Express could be a veneer on top of a more complex architecture.

Eran brings up other points as well, but it's difficult to say how well hapi or Express satisfy the goals of building large production web applications because people building things at that level don't release gory details about their solutions to architectural problems. I occasionally run into a friend who works on a Rails project with thousands of models. It doesn't work very well. But where are concrete details on real solutions to the problem of scaling business logic?


node-treap (GitHub: brenden / node-treap, License: MIT, npm: treap) by Brenden Kokoszka is a Treap implementation. A treap is a self-balanced binary search tree. Once a tree has been created, keys can be added with data objects:

var treap = require('treap');  
var t = treap.create();

// Insert some keys, augmented with data fields
t.insert(5, { foo: 12 });  
t.insert(2, { foo: 8 });  
t.insert(7, { foo: 1000 });  

Then elements can be fetched and removed:

var a = t.find(5);  
t.remove(a); // by reference to node  
t.remove(7); // by key  

Brenden has included tests, and each API method has documentation in the readme. He's included some notes on what treaps are, so you don't need to be fresh off the back of a computer science degree to figure out what the module does.


libraries events web competitions

Choco, JS1k

Posted on .


Choco by Anthony Heukmes is a framework for building web apps built from one HTML page. It's a bit like
Cappuccino and SproutCore, except a lot simpler. It's built from 3 other

  • Sammy - a client-side, jQuery-based Sinatra style routing framework
  • js-model - a way of handling data structures in the client
  • Jim - yet another JavaScript package manager

Most of Choco seems to be built by Ruby developers, and the author has a
Rails 3 example project. If you're building Rails projects you might
find something useful here.


Angus contacted us about JS1k which is a
conference to build a JavaScript demo in no more than 1024 bytes. This
doesn't include external libraries, but minification is allowed. The
conference is organised by Peter van der Zee, and it seems to have a
demo scene attitude about it.

There have been JavaScript related scene demos in the past (search
Scene.org), but it's good to see this type of thing in our area of interest and I hope JS1k gets some awesome entries.


tutorials frameworks events web lmaf

Let's Make a Framework: Events Part 3

Posted on .

Welcome to part 11 of Let's Make a Framework, the ongoing series about
building a JavaScript framework. This part continues looking at events.

If you haven't been following along, these articles are tagged with
lmaf. The project we're creating is called Turing and is available on GitHub:

Stopping Events

Once an event has been triggered it can propagate to other elements --
this is known as event bubbling. To understand this, try to think
about what happens if you have a container element and attach an event
to an element inside it. When the event is triggered, which elements
should receive the event?

We often don't want to propagate events at all. In addition, some
elements have default actions -- a good example is how a link tag's
default action makes the browser follow the link.

Prototype's Event.stop() method simplifies event
management by cancelling event propagation and default actions. We
generally want to do both at the same time.

jQuery models the W3C's Document Object Model Events
providing lots of methods on the event object itself:

  • event.preventDefault(): Stop the default action of the event from being triggered
  • event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
  • event.stopImmediatePropagation(): Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree

Our Stop API

I've modelled Turing's API on jQuery, with the addition of
stop(). The reason I like jQuery's approach is it creates a
cross-browser W3C API, which may future-proof the library.

Event objects are extended with:

  • event.stop() - Prevents the default handler and bubbling
  • event.preventDefault() - Prevents default handler
  • event.stopPropagation() - Stops the event propagating

Usage is best illustrated with a test from

should('stop', function() {
  var callback = function(event) { event.stop(); };
  turing.events.add(turing.dom.get('#link2')[0], 'click', callback);
  // ...

The Implementation

I've created a private function to extend and fix event objects. This
essentially patches IE and adds stop():

function stop(event) {

function fix(event, element) {
  if (!event) var event = window.event;

  event.stop = function() { stop(event); };

  if (typeof event.target === 'undefined')
    event.target = event.srcElement || element;

  if (!event.preventDefault)
    event.preventDefault = function() { event.returnValue = false; };

  if (!event.stopPropagation)
    event.stopPropagation = function() { event.cancelBubble = true; };

  return event;

Other Browser Fixes

Most frameworks patch other browser inconsistencies as well. Keyboard
and mouse handling in particular are problematic.

jQuery corrects the following:

  • Safari's handling of text nodes
  • Missing values for event.pageX/Y
  • Key events get event.which and event.metaKey is corrected
  • event.which is also added for mouse button index

Prototype also has similar corrections:

var _isButton;
if (Prototype.Browser.IE) {
  // IE doesn't map left/right/middle the same way.
  var buttonMap = { 0: 1, 1: 4, 2: 2 };
  _isButton = function(event, code) {
    return event.button === buttonMap[code];
} else if (Prototype.Browser.WebKit) {
  // In Safari we have to account for when the user holds down
  // the "meta" key.
  _isButton = function(event, code) {
    switch (code) {
      case 0: return event.which == 1 && !event.metaKey;
      case 1: return event.which == 1 && event.metaKey;
      default: return false;
} else {
  _isButton = function(event, code) {
    return event.which ? (event.which === code + 1) : (event.button === code);

You can also find similar patching in MooTools:

if (type.test(/key/)){
  var code = event.which || event.keyCode;
  var key = Event.Keys.keyOf(code);
  if (type == 'keydown'){
    var fKey = code - 111;
    if (fKey > 0 && fKey < 13) key = 'f' + fKey;
  key = key || String.fromCharCode(code).toLowerCase();
} else if (type.match(/(click|mouse|menu)/i)){
  doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
  var page = {
    x: event.pageX || event.clientX + doc.scrollLeft,
    y: event.pageY || event.clientY + doc.scrollTop
  var client = {
    x: (event.pageX) ? event.pageX - win.pageXOffset : event.clientX,
    y: (event.pageY) ? event.pageY - win.pageYOffset : event.clientY
  if (type.match(/DOMMouseScroll|mousewheel/)){
    var wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;


Over the last 3 weeks I've introduced event handling, explained how to
use the W3C and Microsoft APIs, and built an event handling framework.
The life cycle of event handling has been explained an implemented, from
creating events to stopping and removing them. I've also demonstrated
how differences between browsers are dealt with.

You can find the current version of Turing on GitHub: