Socket.IO Debugging

08 Nov 2013 | By Alex Young | Comments | Tags npm node websockets

How do you debug WebSockets, other than inserting console.log all over the place? One technique is to look at the Frames tab, under Network, in WebKit Inspector.

The Frames tab in WebKit Inspector.

The term “frames” refers to the data that is sent in a WebSocket connection. Unfortunately, I’ve been doing some work with WebSockets inside a desktop application, so I can’t easily see WebKit inspector.

Diego Costantino sent in ThreePin (GitHub: dieguitoweb / ThreePin, License: MIT, npm: threepin, bower: dieguitoweb/ThreePin), a tool for developing and testing software that uses Socket.IO and Node:

ThreePinJS is a stress-free test environment for Socket.IO allows you to test your WebSocket server code before you write the client code.

It uses a configuration file called threepin.json that sets up a server, and a list of events to listen for and send. The readme has a full example.

Once the server is configured, you can use any local HTTP server you want to serve a simple HTML file that connects and runs through the event list. It means you can focus on the server-side logic before worrying about the client-side code.

I’m still looking for options to help test and debug Socket.IO projects, but I thought ThreePin was an interesting stab at the problem.

Should You Share Client-Side Projects on npm?

07 Nov 2013 | By Alex Young | Comments | Tags npm node browser

Should you share your client-side projects with npm? Or, as a client-side developer, should you be using npm and a package.json to organise your project’s dependencies?

People are already using npm for distributing client-side code for many types of projects:

  1. Generic JavaScript that is sometimes used on the server but often used in the client (Underscore.js, Backbone.js)
  2. Client-side libraries that are so popular they’ve ended up npm out of convenience (jQuery)
  3. Client-side plugins for Backbone.js, AngularJS, jQuery (check out peer dependencies if you want to do this in a clean way)

If you decide to share a module using npm, you don’t necessarily need to wrap it in Node’s module system, but I would argue that you should, and you should also supply tests that can be run with Node. In an ideal world all modules on npm would include tests, and I believe this extends to client-side projects.

A recent client-side workflow pattern that has emerged, perhaps most notably from Substack, is to use Node in the browser, using something like Browserify. This means you can use require, so you can organise client-side code with Node’s module system. What I think is amazing about this is you can use Node’s core modules, so if you’re used to using EventEmitter and streams then you can bring these patterns over to the browser.

However, as Substack notes in this post on reddit, require is incompatible with RequireJS. It might seem surprising if you’re a Node developer, but the naming of require and RequireJS causes serious confusion to client-side developers who are just discovering module systems.

The Question

So, the question is, should you use npm for sharing client-side projects, or something like Bower? Do you prefer using Browserify or similar pre-processors, or is using AMD good enough?

Node Roundup: Mongovi, hoquet

06 Nov 2013 | By Alex Young | Comments | Tags node modules templating clojure mongodb


I’ve been working on a project that uses MongoDB, and one of the problems I have is with Mongo’s REPL. For one thing, I keep hitting CTRL-C because I expect it to cancel the current line rather than exit the whole REPL, but a bigger problem for me is they’ve switched to linenoise. I’m used to Vim’s shortcuts, which readline can use. When dealing with programs with non-readline REPLs, I often invoke rlwrap (or write an alias to use rlwrap), but when it comes to Mongo a better solution might be Tim Kuijsten’s Mongovi.

Mongovi (GitHub: timkuijsten / node-mongovi, License: MIT, npm: mongovi) is a REPL for MongoDB with Vi keys. It uses readline-vim and node-mongodb-native, so it isn’t a wrapper around the command-line mongo tool but instead a reimplementation in Node.

Several high-level commands work: show dbs lists databases, use db switches to a different database, and the usual commands like c.collectionName.find, update, and insert work. The author has included Mocha tests, and documentation can be found in the readme.


I had a brief love affair with Clojure. It was a romance that lasted a few months, but work got in the way and we had to break up. However, thanks to Tom Brennan I can relive those days with hoquet (GitHub: tjb1982 / hoquet, License: MIT, npm: hoquet). This is a templating library based on Clojure’s Hiccup. It uses a structured language based on arrays for generating HTML:

var http = require('http'),
    h = require('hoquet');

function layout(c) {
  var out =
      ['title', c.title],
     ['body', {'ng-app':'MyApp'}, c.body]];

  return out;

var index = layout({
  title: 'My Page',
  body: ['div', {'ng-view':''},
         ['h1', 'Hello world']],
  head: [['meta', {'name':'description',

http.createServer(function(q,s) {
  s.writeHead(200, {'Content-Type': 'text/html'});
  s.end( h.doc('html5', index) );

Tom also notes that hoquet can be used in browsers, because the underlying implementation is plain ol’ JavaScript:

You create your own functions/literals to pass in whatever you want and call render, which stringifies it. You can also render inner portions at any time and insert them as Strings so you don’t have to worry about when render is called.

stickUp, Backbone.js Guide

05 Nov 2013 | By Alex Young | Comments | Tags books backbonejs jquery plugins ui


stickUp (GitHub: LiranCohen / stickUp, License: LGPL) by Liran Cohen is a plugin for handling navigation bars that stick at the top of the page when it’s scrolled:

stickUp is a simple plugin that “sticks” an element to the top of the browser window while scrolling past it, always keeping it in view. This plugin works on multi-page sites, but has additional features for one-pager layouts.

It can detect the vertical position of the element and automatically fix it to the right position:

  marginTop: 'auto'

Backbone.js Guide

Julio Cesar Ody’s Backbone.js Guide is a freely available and somewhat opinionated book about Backbone that he’s currently in the process of writing. There are five chapters so far, and two more should be coming soon. The source is on GitHub at juliocesar / backbone-book.

The rule of thumb is get the hell away from the DOM. You won’t read from it ever (e.g.: getting an element’s class name, or the length of a list counts as that), because your data layer knows what has what value and in what state anything is at any given time. You’ll write to the DOM only by rendering views. If you like this approach, it’s totally ok to use just regular JS or jQuery.

Grasp, Optimizing AngularJS

04 Nov 2013 | By Alex Young | Comments | Tags angularjs search productivity optimisation


George Zahariev sent in his latest project, Grasp (GitHub: gkz / grasp, License: MIT, npm: grasp). Grasp allows you to search and replace JavaScript code based on its abstract syntax tree.

Unlike programs such as “grep” or “sed”, it searches the structure behind your code, rather than simply the text you’ve written - this allows for much more powerful searches.

It uses a language inspired by CSS selectors for creating intuitive search expressions. For example, given this code:

var obj = {
  toEven: function(x) {
    if (isEven(x)) {
      return x;
    } else {
      return x + 1;

assert.equal(false, isEven(7));

Searching for obj.props func! #isEven would match the call to isEven inside the property toEven on the object obj. References outside, like the assertion at the bottom, will not be matched.

My preferred solution for searching code is The Silver Searcher, but I like the idea of combining an AST with search and replace – it seems like a potentially fertile ground for experimentation.

Optimizing AngularJS: 1200ms to 35ms

In Optimizing AngularJS: 1200ms to 35ms, optimisations for AngularJS are discussed. It’s actually a lot deeper than you might expect: it goes from caching DOM elements to bypassing watchers for hidden elements, and deferring element creation:

A straightforward AngularJS implementation of the log view took 1.2 seconds to advance to the next page, but with some careful optimizations we were able to reduce that to 35 milliseconds. These optimizations proved to be useful in other parts of the application, and fit in well with the AngularJS philosophy, though we had to break few rules to implement them. In this article, we’ll discuss the techniques we used.

The conventional wisdom for AngularJS says that you should keep the number of data-bound elements below 200. With an element per word, we were far above that level.

Using Chrome’s JavaScript profiler, we quickly identified two sources of lag. First, each update spent a lot of time creating and destroying DOM elements. Second, each word had its own change watcher, which AngularJS would invoke on every mouse click. This was causing the lag on unrelated actions like the navigation dropdown.

The post got a huge amount of interest, so the authors are working on open sourcing their AngularJS directives.

WDS2013, flyLabel.js

01 Nov 2013 | By Alex Young | Comments | Tags animation jquery webgl

Web Directions South 2013 Opening Titles


Hugh Kennedy sent in the Web Directions South 2013 Opening Titles (GitHub: smallmultiples /, MIT, MPL and Creative Commons). This is an extremely impressive WebGL animation complete with a cool soundtrack. It’s partly demoscene inspired, but also reminds me of Darwinia.

The code’s open source, mostly MIT with a couple of files under the Mozilla Public License and assets under Creative Commons.

Done in collaboration with Small Multiples’ ( Jack Zhao and François Robichet, it’s pushing some of the newer browser APIs quite a bit - WebGL, IndexedDB, Web Audio, Web Workers, etc.


flyLabel.js (GitHub: athaeryn / flyLabel.js, License: MIT) by Mike Anderson is a jQuery plugin that adds fancy animations to form labels. It uses CSS animations, and has a simple JavaScript API. Mike’s example uses Modernizr:

if (Modernizr.input.placeholder) {

New Features in npm: Part 2

31 Oct 2013 | By Robert Kowalski | Comments | Tags node npm
Node has one of the best package managers around: npm. Every month a lot of features are added to npm. Here are some new features as of 1.3.12.

Default Homepage URLs

Many projects use the same URL for their homepage and GitHub page. As of 1.3.12, you do not have to define the homepage property in your package.json – if you have a GitHub URL as the repository field the homepage will default to the GitHub page.

For example, this:

"repository": {
  "type": "git",
  "url": ""

will result in the homepage field being set to

Outdated Upate

npm outdated shows the latest compatible version of each module according to your package.json definition. The updated version of this command, which you can use with npm 1.3.12, will also show the very latest version, even if it is not compatible with your package.json definitions.

These will show as latest:

underscore node_modules/underscore current=1.3.1 wanted=1.3.3 latest=1.5.1


With a new version of npm (and also Node) a ton of features and bug fixes arrive, so you should always be up to date. Fortunately, you just have to to get the latest Node version each time, as the latest npm versions are bundled into each node release.

You can find me on Twitter @robinson_k and GitHub at robertkowalski.

Node Roundup: 0.11.8, tabby, Nixt

30 Oct 2013 | By Alex Young | Comments | Tags node modules substack node-web testing command-line

Node 0.11.8

The core developers are cranking the handle again and firing out releases. Today Node 0.11.8 was released, which upgrades uv and V8. There’s a new buf.toArrayBuffer API, debugger improvements, and core module fixes.

I saw 0.11.8 announced on Twitter, and the author hinted at more frequent unstable releases.


If it’s not TJ Holowaychuk it’s Substack. I don’t believe it’s possible to write a weekly column about Node without mentioning one of them at least once. Substack just released a client-side project called tabby (GitHub: substack / tabby, License: MIT, npm: tabby), a module for creating web applications with tabs using progressive enhancement techniques.

Why is this notable? Well, Substack has been ranting about Node’s module system and client-side code. He wants you to stop mucking about and require(). Tabby blends the browser and Node by using WebSockets, and makes judicious use of Node’s core modules and streams.

For something focused on client-side code, it uses an interesting cocktail of modules. The inherits module provides browser-friendly inheritance, whilst still being compatible with util.inherits. And trumpet is used for parsing and transforming streaming HTML using CSS selectors. In the documentation, Substack recommends using hyperspace for rendering.

Looking through the examples, it definitely feels like idiomatic Node. I can imagine this style scaling up well to a larger web application.



Test code readability can bring huge gains when maintaining projects. Tests should communicate intent, and the longer they don’t need heavy modification the happier everyone will be. I generally find myself writing DSL-like methods for tests that reduce code duplication, particularly in the set-up phase.

With that in mind, it’s interesting to see Nixt (GitHub: vesln / nixt, License: MIT, npm: nixt) by Veselin Todorov. This is a module for testing command-line applications. It’s based around expectations, which reminds me of good old Expect.

Nixt works well asynchronously because it supports middleware for ordering execution. It can be used with a test harness like Mocha, and allows you to define custom expectations, which is where your application-specific DSL-like test helpers come in.

Although I’m probably guilty of using Node for command-line scripts that could be done with a shell script (I write my share of shell script too though), Nixt seems like a great way to test them, particularly as people often forget to test such scripts.

Script Roundup: jWebAudio, Scrolling Component

29 Oct 2013 | By Alex Young | Comments | Tags jquery plugins browser audio scrolling
Note: You can send your scripts and articles in for review through our contact form.


jWebAudio (GitHub: 01org / jWebAudio, License: Apache 2.0) by Wenli Zhang and published by Intel’s Open Source Technology Center is an audio library focused on games:

Web Audio seeks to process and synthesize audio in web applications. jWebAudio keeps the technical details of Web Audio under the hood and makes it easier to control your audio.

It has a jQuery API and also a framework-agnostic JavaScript API. Playing a set of sounds looks like this:

$('.sound').each(function() {
  var $this = $(this);
  var url = $'sound');
  $(this).jWebAudio('addSoundSource', {
    url: url,
    preLoad: true,
    callback: function() {

jWebAudio also supports synthesis and effects:

Sound effects include telephonize and cathedral currently. And you may create new sound effects using the combination of LOWPASS, HIGHPASS, BANDPASS, LOWSHELF, HIGHSHELF, PEAKING, NOTCH, ALLPASS.

There’s a demo here: jWebAudio demo.

Wenli also writes about JavaScript. Here’s a post about the gruesome details of Number, parseFloat, and parseInt: Converting To Numbers In JavaScript.

Scrolling.js Component

Guille Paz sent in Scrolling.js Component (GitHub: pazguille / scrolling, License: MIT, component: pazguille/scrolling). It allows you to decouple scrolling from callbacks to avoid generating too many scroll events (the old debouncing issue):

var scrolling = require('scrolling');

scrolling(document.querySelector('#box'), callback);

The project is distributed as a component, and has a demo on the homepage.

HiDPI Canvas Polyfill, formatter.js

28 Oct 2013 | By Alex Young | Comments | Tags browser canvas polyfills

HiDPI Canvas Polyfill

Don’t you just hate it when a cool canvas animation suddenly goes blurry? HiDPI Canvas Polyfill by Jonathan Johnson scales the canvas so the PPI is right, avoiding unsightly blurring. Jonathan notes that Safari is currently the only browser that does this properly.

I don’t know if the author was inspired by How do I fix blurry text in my HTML5 canvas? on Stack Overflow, but the solution looks similar to MyNameIsKo’s answer.

Jonathan has gone further by including tests, and he’s included a Grunt build script as well.

Jonathan also sent in BubbleChart (GitHub: jondavidjohn / bubblechart, License: Apache 2.0, npm: bubblechart) which is an interactive visualisation for two dimensional data.


formatter.js (GitHub: firstopinion / formatter.js, License: MIT) by Jarid Margolin helps you to define custom form fields. The examples given are a credit card form and a telephone number entry. The script can insert text as the user types, so the credit card form inserts hypens, and the telephone number uses the US-style format with brackets and a single hyphen.

The API looks like this, but there’s a jQuery wrapper as well:

new Formatter(document.getElementById('credit-input'), {
  pattern: '9999-9999-9999-9999'

The project includes tests that can be run with npm, and there are examples here: formatter.js demos.

How Apple Could Fix iWork: JavaScript

25 Oct 2013 | By Alex Young | Comments | Tags apple essays embedding

Apple and JavaScript

Apple recently updated iWork and removed a whole bunch of features. The company where I work makes a popular Mac application, and the removal of AppleScript from iWork caused a backlash from customers who rely on this feature for integration between our program, and Pages and Numbers.

AppleScript wasn’t ideal, but it did the job. Now we’re left in the dark, and as Apple are being typically opaque about adding it back we’re not sure what to do. The way it worked before was with scripting bridge, and although SBApplication is still around, Pages and Numbers no longer have it.

Scripting Bridge

Scripting Bridge provides an Objective-C API for sending and receiving Apple events, so you can take control of applications in Objective-C. It can be used to bridge another scripting language. JSTalk is one such example:

JSTalk is a scripting language for Mac OS X built on top of JavaScript, with a bridge to Apple’s Cocoa libraries. You can use it to communicate with other applications just like AppleScript does

JSTalk is built on top of Apple’s JavaScriptCore, the same JavaScript engine that powers Safari. So when you write in JSTalk, you are really writing JavaScript.

There’s also JavaScript Bindings for C and Objective-C. This uses SpiderMonkey to interpret your JavaScript, and bindings for Objective-C. You can even subclass native objects with JavaScript.

From my perspective as a JavaScript and Node specialist who does some Objective-C on the side, these projects have their appeal. It would be better if JavaScript was the default, though.


Apple makes JavaScriptCore available to Mac and iOS developers with an Objective-C API. This quote is from Owen Mathews at Big Nerd Ranch:

JavaScriptCore gives developers deep access to the full JavaScript runtime from Objective-C. You can syntax-check and execute scripts, access variables, receive callbacks, and share Objective-C objects, making possible a wide range of interactions. (One caveat: on iOS, there is currently no way to access the UIWebView’s runtime, so unfortunately it’s not possible to tie into web apps at this level.)

Post Scripting Bridge

Now Apple have removed Scripting Bridge from iWork, it made me want to rethink application scripting. What would it be like to run JavaScript in an application? It would be much like browser DOM scripting, except the document would be a Keynote or Pages file.

When we wrote AppleScript in the past we wanted to modify a document without having to understand how to parse its format. There’s an element of driving the application, but also handling an abstracted version of the document rather than the underlying proprietary format. It’s probably easier to say “make words that match this regular expression bold” than it is to write a parser for Pages documents.

I recently wrote about the importance of embedded JavaScript, and I think Apple could gain a lot by adding JavaScript APIs to their applications. It would be more agnostic than AppleScript or VBScript, which can be used with Microsoft Office. If I could somehow insert myself into the nexus of all Apple development and advocate JavaScript I would, but I don’t have that kind of power, so perhaps someone reading this will!

Introduction to ChocolateChip-UI

24 Oct 2013 | By Robert Biggs | Comments | Tags browser tutorials ui
This post is a tutorial about ChoculateChip-UI from Sourcebits Inc.

We’re going to look at how to throw together a simple navigable app with the ChocolateChip-UI framework. This will require familiarity with HTML. You don’t need to be good with CSS or even know how to write JavaScript. ChocolateChip-UI provides functionality out of the box to provide functionality for Web apps.

ChocolateChip-UI uses a particular combination of simple tags to define the structures that make up a mobile app. These are: nav, article, section, ul, li, div, aside, span, p and h1 through h5.

To follow along, download the framework and grab the folder “chui”. This contains the files that comprise ChocolateChip-UI. We’re going to use three files: chocolatechip-3.0.4.min.js, chui-3.0.4.min.js and chui-ios-3.0.4.min.js.

To make a Web page behave like an app in the browser, we need to first provide some meta tags. Here is the basic skeleton with appropriate meta tags and links to the ChocolateChip-UI resources:

<!doctype html>
<html lang="en">
  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="msapplication-tap-highlight" content="no">
  <meta charset="UTF-8">
  <link rel="stylesheet" href="chui/chui.ios-3.0.4.min.css">
  <script src="chui/chocolatechip-3.0.4.min.js"></script>
  <script src="chui/chui-3.0.4.min.js"></script>

The app will reside inside of the body tag. When you look at the screen of a mobile devices, you notice that most apps use two main parts to present everything on the screen: a nav bar and everything below that. ChocolateChip-UI uses a combination of a nav tag and an article tag to create each screen of the app. Since we’re going to make a navigable app, we’ll need to put together a number of screen, each consisting of a nav and article.

The first screen will be the current view, and all others with be upcoming. ChocolateChip-UI designates this navigation status using two classes: “current” and “next”.

Every nav will have at least an h1, which is the title that appears in the navigation bar. Let’s start building this. We’ll need to create a navigation bar and an article. ChocolateChip-UI forces the article to fill the screen. Every article should have one child – a section tag. All the content will go in the section. It will automatically provide inertia scrolling when the user swipes.

Every article tag must have a unique id. This is used during navigation so that ChocolateChip-UI knows where to go and where to return to. If you find at some time that your app is not going to where you want or not returning properly, check that your articles have the ids they need and that you have all uses of them spelled identically.

Here is the basic app shell.

<!doctype html>
<html lang="en">
  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="msapplication-tap-highlight" content="no">
  <meta charset="UTF-8">
  <link rel="stylesheet" href="chui/chui.ios-3.0.4.min.css">
  <script src="chui/chocolatechip-3.0.4.min.js"></script>
  <script src="chui/chui-3.0.4.min.js"></script>
  <nav class="current">
  <article class="current" id="fruits">

You’ll notice that when it loads in the browser, the title appears in a nav bar, but there is nothing below that. ChocolateChip-UI uses unordered lists with the class list to display tabular data. We can give the list a title by putting an h2 right before the list. To display data in each list item, we use an h3 as the title and an h4 as the subtitle and a paragraph tag as the item detail. If we put the class nav on a list item, we get the right facing caret that iOS uses to indicate a navigable item.

Source code, part 3

To make this list able to navigate to other articles, we need to indicate where each list item should go. We do this using an HTML5 data attribute: data-goto. We give it the id of the article to which it will go. This will result in automatic navigation when the article that it points to exists.

This example includes the data- attributes:

Source code, part 4

Here’s what the navigation list should look like so far:

Navigation list

Now we need to add an article with the id for each fruit: apples, oranges, bananas, mangos and avocados. We’ll also want to provide a nav with an h1 with the title of each fruit. Because these navs and articles are not current in navigation, we need to explicitly give them the class next. This will put them out of view until the navigation occurs.

Source code, part 5

This creates a navigable app, except for one problem. After the user selects a fruit and the app navigates to that screen, there is no way to get back. We can provide a way back by adding a back button in each nav bar right before the title.

Source code, part 6

Detail page of Navigation list

To complete our simple app we just need to add a list to each of the fruit articles. We can use the same pattern we used on the main article.

Source code, part 7

To support Android or Windows Phone 8, you just need to switch out the reference in the CSS link: chui/chui.ios-3.0.4.min.css. Change ios for android or win.

Of course, this is just the most basic setup for an app. In real life you would want to get data dynamically through Ajax requests and output it to your app using templates. Sounds like another article.

Node Roundup: HTTP DoS Fixed, Flocon, Trans

23 Oct 2013 | By Alex Young | Comments | Tags node modules uuid json

Node DoS Fixes

This week two maintenance releases of Node were rolled out to fix a DoS vulnerability in the HTTP module.


I seem to find myself generating a lot of unique IDs lately. Flocon (GitHub: Yosee / flocon, License: MIT, npm: flocon) from Yosee is a 64-bit unique ID generator, written in C++. It’s currently considered experimental by the authors but comes with unit tests.

Flocon returns IDs synchronously as strings with flocon.snow(), and the algorithm used is based on Twitter’s Snowflake service.

There are also some benchmarks of the flocon module so you can compare it to other projects.


Gabriel Adomnicai sent in “trans” (GitHub: gabesoft / trans, License: MIT, npm: trans), a module for transforming objects. Given some JSON, trans can group and modify objects by using a chainable API:

var trans = require('trans');
var data = [
  { a: { b: 'fbc' }, c: 1 }
, { a: { b: 'foo' }, c: 3 }
, { a: { b: 'fde' }, c: 2 }
, { a: { b: 'def' }, c: 3 }
, { a: { b: 'ghk' }, c: 4 }

  .group('a.b', 'c', ['charAt', 0], 'toUpperCase')

[ { key: 'D', value: [ 3 ] },
  { key: 'F', value: [ 1, 2, 3 ] },
  { key: 'G', value: [ 4 ] } ]

Each of the methods is documented in the readme, and Gabriel has included tests as well.

Script Roundup: Handpicked jQuery, Firepoker, Enyo 2.3

22 Oct 2013 | By Alex Young | Comments | Tags jquery plugins angular apps cdn
Note: You can send your scripts and articles in for review through our contact form.

Handpicked jQuery Plugins

The Handpicked jQuery Plugins site by David Higgins has been updated to the third version. He’s also released, which has links to resources served from MaxCDN. All of the plugins have MaxCDN links as well.

The site gets increasingly lean and mean over time. Outdated plugins get removed, and new ones take their place. The colors change, the CDN gets better, and more new fans download the repo each day to experiment with the plugins.



Firepoker (GitHub: Wizehive / Firepoker, License: MIT) by Everton Yoshitani is a “Scrum poker” game used for estimating user stories.

In planning poker, members of the group make estimates by playing numbered cards face-down to the table, instead of speaking them aloud. The cards are revealed, and the estimates are then discussed. By hiding the figures in this way, the group can avoid the cognitive bias of anchoring, where the first number spoken aloud sets a precedent for subsequent estimates.

It’s built with AngularJS and Firebase. It comes with a Grunt build script, so you can run a local development server to check it out easily.

The Firebase integration seems lightweight and easy to follow – if you look at main.js you can see how AngularFire is used.

If you’re looking for an AngularJS/Firebase example app, then take a look at the source for Firepoker.

Let’s Make a Framework Chronological List

Uri sent in a chronological list of the Let’s Make a Framework posts, because DailyJS is really just a static site so sometimes it’s a bit hard to make sense of long running article series:

Enyo 2.3.0

Ben Combee sent in a post about Enyo 2.3.0-pre.10:

If you’ve been following Enyo, you’ve probably noticed that it has been a while since our last public release. From the outside it may appear that the pace of Enyo development has slowed, but appearances can be deceiving — it has actually been an exceptionally busy, productive year for the Enyo team.

So what have we been up to? For starters, we’ve been doing some exciting UI work to support an upcoming LG product release. We can’t share this work with you just yet, but it will ultimately be open-sourced alongside our other Enyo libraries. We’ve also been pushing forward on the Ares IDE, with our HP team members playing a leading role.

Enyo 2.3 should improve data bindings, data layers, and adds the enyo.Application kind which is an entry point that can be used to organise data and functionality across the entire application.

The blog post explains how to get the prerelease and start using it.

Why Don't You Use Tap?

21 Oct 2013 | By Alex Young | Comments | Tags node libraries testing

I always write tests for my Node projects, and I default to using Mocha. It’s popular with DailyJS readers and good at what it does. About two years ago Isaac Schlueter published tap, which is an implementation of the Test Anything Protocol. I wrote about it back in 2010, but haven’t used it very often.

The TAP will appeal to you if you’ve ever had to deal with “corporate” CI servers and overcomplicated XML protocols. The protocol is inherently simple, so it’s easy to both produce and consume it. That means you can write tools that do things with tests, and plug tools together.

Also there are browser-friendly modules out there. Tape by Substack is a tap-producing test harness that works in browsers thanks to Browserify.

One thing I like about Isaac’s tap module is the tests feel natively asynchronous. The TAP itself is based around streams of test data, so it’s no surprise that it fits in well with Node. However, it’s the API that I really like: every test case must be ended with .end(), or the number of assertions is declared with .plan(n).

Why is declaring the number of assertions (tests) useful? Well, in Node projects we tend to nest asynchronous calls, so it makes sense to ensure assertions were run at all. I’ve seen many tests over the years that had assertions that would never be reached, yet the tests still passed because there was no way to express this.

Another thing I like about the Isaac’s tap module is the tests can be run with node test_file.js, because the module has to be loaded like this:

var test = require('tap').test;

test('make sure the thingie is a thing', function(t) {
  t.equal(thingie, 'thing', 'thingie should be thing');
  t.type(thingie, 'string', 'type of thingie is string');

Because test is loaded from the tap module, we can run the test with the Node command-line binary, or use Isaac’s provided tap command which collates results with the tap-results module.

Also, assertions are included in the t instance, so everything is neatly organised.

I’ve noticed that some prominent Node developers like Substack continue to use the TAP, but I feel like it’s fallen out of favour in the Node community. So, I want to inspire a TAP renaissance. Give it a try, and see how it compares with your preferred test framework.

AngularJS 1.2

18 Oct 2013 | By Alex Young | Comments | Tags angularjs browser mvc

RC3 for AngularJS 1.2 was announced recently, with the news that the official 1.2 release should be out next week. There’s a full changelog at the AngularJS GitHub repository.

This release has some major changes: ngAnimate has been rewritten, $q gets a shorthand for error handlers (.catch), forms can now be addressed with $scope.ctrl.form instead of $scope.ctrl.form, and jQuery 1.10.x is supported.

Some annoyances have been fixed as well. $httpBackend can set headers with falsy values, $log no longer prints undefined in IE, and numberFilter will use toFixed() to ensure that large numbers are formatted as expected rather than using scientific notation. There are many more bug fixes documented in the changelog.

This release will introduce breaking changes. Promise unwrapping has been deprecated:

This is a feature that didn’t prove to be wildly useful or popular, primarily because of the dichotomy between data access in templates (accessed as raw values) and controller code (accessed as promises).

Here’s an interesting one: inputs cannot have a name of hasOwnProperty:

Before, inputs whose name was “hasOwnProperty” were quietly ignored and not added to the scope. Now a badname exception is thrown.

The biggest changes are due to the ngAnimate rewrite. The latest documentation for that is available here: lastSuccessfulBuild/ngAnimate.

The animate service will automatically apply two CSS classes to the animated element and these two CSS classes are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported and can be used to play along with this naming structure.

JavaScript animations are also supported:

JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits the element’s CSS class attribute value and then run the matching animation event function.

From what I can tell the breaking changes sound sensible, so it looks like most projects will just need to verify the use of the animate service.

ES6 Generator Performance in V8

17 Oct 2013 | By Daishi Kato | Comments | Tags node modules npm es6
This is a guest post written by Daishi Kato.

Node’s getting ES6 generators – otherwise known as the yield keyword. For those who are not familiar with generators, here is a simple example that will yield a value up to five times when onetofive is called.

function* onetofive() {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  return 5;

It’s hard to see why that’s useful until we introduce a loop. We can call onetofive repeatedly like this:

function run() {
  var iterator = onetofive();
  obj = {};
  // Assuming obj.done is a boolean
  while (!obj.done) {
    obj =;
    // do something with obj.value
    // ex. console.log(obj.value);

See what’s happening? We’re able to use a standard loop keyword yet provide an asynchronous API.

When I ran this a million times, it took 360ms. Now, I know yield is much more descriptive and you can even send a value back, but we should compare it to the equivalent hand-written generator code.

function onetofive() {
  var array = [1, 2, 3, 4, 5];
  var index = 0;
  var iterator = {
    next: function() {
      return { value: array[index++], done: array.length <= index };
  return iterator;

Running this version with the previous condition took 265ms, which is comparable or a little faster.

The reason why I was investigating generators is because I am interested in how yield can be used to write tail-recursive code.

Let’s look at this idea in more detail. The following is a factorial function in a tail-recursive manner.

function fact_tail(x) {
  var fact_tail_sub = function(x, r) {
    if (x === 0) {
      return r;
    } else {
      return fact_tail_sub(x - 1, x * r);
  return fact_tail_sub(x, 1);

It’s relatively easy to follow, but it will consume a call stack for each sub function call. TCO (Tail Call Optimization) avoids such consumption, and we can use yield for TCO like the following:

function fact_tail_loop(x) {
  var fact_tail_sub = function* (x, r) {
    if (x === 0) {
      return r;
    } else {
      yield fact_tail_sub(x - 1, x * r);
  var c = fact_tail_sub(x, 1);
  var d = {};
  while (!d.done) {
    d =;
    c = d.value;
  return d.value;

Here there is no recursive call and it doesn’t exhaust the call stack. Note the similarity of fact_tail_sub with the previous example.

When I ran it several times with different values of x, it took 217ms. That isn’t bad, but I can do it a little differently without yield:

function fact_tail_loop2(x) {
  var LoopCont = function(f) {
    this.f = f;

  var fact_tail_sub = function(x, r) {
    if (x === 0) {
      return r;
    } else {
      return new LoopCont(function() {
        return fact_tail_sub(x - 1, x * r);

  var c = fact_tail_sub(x, 1);
  while (c instanceof LoopCont) {
    c = c.f();

  return c;

This is harder to understand, but the behavior is similar to the previous code. When I ran it with the same condition as the previous example, it took 63ms, which is much faster. By the way, this transformation is exactly what is done in

My observation at this point is that the code using yield doesn’t improve performance compared to the code which is carefully written like a generator. However, the performance characteristics might change if the optimization of generators goes well in V8 – and I hope it will.

* The evaluation is done with node-v0.11.5 on Intel Core2 Duo@3GHz PC.

Node Roundup: Browser Tests

16 Oct 2013 | By Alex Young | Comments | Tags node modules npm testing

I wanted to write about Substack’s Testling project, but then coincidentally Chris Scribner sent in his Browser Harness project. Let’s look at both to see how they shape up.


Testling (GitHub: substack / testling, License: MIT, npm: testling) is a tool for running tests in local instances of browsers. It works by using browserify – this allows Node modules to be used in browsers.


But what’s really going on? Follow Testling’s source into browser/prelude.js and you’ll find xhr-write-stream. Also, Testling uses browser-launcher which allows browsers to be launched headlessly through Xvfb or PhantomJS.

I installed browserify and testling then ran browserify test.js | testling and it opened Chrome and ran my tests. I wasn’t sure how to make Testling run it headlessly, or run it in a different browser, but apparently if you define a "testling" field in your package.json it should pick up your desired browser settings from there. Read more in testling field documentation.

Browser Harness

Browser Harness (GitHub: scriby / browser-harness, License: MIT, npm: browser-harness) takes a different approach. It uses client-side code to listen for commands to run tests. It currently uses NowJS for communication, but the author wants to replace it with Socket.IO.

It requires a file to be served from the domain of the site being tested, and has a few other limitations which are documented in the readme file.

The harness has built-in support for fibers, so if you install asyncblock you can write tests in a blocking style.

The example in the documentation uses Mocha, but the author notes that other test frameworks should work as well.

Script Roundup: Dolly.js, ngProgress

15 Oct 2013 | By Alex Young | Comments | Tags jquery plugins angular
Note: You can send your scripts and articles in for review through our contact form.


Dolly.js (GitHub: LunarLogic / dolly.js, License: MIT) from Lunar Logic is a jQuery UI widget for cloning fields in tables. It works like Excel and does not make any assumptions about the underlying data structure. Rows and cells can be constrained with selectors, and the API is event-based so you can hook up listeners to cloned events.

  rowSelector: 'div.row',
  cellSelector: 'div.cell'


ngProgress (GitHub: voronianski / ngprogress-lite, License: MIT) by Dmitri Voronianski is a port of NProgress for AngularJS applications. NProgress looks like the Chrome for Android progress bar which is a glowing blue line that grows to fill the top of the page.

The ngProgress demo page allows you to see how it works with buttons for each API call, for example: .set(0.4) and .inc(). This is the perfect way to give people feedback when your AngularJS app makes Ajax requests to the server.

Ghost: A Blogging Platform

14 Oct 2013 | By Alex Young | Comments | Tags node modules apps gbnc


Ghost (GitHub: TryGhost / Ghost, License: MIT) is a blogging platform built with Node and Express. It uses CasperJS for testing, and Bookshelf.js for the ORM layer.

Ghost started out as a Kickstarter project, with the aim of bettering WordPress. Ghost is run by a non-profit organisation, and released the source code today under the MIT license. Ghost is also run as a service, so you can create an account at and try it out without having to install it.

However, fortunately it is pretty easy to install: npm install --production and npm start should get it running. It’s easy because Bookshelf.js is database agnostic, so if your system has SQLite then it should be able to use it to store posts and users.

Event better, the fact Bookshelf.js is based around Backbone.js means you should be able to start hacking Ghost without much trouble. If you’ve done any work with Express and Backbone.js then Ghost’s source will be eminently hackable.

The project is split into client and server code, and it uses popular patterns like promises, Express route separation, and Express middleware.

The architecture of the project has been shaped by the need to allow people to easily install and theme Ghost blogs, which means it deviates from the typical Express applications I write which are bespoke services. The focus on theming came from the need to create a similar designer-friendly ecosystem that WordPress has, and already on launch themes and services that sell themes are available. You can read more about this in Ghost Launches to The Public.

The fact the project started off as a Kickstarter project with hundreds of eager alpha testers means it already feels mature. And unlike many open source projects it has a dedicated team and a business model behind it, so it’s definitely off to a promising start. I recommend giving it a look over if you’re an Express developer or just tired of your own blogging platform.