Licensing for JavaScript Projects

09 Apr 2012 | By Alex Young | Comments | Tags tutorials licensing

Each project we feature on DailyJS includes the license. If your project doesn’t include a license, it may not be used by the wider community and commercial developers.

Why is licensing important? From the author’s perspective, it can be used to influence how the project is reused. From our perspective, as users of your software, the license determines whether we can legally reuse your software.

License Types

Licenses are split into permissive and copyleft. Permissive licenses have less restrictive requirements about how the software can be redistributed – copyleft licenses aim to preserve the freedoms dictated by the original license.

Under these broad categories, the GPL is a copyleft license. The MIT license is a permissive license.

GNU’s site explains how to use the GPL. Other initiatives aim to help configure the most appropriate license for a given project, such as the Creative Commons non-profit organisation. For a large list of licenses, see the OSI’s list here: Open Source Licenses by Category.

jQuery Plugins and Client-side Projects

Many of the jQuery plugins we receive for review are dual licensed under the GPL and MIT. Why? Well, this allows the author of a derivative work to choose either license for their work.

The jQuery project itself has some comments on this: jQuery License

The MIT License is recommended for most projects. It is simple and easy to understand and it places almost no restrictions on what you can do with a jQuery project. If the GPL suits your project better you are also free to use a jQuery project under that license.

If you’re writing a jQuery project, consider adopting this approach as it’s widely used by the community.

Node Modules

It’s pretty clear at this point that Node developers like permissive licensing. Almost all of the Node modules we receive are MIT licensed. Let’s take a look at the current top 5 projects according to npm’s stats:

  • Underscore: MIT
  • CoffeeScript: MIT
  • Request: Apache License Version 2.0
  • Express: MIT
  • Async.js: MIT

Notice that the Apache License is also a permissive license.

Isaac Schlueter wrote an interesting post about a modification to permissive licenses called “no-false-attribs”: Wanted: “no-false-attribs” OSS License. People are starting to include “MIT no-false-attribs” with their projects to denote that any derivatives must amend incorrect references like contact information and bug reporting links.

How to Include a License

It’s not acceptable to simply paste a license’s text into your readme, or a license file in the project. The license must be edited to include your name and the date of copyright.

Include the name of the license in your project’s readme and the license file. The name is important – people don’t want to have to memorise and recognise license text, they simply want to look for license names they know are compatible with their project’s policies. From my perspective, I want to be able to include the license name in my articles.

Also consider writing a package.json – even if it’s not a Node project! A well-written package.json includes a license, author information, homepage and repository links.


  • Choose a license based on your organisation’s policies, or your own opinions – have a look at some permissive or copyleft licenses and see what fits
  • Include the name of your license in your project’s readme
  • Add the license to your project as a text file, and edit it to include your name
  • Write a package.json that includes the license name even if it’s a client-side project


This article was inspired by Why I’d like a “license type” setting for GitHub projects by Thomas Fuchs.

Krisztian Toth's JavaScript Games, XRegExp, PlastronJS

06 Apr 2012 | By Alex Young | Comments | Tags games closure-library regex

Krisztian Toth’s JavaScript Games

JavaScript Boulder Dash

Krisztian Toth makes browser-based conversions of retro games. JavaScript Boulder Dash is an extremely elaborate version of the classic Boulder Dash which includes a level creator. Krisztian has made the source available (in non-minimised form) here:

This is built on jQuery 1.7.1, and provides some interesting insights for those looking for guidance with game engine architecture.

Wizard of Wor

He’s also ported the Commodore 64 version of Wizard of Wor, with source available in jWoW.js.

Krisztian builds these games with a manifesto of sorts, where he tries to create addictive gaming worlds by writing code that aims to make the illusion as solid as possible, without distracting the user with overly technical solutions. I definitely enjoyed playing his version of Boulder Dash, even though I’m actually pretty bad at it (I blame my keyboard, I need a controller!)


XRegExp (GitHub: slevithan / XRegExp, License: MIT, npm: xregexp) by Steven Levithan is an impressive regular expression library that works in Node and even Internet Explorer 5.5. Regular expressions must be represented as strings to make Steven’s extensions possible, but the examples are compelling:

// Using named capture and flag x (free-spacing and line comments)
var date = XRegExp('(?<year>  [0-9]{4}) -?  # year  \n\
                    (?<month> [0-9]{2}) -?  # month \n\
                    (?<day>   [0-9]{2})     # day   ', 'x');

// XRegExp.exec gives you named backreferences on the match result
var match = XRegExp.exec('2012-02-22', date);; // -> '22'

// In fact, all XRegExps are RegExps and work perfectly with native methods
date.test('2012-02-22'); // -> true

Native prototypes can be extended to use XRegExp, if required, by calling XRegExp.install('natives').

Optional Unicode libraries are included which can be used to add support for several useful expressions:

XRegExp('^\\p{Hiragana}+$').test('ひらがな'); // -> true

XRegExp includes a whole load more, which is documented on both the project’s website at and the XRegExp readme.


PlastronJS (License: MIT) by Rhys Brett-Bowen is a new framework built on the Google Closure Library for use with the Closure Compiler:

PlastronJS though is not just an MVC framework, it’s the start of an application framework. I’ve decided to include a mediator and a store with the package which will hopefully help in the construction of medium to large size applications.

Models can be created by inheriting from the mvc.Model class:


 * @constructor
 * @inheritDoc
var Person = function(firstName, lastName) {
    goog.base(this, {attr: {
        'firstName': firstName,
        'lastName': lastName
    this.meta('name', ['firstName','lastName'], function(firstName, lastName) {
        return lastName + ", " + firstName;
goog.inherits(Person, mvc.Model);

Getters and setters are available using the model.get and model.set methods. Exceptions are used to handle validation errors – full details can be found in the project’s readme.

Data can be saved by using mvc.Syncmvc.AjaxSync and mvc.LocalSync have been included, but other implementations could be created if required. The sync/ajax.js file currently shows how PlastronJS would effectively communicate with a server.

The Google Closure Library itself is the base JavaScript used for most of Google’s flagship projects. For those who are missing Backbone-like MVC from Closure Library, then PlastronJS should work well.

Unix and Node: Interfaces

05 Apr 2012 | By Alex Young | Comments | Tags node tutorials unix cli

Earlier in this series I covered command-line arguments, which are well-supported in Node. There are times when a more interactive interface is required, however.

Fortunately, various node modules give us the tools to create command-line Unix programs with many different console-based interfaces, from Read-Eval-Print-Loops to GUI-like terminal control libraries.


Node’s Read-Eval-Print-Loop (REPL) is available as a module, and can be used to create interactive JavaScript shells. Node’s documentation has a cool example that uses a TCP server, so clients can connect with telnet.

The documentation is currently slightly inaccurate with regard to REPL.start – the callback method actually takes four arguments and won’t work as advertised. This example should work with the current version of Node 0.6:

var repl = require('repl')
  , vm = require('vm');

repl.start('> ', process, function(code, context, file, callback) {
  var result
    , err;

  try {
    result = vm.runInThisContext(code, file);
  } catch (err) {
    console.error('Error:', err);
  callback(err, result);

The process global is passed as the stream argument to make the REPL read and write to stdin and stdout. The callback method can do anything that’s required. For example, you could allow access to your database objects and methods in a web application, or provide an interactive administration interface to a daemon.


The repl module works well when a JavaScript shell is required, but what about a custom REPL? Node actually includes a Readline module, which is perfect for this:

var readline = require('readline')
  , rl;

rl = readline.createInterface(process.stdin, process.stdout, null);


rl.on('line', function(cmd) {
  if (cmd === 'quit') {
    rl.question('Are you sure? (y/n) ', function(answer) {
      if (answer === 'y') {
      } else {
  } else {
    console.log('You typed:', cmd);
    console.log('Type "quit" to exit');


rl.on('close', function() {


Here I’ve used the readline module to create an interface, then listen for line events which denote a line of text was typed. The question method will display a prompt and invoke the callback with the response.

By using simple string matching, a completely customised command-line interface can be created. The readline module also has some useful built-in features like command history.


The ncurses module by Brian White provides bindings to the ncurses library. This is a popular method for creating text-based user interfaces. If your application needs things like windows, menus, and more elaborate widgets such as a calendar, then ncurses is a good solution.

These bindings require a level of familiarisation with the original ncurses API. One freely available resource for learning ncurses is the NCURSES Programming HOWTO – combined with the ncurses-node README it’s possible to work out how to apply these techniques to a Node project.

Brian has also written some reusable widgets that come with the node-ncurses module:

var ncurses = require('ncurses')
  , widgets = require('ncurses/lib/widgets')
  , win = new ncurses.Window();

widgets.InputBox('Enter your name:', {
    pos: 'center',
    style: {
      colors: {
        bg: 'blue',
        input: {
          fg: 'red',
          bg: 'black'
  }, function(input) {
    if (!input) {
      input = 'nothing';
    win.centertext(0, 'You entered: ' + input);
    setTimeout(function() { win.close(); }, 1000);

I’ve adapted this example from Brian’s code – it should work if you install the relevant module with npm install ncurses. The result looks like this:

node-ncurses screenshot


There are simpler alternatives to ncurses. Libraries we’ve covered before, like Commander.js have prompts and dialogs. Then there’s ansi.js (License: MIT, npm: ansi) which makes working with 256 ANSI colours relatively painless, particularly for web developers who are familiar with hex colours:


TermUI (npm: node-term-ui) by Josh Faul has a chainable event-based API that can move the cursor around and output text with various colours:

  .out('Hello, world!');

There’s even a tab completion module: complete (License: MIT, npm: complete) by hij1nx. It’s actually designed to work with bash completion, and will write to .bashrc or .bash_profile:

# Node Completion - Auto-generated, do not touch.
shopt -s progcomp
for f in $(command ls ~/.node-completion); do
  test -f "$f" && . "$f"

There are dozens more interesting command-line UI libraries out there. If you’ve written something that you’d like us to feature in a Node Roundup post, then please get in touch!

Node Roundup: Nodetime, Flow.js, Lox

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


Nodetime screenshot

Nodetime (GitHub: dmelikyan / nodetime, License: MIT, npm: nodetime) by Dmitri Melikyan is an instrumentation service for profiling Node applications.

Once the nodetime module has been added to a project, running require('nodetime').profile() will cause it to start sending HTTP and database statistics to the Nodetime service:

The Nodetime profiler running within the application securely sends profiling data to the Nodetime server, where it is stored and sent to the browser in real-time. Profiling data is kept on the server for 10 minutes.

It’s also possible to avoid sending the profiling data to the server, by using require('nodetime').profile({ stdout: true }).

Nodetime is built on the author’s Timekit module, which adds some useful bindings to gettimeofday and getrusage.


Flow.js (License: MIT, npm: flow.js) by Tony Findeisen is inspired by Seq and Async.js, but is written from scratch rather than forking these projects. It’s based around the idea of creating ‘flows’ which can be executed synchronously or asynchronously. Results can be collected from each operation, and callbacks are used to signal the completion of parallel methods:

    a: function() {
      return 123;
    b: function(cb) {
        cb(null, 'I completed after 100ms');
      }, 100);
    // and even more
  .exec(function(err, results) {
    // results.a: 123;
    // results.b: 'I completed after 100ms');

This library uses the .length property of functions to determine if an argument has been supplied – if so, the function is considered asynchronous. Libraries like this benefit from the fact that functions in JavaScript are objects:

Every function in JavaScript is actually a Function object.

Flow.js comes with tests written with Mocha.

Function documentation at MDN


Lox (GitHub: reaktivo / lox, License: MIT, npm: lox) by Marcel Miranda is a Mongoose-based authentication middleware library for Express, and includes tests written with Mocha.

The lox function itself takes a MongoDB connection URI string, and the result can be passed to app.use. It needs suitable routes for managing users, but provides middleware for logging in and out:

# Sign in '/login', lox.routes.login('/success_uri', '/fail_uri')

# Sign out
app.get '/logout', lox.routes.logout('/success_uri', '/fail_uri')

jQuery Roundup: jQuery-CreditCardValidator, pow.js, idom

03 Apr 2012 | By Alex Young | Comments | Tags jquery plugins css validation templating
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.


jQuery-CreditCardValidator (GitHub: PawelDecowski / jQuery-CreditCardValidator, License: CC BY-SA 3.0) by Pawel Decowski is a nicely presented credit card validator:

$('#cc_number').validateCreditCard(function(result) {
  alert('CC type: ' + result.card_type
    + '\nLength validation: ' + result.length_valid
    + '\nLuhn validation: + result.luhn_valid');

All the popular cards are supported, including debit cards.



pow.js (GitHub: greim / pow.js, License: MIT) by Greg Reimer is an “algorithmic sunburst generator”. It’s a bit of fun with CSS, but I really liked the way the plugin is presented by combining the API options with form fields to create a self-documenting interface.


idom (GitHub: idibidiart / idi.bidi.dom, License: BSD) by Marc Fawzi is a data-driven templating library. It caches elements that have an idom-node-id attribute, and will insert values from JSON where the idom$ prefix has been used.

This project extends built-in prototypes to make the syntax that the author wants possible, and adds some jQuery plugin methods if it’s available. The author has some interesting ideas, so I’m hoping to see a version that works more like jQuery (avoiding using native elements).

cld.js, Presenteer.js, Algorithmic MochiKit Extensions

02 Apr 2012 | By Alex Young | Comments | Tags node language libraries jquery MochiKit


cld.js (License: BSD) by Janne Aukia is a language detection library, ported from the Compact Language Detector in Chromium using Emscripten. It should work in Node and browsers, and has a simple API for detecting languages:

var cld = require('./cld-min.js');

console.log('Language:', cld.detectLanguage('上'));
// Chinese
console.log('Language:', cld.detectLanguage('上か'));
// Japanese


Presenteer.js (GitHub: willemmulder / Presenteer.js, License: CC BY-SA 3.0) by Willem Mulder is a presentation library that’s based around a class that applies CSS3 transforms and transitions to a set of elements:

var presentation = new Presenteer('#presentation', $('#presentation > div'));

The presentation instance can then be interacted with using the mouse, or programatically with methods like presentation.start() and The nice thing about this API is multiple presentations can be displayed on a page.

Algorithmic MochiKit Extensions

Fredrik Blomqvist sent in his functional programming extensions for MochiKit. It includes an alternative bind method inspired by the one in the Boost C++ library that supports placeholder arguments. Other methods have also been extended to include placeholder arguments.

Fredrik has written several other MochiKit modules, inspired by Python:

Spaceship Pilot, CARPE Slider, CasperJS, lazyload

30 Mar 2012 | By Alex Young | Comments | Tags node iOS images games

Spaceship Pilot

Spaceship Pilot screenshot

Spaceship Pilot from Webdigi is a browser-based game that’s controlled by tilting an iOS device. A QR code can be used to easily launch the site that’s used to collect accelerometer data – the Google iOS app is a relatively painless way of doing this (using the image search).

The authors have written a blog post about the client and server-side code – the server uses Node and Socket.IO.

CARPE Slider

CARPE Slider by Tom Hermansson Snickars is a cross-browser slider widget with no dependencies. It doesn’t require any image files, and works well with both the mouse and keyboard.

When used with HTML5, data attributes can be used to configure sliders without extra JavaScript. Multiple sliders can safely coexist on a single page as well.

The project is distributed free for open source or non-commercial projects, otherwise it costs $99 for a license.


CasperJS (GitHub: n1k0 / casperjs, License: MIT) by Nicolas Perriault is a testing tool for PhantomJS.

Using PhantomJS seems like the ideal solution for creating advanced browser-like scripting environments, and CasperJS has an appealing API:

casper.start('', function() {
  // search for 'casperjs' from google form
  this.fill('form[action="/search"]', { q: 'casperjs' }, true);

casper.then(function() {
  // aggregate results for the 'casperjs' search
  links = this.evaluate(getLinks);
  // now search for 'phantomjs' by filling the form again
  this.fill('form[action="/search"]', { q: 'phantomjs' }, true);

The author has written a tutorial including installation instructions on the CasperJS homepage, and the project includes tests.


lazyload (License: MIT) by Vincent Voyer and Stéphane Rios is an image loader that uses a temporary base64 image:

  onload="lzld(this)" />

The authors opted to use the inline onload so each image effectively registers itself with the lazy loading system, rather than calling something like getElementsByTagName or querySelectorAll.

Unix and Node: Daemons

29 Mar 2012 | By Alex Young | Comments | Tags node tutorials unix daemons

As we’ve seen over the last few weeks, Node is a great platform for building portable Unix programs. This makes it a useful tool for developing daemons. I often find myself dealing with daemons, whether working as a web developer, sysadmin, or general Unix developer.


Why bother making a Node process behave like a daemon? There are several reasons, but generally because it’s a service that should be running at all times, in the background, and will automatically start after a reboot.

There are different ways to do this depending on the operating system. Most Linux distributions use System V compatible init scripts with runlevels. An alternative is upstart which is installed by default on Ubuntu systems.

BSD’s init behaves differently – there are no run levels. Solaris has the Service Management Facility which describes services using XML service manifests – I often find myself writing a simple XML file that wraps around a start/stop init script.

Finally, Mac OS has launchd which is a system wide and user-oriented daemon manager. It uses XML plist files, and the documentation for these can be found in man launchd.plist.

Linux Standard Base

Guidance for writing init scripts can be found in the Linux Standard Base’s section on Init Script Actions. This states that applications conforming to the standard should accept a single argument which should include one of the following:

  • start
  • stop
  • restart
  • force-reload
  • status

The status action works by returning specific exit status codes:

  • 0: The service is running correctly
  • 1: The program is dead and a /var/run pid file exists
  • 2: The program is dead and a /var/lock lock file exists
  • 3: The program is not running
  • 150 to 199 are reserved for your own requirements

Other actions are also expected to return specific status codes:

  • 1: Unspecified error
  • 2: Invalid arguments
  • 3: Unimplemented feature
  • 4: Insufficient privileges
  • 5: Program is not installed
  • 6: Program is not configured
  • 7: Program is not running
  • 150 to 199 are reserved for your own requirements

Most daemons are distributed without implementing all of these actions and status codes, but it’s a good idea to be aware of them.

Node Examples

StatsD (License: MIT, npm: statsd) from Etsy is a network daemon for aggregating statistics. It comes with the files for a Debian package, and includes an upstart script:

description "statsd"
author      "rdio"

start on startup
stop on shutdown

    # We found $HOME is needed. Without it, we ran into problems
    export HOME="/root"

    exec sudo -u nobody /usr/share/statsd/scripts/start
end script

Part of the installation process sets up log files with the correct permissions, and installs a configuration file to /etc/statsd. It’s usually a good idea to support a system-wide configuration file that can be overridden for the purpose of distributing daemons.

The log file is created in /var/log/statsd/, which is standard as well.

This daemon loads the configuration file based on the command-line argument:

config.configFile(process.argv[2], function(config, oldConfig) {
  // Process the configuration file

Some daemons may opt to check for configuration files in default locations, loading them in order of preference:

  • /etc/mydaemon/config.js
  • $HOME/.mydaemon/config.js

Init Module

Developing a Linux-friendly init script is made easy by the Init Node module by Paul Driver. He’s actually implemented the correct status codes, and the daemon module has been used, so you essentially get a real background daemon with very little code:

var init = require('init');

  pidfile: '/var/run/',
  logfile: '/var/log/myprog.log',
  command: process.argv[3],
  run: function() {
    setInterval(function() {
      // Will be redirected to /var/log/myprog.log
    }, 1000);

Notice that console output will be redirected to a log file, so in this case “Running” will be printed to /var/log/myprog.log.

Wrapper Scripts

The Init module turns a Node script into a daemon, but what if your daemon needs to accept various command-line parameters rather than just start/stop/restart? In this case, most people either write a shell script to provide a System V init wrapper, or they might use an upstart script as we saw with StatsD.

Of course, other Unix systems have different init implementations, but a simple init script or init script-compatible Node module can usually be coerced into working with systems like Solaris’ SMF.

You’ll need basic shell scripting skills to write an init script, but there’s an example of one in Fedora’s packaging documentation: SysVInitScript.

Packaging Guidelines

If you want to reach a wider audience, packing guidelines often have useful tips on how to distribute daemons as well:

Node Roundup: 0.6.14, Mocha 1.0, ncluster, ENVy

28 Mar 2012 | By Alex Young | Comments | Tags node modules deployment mocha testing
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.6.14

Node 0.6.14 was released soon after 0.6.13. This release includes bug fixes and updates npm to 1.1.12.

Mocha 1.0

Mocha 1.0 has been released. There’s now a GitHub-flavoured Markdown reporter, and JavaScript “compilers” are now supported with mocha --compilers coffee:coffee-script.

An API has also been added, so it’s possible to programatically create tests:

var mocha = new Mocha;



ncluster (npm: ncluster) by Ben Murphy is a zero-downtime clustering solution. It’ll reload the application when a SIGHUP is issued, and gracefully quit when SIGQUIT is sent.

Ben has designed it to be used with Capistrano. He’s also created a Node/Ubuntu Vagrant deployment solution with instructions for deploying his demo app to a virtual machine (nodejs_vagrant_helloworld).


ENVy (npm: envy) by Elio Capella Sánchez is a small module for managing JSON settings files. It’ll use require to load a file called config.json in the project’s root directory.

It also uses a convention for automatically determining the environment and loading the appropriate properties. Given a JSON file like this:

  "environment": "development",

  "development": {
    "test": "Development property"

  "production": {
    "test": "Production property"

Then require('envy').config will load the development settings, so config.test will return “Development property”.

jQuery Roundup: 1.7.2, Filtrify, JsBehaviour, Rest Test Test

27 Mar 2012 | By Alex Young | Comments | Tags jquery plugins tags rest libraries debugging
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery 1.7.2

jQuery 1.7.2 has been released. This release mainly includes fixes, but there are also tweaks that improves API consistency. There’s an important note for jQuery Mobile users on which jQuery version to use:

If you’re using jQuery Mobile, please use jQuery 1.7.2 only with jQuery Mobile 1.1. For previous versions of jQuery Mobile, stay with jQuery core 1.7.1 or earlier.


Filtrify screenshot

Filtrify (GitHub: luis-almeida / filtrify, License: MIT) by Luís Almeida is a Chosen-inspired tag filtering plugin. It allows multiple tags to be selected and searched, and multiple Filtrify instances can be used on a single page.

The markup is based on data attributes:

<div id="placeHolder"></div>

<ul id="container">
  <li data-genre="pop, rock, british, classic rock"> The Beatles </li>
  <li data-genre="rock, british, blues, classic rock"> The Rolling Stones </li>
  <li data-genre="alternative, electronic, female vocalists"> Björk </li>
  <li data-genre="rock, alternative, grunge"> Foo Fighters </li>
  <li data-genre="rock, classic rock"> Bruce Springsteen </li>

Now calling $.filtrify('container', 'placeHolder') will add the selector to the page.

The plugin accepts lots of options, including a property for supplying a callback that fires when tags are added or removed.


JsBehaviour (License: MIT) by DracoBlue is similar to Declarative that we featured last week – both are essentially tools for associating complex behaviour with markup as unobtrusively as possible.

Handlers must be registered with jsb:

jsb.registerHandler('example', function(el, options) {
  element.textContent = 'I am loaded with name: ' +;

Then parameters can be supplied to JsBehaviour like this:

<span><input class="jsb_ jsb_example" type="hidden" value="{&quot;name&quot;:&quot;Jan&quot;}" />Are you loaded?</span>

Running this example would produce I am loaded with name: Jan.

JsBehaviour expects “enhanced” elements to include a jsb_ class. The author has written more about this library with examples on the JsBehaviour blog.

Rest Test Test

Rest Test Test (GitHub: jeroenooms / resttesttest) by Jeroen Ooms is a jQuery and Bootstrap-based HTTP testing tool. It allows various HTTP methods to be issued, along with parameters. The results are displayed with the associated HTTP headers.

The author recommends using this with Firebug for testing REST services and Cross Origin Resource Sharing (CORS).

Gazel, Heroku Node Versions, nios

26 Mar 2012 | By Alex Young | Comments | Tags node browser hosting indexeddb database iOS


Gazel (GitHub: matthewp / gazel, License: MPL 2.0) by Matthew Phillips is a key-value store for browsers, based on Redis. The API is similar to Redis, and has a friendly chainable syntax:

var client = gazel.createClient();

client.on('error', function(err) {
  console.error('Error:', err);

  .set('key', 1)
  .incrby('key', 10)
  .exec(function(results) {
    var key = results.pop()[0];

It uses IndexedDB for storage, and will attempt to use vendor-specific versions where available. The author has written a sizeable suite of Mocha tests that can be run in a browser.

Heroku Node Version Support

Heroku now permit Node and npm versions to be requested using your application’s package.json file:

  "name": "myapp",
  "version": "0.0.1",
  "engines": {
    "node": "0.6.x",
    "npm":  "1.0.x"

The available versions are listed here:

Heroku defaults to their oldest version of Node 0.4, so it’s probably a good idea to specify the latest 0.6 version.

Read more here: Specifying a version of Node.js / npm


Node iOS

nios by Sebastian Waisbrot is a Node port for iOS. The objective is to allow Node projects to run on an iOS device with minimal modifications. It uses WebViewJavascriptBridge to run Node’s libraries.

The example that comes with the project runs a Node HTTP server within a native iOS app.

tQuery Web Audio, JavaScript Motion Tracking, Reified, Thing.js

23 Mar 2012 | By Alex Young | Comments | Tags ECMAScript ES5 audio binary node

tQuery Web Audio

Jerome Etienne has added support for the Web Audio API to the development branch of his tQuery project. tQuery.WebAudio shows off the API, and he’s also written a tutorial with a screencast: tQuery WebAudio for More Realistic 3D.

JavaScript Motion Tracking

Romuald Quantin sent in an article on JavaScript Motion Tracking which has a demo and some explanation behind the Canvas-based effect.


Reified (License: MIT, npm: reified) by Brandon Benvie is a binary library for Node and browsers. Each supported binary type is implemented using buffers:

var reified = require('reified')
  , int32 = new reified('Uint32', 10000000)
  , int16 = new reified('Uint16', int32)
  , int8 = new reified('Uint8', int16);

// Uint8 100

// Exception: TypeError: Invalid value for Uint8: undefined

There are also constructors for arrays, structs, and bitfields:

var DescriptorFlags = reified('DescriptorFlags', {
  READONLY     : 3,
  WRITABLE     : 4,
  FROZEN       : 5,
  HIDDEN       : 6,
}, 1);

var desc = new DescriptorFlags;
desc.HIDDEN = true;

// { ‹DescriptorFlags›
//   ENUMERABLE:   false,
//   CONFIGURABLE: true,
//   READONLY:     true,
//   WRITABLE:     true,
//   FROZEN:       true,
//   HIDDEN:       true,
//   NOTPRIVATE:   true }


Thing.js (GitHub: matthewp / thingjs, License: MPL 2.0, npm: thingjs) by Matthew Phillips is a small library that wraps around the ES5 Object.create method to provide mixins and object initialisation:

var Thing = require('thingjs')
  , A = { name_a: 'a' }
  , B = { name_b: 'b' }
  , C;

C = Thing.create([A, B], {
  init: function() {

// Returns an instance of C
Thing.create(C, true);

Unix and Node: Processes

22 Mar 2012 | By Alex Young | Comments | Tags node tutorials unix

Last week in Unix and Node: Signals I discussed how to interact with Node processes using POSIX signals. We often also need to run multiple processes, but how exactly can we launch processes from Node, and how can we manage multiple processes programatically?

This depends on the architecture of your application. If you’ve got a situation where consumers take work from a queue – perhaps from a messaging system like RabbitMQ or from a centralised database – then multiple processes can be launched from the shell. The standard Unix rules apply:

  • Consider writing a PID file using
  • If the processes are long-running, then listen for the appropriate signals
  • Exit with a non-zero code using process.exit when an unrecoverable error occurs
  • Use the right output streams – log errors with console.error and messages with console.log, or consider using a library like winston to handle logging

If your Node programs adhere to these rules then it’s fairly easy to manipulate them at the system level using shell scripts or makefiles.

Spawning Processes

Running a child process using child_process.spawn has a familiar event-based API:

var spawn = require('child_process').spawn
  , ls = spawn('ls', ['-latr']);

ls.stdout.on('data', function(data) {

ls.on('exit', function(code) {
  console.log('Child process exited with code:', code);

The object returned by spawn has the standard streams, which also have event-based APIs. It also makes grabbing the exit code pretty easy.

An alternative is child_process.exec which has a lighter syntax:

var exec = require('child_process').exec;

exec('ls -latr', function(err, stdout, stderr) {

The interesting thing about exec is it takes a second argument that includes useful options like timeout and env. If you’re running something resource intensive but only want it to run for a few seconds, then exec('command', { timeout: 1000 }) is extremely convenient.

There’s another related method which is execFile – this one doesn’t run a subshell, so you’ll want to use the full path to the command.

Node processes can be spawned using child_process.fork which allows messages to be passed to the child process. There’s a full example in the Node documentation on fork. If you need to pass messages between processes then this is an easy way to do it without involving something more complex.


Node’s Cluster API offers a programmatic solution to process management. This is particularly attractive when you need to take advantage of multiple cores or CPUs but don’t want to use a full-blown messaging system.

Workers can be spawned using cluster.fork, and when they die a death event is fired. This example is adapted from Node’s documentation:

var cluster = require('cluster')
  , http = require('http')
  , numCPUs = require('os').cpus().length
  , i
  , worker
  , numReqs = 0;

if (cluster.isMaster) {
  console.log('Master PID:',;

  // Start a set of workers based on the number of CPUs
  for (i = 0; i < numCPUs; i++) {
    var worker = cluster.fork();
    worker.on('message', function(msg) {
      if (msg.cmd && msg.cmd == 'notifyRequest') {
        console.log('Total requests:', numReqs);

  // Log when the worker dies
  cluster.on('death', function(worker) {
    console.log('Worker died, with PID:',;
} else {
  console.log('Worker PID:',;

  http.Server(function(req, res) {
    res.end('Hello from ' + process.env.NODE_WORKER_ID + '\n');

    process.send({ cmd: 'notifyRequest' });

  console.log('Listening on port 8000');

First, cluster.isMaster is used to determine if the current process is the master or a worker. Next, cluster.fork is used to spawn a new worker – this can only be called from the master process. A listener is set up on the worker for a message event – later on process.send is used to notify the master process of an event. This is a useful form of message passing that allows JavaScript objects to be sent as messages.

If the process isn’t the master then a HTTP server is started; each worker is now effectively sharing HTTP requests across CPU cores. The interesting thing about cluster.fork is it allows TCP servers to be shared across workers, and notice that the message passing API used here is available with child_process.fork as well.

Running this demonstrates that the PID files work as expected:

➜ node cluster.js
Master PID: 31839
Worker PID: 31840
Listening on port 8000
Worker PID: 31842
Listening on port 8000
Worker PID: 31844
Listening on port 8000
Worker PID: 31843
Listening on port 8000
Worker PID: 31841
Listening on port 8000
Worker PID: 31845
Listening on port 8000
Worker PID: 31846
Listening on port 8000
Worker PID: 31847
Listening on port 8000

Killing a worker behaves as expected, too:

➜ kill 31845
Worker died, with PID: 31845

The servers will still be running, and Node won’t try to access the dead worker no matter how hard you try.

Killing Clusters

This all works fairly well and may reduce the amount of work it takes to run groups of Node processes, but until recently Node didn’t automatically kill workers when the master is killed. In the previous example, kill 31839 (which was the master’s PID) will leave the children hanging around.

There are many ways to deal with this – Linux comes with setsid which can be used to run programs in sessions. The master process would then be the session leader, and the signals would be sent to each worker.

It can also be handled manually by keeping an array of workers around:

process.on('SIGTERM', function() {
  console.log('Master killed');

  workers.forEach(function(w) {


Issuing SIGINT by pressing ctrl c seems to have the desired effect by default.

Node Roundup: 0.6.13, 0.7.6, ShareJS, Route66

21 Mar 2012 | By Alex Young | Comments | Tags node modules connect middleware apps
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.6.13 and 0.7.6

Node 0.6.13 (stable) and 0.7.6 (unstable) have been released. These releases also update npm, and I noticed npm can now take OS and CPU properties in package.json. This is documented in the man page, so to read more type man npm-json or view the online version here:

Architectures and operating systems can even be blacklisted, so if you’re sure your module runs fine everywhere except Windows, then this can be represented with "os" : [ "!win32" ].


ShareJS (GitHub: josephg / ShareJS, License: MIT, npm: share) by Joseph Gentle is an application that can be used to add concurrent editing to any web application. The server is Node, and the client is expected to use Ace for editing.

The author has already put together a ShareJS wiki with extra documentation (although the readme is pretty good too). Also of note is the decision to use Operational Transformations:

Most wikis have a ‘save’ button and do locking. OT is a class of algorithms that do multi-site realtime concurrency. OT is like realtime git. It works with any amount of lag (from zero to an extended holiday). It lets users make live, concurrent edits with low bandwidth.

According to the project’s documentation, Joseph is an ex-Google Wave engineer (his LinkedIn profile mentions “Engineering Intern at Google”). Also, ShareJS has a 1:1 code to test LoC ratio.


Route66 (GitHub: vdemedes / route66, License: MIT, npm: route66) by Vadim Demedes is a middleware for routing in Connect 2.0. Vadim missed the connect.router middleware that was removed from Connect, so he created a replacement.

The decision behind removing the router was discussed at length in the Remove router ticket in Connect’s GitHub issues.

jQuery Roundup: Declarative, jQR, Ender-Carousel, Stapes.js

20 Mar 2012 | By Alex Young | Comments | Tags jquery plugins ender frameworks libraries
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.


Declarative (License: MIT, npm: declarative) by Alex Lawrence allows HTML to be mapped to behavioural JavaScript using mappings. The author’s first example is a search form with a character counter that uses the following HTML:

<form action="/" method="POST">
  <input id="search" name="search" type="text" maxlength="50" />
  <span data-widget-counter="target: 'search', text: '{0} characters left'"></span>
  <input type="submit">

Notice the use of data attributes to supply options to the JavaScript mapping:

  id: 'counter',
  prefix: 'data-widget-',
  types: ['counter']
  callback: function(counter, type, options) {
    var input = document.getElementById(;
    var maxlength = input.getAttribute('maxlength');
    countCharacters(input, counter, maxlength);

Once a mapping has been declared, it can be mapped to the whole DOM using apply:


None of this depends on jQuery, but the author has provided examples that demonstrate jQueryUI integration. Jasmine tests and examples are included in the project’s source.


jQR (GitHub: Gottox / jQR, License: GPL3) by Enno Boland is a QR Code generator for jQuery. It’s similar to jquery.qrcode.js by Jerome Etienne, featured previously on DailyJS – both use the same method name:

$('#qrcode').qrcode('Hello World');

Jerome’s plugin includes qrcode.js by Kazuhiko Arase, whereas Enno’s plugin is a rewrite that’s influenced by Kazuhiko’s original code.


Ender-Carousel example

Ender-Carousel (GitHub: nemeseri / ender-carousel, ender: ender-carousel, npm: ender-carousel) by Andras Nemeseri is a carousel plugin for Ender that’s jQuery-compatible. The Ender-Carousel Basic Configuration Tutorial has sample HTML, CSS, and JavaScript, which is just $('.carousel').carousel().


Stapes.js (GitHub: hay / stapes, License: MIT) by Hay Kranen is a small JavaScript MVC framework. Like other recent takes on MVC, it’s based around events and inheritance. It also works nicely with RequireJS, jQuery, and Zepto.

Stapes uses modules:

var Module = Stapes.create();

  init: function() {

Modules include data methods for getting and setting attributes:

var module = Stapes.create();

  name: 'Alex'
, title: 'Mr'

module.get('name'); // Alex

Attributes can be removed, filtered, and updated. The author has written up full documentation and a rationale behind the project at the Stapes.js homepage.

Shardjs, soma.js, jsprops

19 Mar 2012 | By Alex Young | Comments | Tags libraries testing node browser


Shardjs (License: MIT) by Francesco Sullo is a module for managing keys of up to 3844 Redis nodes. The author was inspired by Sharding and IDs at Instagram where the Instagram developers discuss a solution to generating unique IDs at scale.

To get around the lack of 64-bit integers in JavaScript, the author has opted to use 62-bit strings. He discusses his algorithm for generating unique keys and where the number 3844 comes from in the project’s readme:

The advantage of this approach is that since all the keys generated at the same millisecond will go on the same virtual shard and there is the incremental sequence, we can mantain the key well sorted by time.


soma.js (GitHub: somajs / somajs, License: MPL) by Romuald Quantin is a new MVC framework that uses the observer pattern with native events, and the command pattern, with the ultimate goal of encouraging development of decoupled modules:

The command pattern aims to encapsulate method invocation, requests or operations into a single object and gives you the ability to both parameterize and pass method calls around that can be executed at your discretion. In addition, it enables you to decouple objects invoking the action from the objects which implement them, giving you a greater degree of overall flexibility in swapping out concrete ‘classes’.

– Addy Osmani on the command pattern

In soma.js applications, there are wires, models, views, and commands. Wires are used to represent the logic of an application and coordinate between other elements of the framework. Models don’t necessarily imply a particular storage solution, they’re more like a convention for integrating with other solutions like localStorage or Knockout – there’s a demo showing how to use soma.js with Knockout’s data bindings.

The project’s website includes demos and a tutorial that explain how everything works.


jsprops (License: MIT) by Tobiasz Cudnik adds class-based properties to prototypes, the goal being to reduce redundancy when copying properties to instances. It also includes inheritance-based signalling.

Tobiasz has included CoffeeScript and JavaScript examples, but I’ve reproduced the JavaScript one here because it’s a little bit easier to understand:

var property = require('jsprops').property;

function Klass() {} = property('foo'); = property('bar', null, 'def_value');
Klass.prototype.baz = property('baz', {
  set: function(set, val) {
    set(val.replace(/a/, 'b'));

The project comes with tests that further illustrate the intended usage.

Augmented Reality in the Browser, Springbase, jQRange

16 Mar 2012 | By Alex Young | Comments | Tags node webgl jquery ranges

Augmented Reality in the Browser

In Augmented Reality in the Browser, Jerome Etienne discusses WebRTC and how to combine WebGL with a live video feed – all in a browser.

To simplify this process, Jerome has created tquery.jsartoolkit, which uses his tquery library to wrap around JSARToolKit. JSARToolKit, by Ilmari Heikkinen, is the core of the augmented reality functionality.


Springbase (GitHub: springbase / node-springbase, npm: springbase) have released a Node driver for their relational data store. This is a hosted database solution that includes a web data browser and management interface, and even SQL support.

The API is event based:

var springbase = require('springbase')
  , conn
  , query;

conn = new{
  application: '1GmTdS2ayPts',
  username: '<email>',
  password: '<password>'

query = conn.getQuery('qryStoreInventoryByZipCode');
query.on('ready', function() {
  var reader = query.execute({ zipCode: 94611 });
  reader.on('row', function(row) {
    console.log('Found store:', row);

They’re currently offering a free account with 100 MB storage and 1 GB per month bandwidth (I get no remuneration for mentioning this).


jQRange (GitHub: Gottox / jQRange) by Enno Boland attempts to help deal with W3C and Internet Explorer ranges. The current selection can be obtained with $.range('^'), and ranges can be spanned with $(selector).range().

The plugin even supports regular expressions, so any range matching a given pattern can be spanned. The author has included QUnit tests, and a lot more functionality is documented in the readme file.

Unix and Node: Signals

15 Mar 2012 | By Alex Young | Comments | Tags node tutorials unix daemons signals

Signals represent a limited form of inter-process communication. When a signal is issued to a process, it will be interrupted and a signal handler will be executed. If there is no signal handler, the default handler will be called instead. This sounds a lot like asynchronous events in Node, and that’s exactly how signals are implemented; using process.on:

process.on('SIGINT', function() {

Typing man sigaction in a terminal will display some background on signals, including a useful list of signal names and their descriptions.

Using Signals

Create a file called signals.js that contains the following, and chmod +x it:

#!/usr/bin/env node

process.on('SIGINT', function() {
  console.log('Got a SIGINT');

process.on('SIGHUP', function() {
  console.log('Got a SIGHUP');

setInterval(function() {
    console.log('Daemon running');
}, 10000);


Now chmod +x signals.js and run it with ./signals.js. It’ll print out its PID – this can be used with the kill command to issue signals:

➜ ./signals.js &
PID: 12626
➜ kill -s SIGHUP 12626

Running the command with & to put it in the background will actually display the PID in most shells, but I put in there just to demonstrate how to get the PID in Node. Once you’ve sent a few signals to it, issuing a SIGINT will end the process.

Usage in Node

A common use of signal events in Node is to perform some kind of cleanup when a process is terminated. Where signals really come in handy is for communicating with daemons. Many daemons accept SIGHUP to reload configuration files – I followed the same convention when I built an IRC daemon in Node. Another convention is to listen for SIGTERM to perform a graceful shutdown. This could be used to close down sockets, database connections, or remove any temporary files.

I believe Node is a great solution for writing Unix daemons. It’s a good idea to follow established conventions, so add listeners for SIGHUP and SIGTERM.

Node Roundup: Command-Option-Argument, Nodemailer, Node.js-Ultra-REPL

14 Mar 2012 | By Alex Young | Comments | Tags node modules inspectors repl email
You can send in your Node projects for review through our contact form or @dailyjs.


Command-Option-Argument (npm: coa) by Sergey Berezhnoy is a command-line option parser that uses a chainable API:

require('coa').Cmd() // main (top level) command declaration
  .name(process.argv[1]) // set top level command name from program name
  .title('My awesome command line util') // title for use in text messages
  .helpful() // make command "helpful", i.e. options -h --help with usage message
  .opt() // add an option
    .name('version') // name for use in API
    .title('Version') // title for use in text messages
    .short('v') // short key: -v
    .long('version') // long key: --version
    .flag() // for options without value
    .act(function(opts) { // add action for option
      // return message as result of action
      return JSON.parse(require('fs').readFileSync(__dirname + '/package.json'))
    .end() // end option chain and return to main command

The API’s chainable design uses stack-like hierarchies, so when an option is declared with opt() subsequent method calls will apply to that option. The author has included a makefile which runs tests with Vows.


Nodemailer (License: MIT, npm: nodemailer) by Andris Reinman is a module for sending emails that supports Unicode, attachments, connection pools, and SSL/STARTTLS. It’s even designed to work with popular mail services like Gmail and Hotmail.

The API centres around SMTP transports:

var nodemailer = require('nodemailer')
  , smtpTransport = nodemailer.createTransport('SMTP', {})
  , options = { from: '', subject: 'Subject', text: 'Hello' };

smtpTransport.sendMail(options, function(err, response) {

Notice the use of the standard leading error argument in the callback. This project includes a test suite written with Nodeunit.



Node.js-Ultra-REPL (License: MIT, npm: ultra-repl) by Brandon Benvie is a REPL for Node that’s intended to be used as a development environment. It provides a command-line UI where JavaScript can be executed and explored. Before using it, I strongly recommend pressing F1 to learn the basic commands. The command prompt stays at the bottom of the screen, while the result of any code is displayed above. Results can be read through by using page up and down. New V8 contexts can be created using control shift up, then switched between using control up and control down.

jQuery Roundup: 1.7.2 RC1, OEmbed All, Ignition, nextVal, jquery-ui-rails

13 Mar 2012 | By Alex Young | Comments | Tags jquery plugins frameworks embedding validation
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery 1.7.2 RC1

jQuery 1.7.2 RC1 has been released. Several bugs have been fixed since the last beta release, which are fully documented in the announcement blog post. The announcement also contains an interesting call for IE6 help:

If you are particularly interested in IE6 support, please help us out. We are having sporadic trouble running the unit tests in IE6. It hasn’t been possible for us to determine the cause of these problems, but the problem doesn’t happen consistently and the sheer size of our test suite may just be overwhelming a browser that is more than a decade old.

jQuery OEmbed

jQuery OEmbed All (GitHub: starfishmod / jquery-oembed-all, License: MIT) can embed content like YouTube videos simply by providing a URL to the item’s page. It was originally created by Richard Chamorro, but this version has been forked by Andrew Mee to rely less on the OEmbed API.

The plugin will attempt to use various third party services to embed the content, including JSONP oEmbed and YQL. Services that require an API key are also supported:

  embedMethod: 'auto',
  apikeys: {
    etsy: '<your etsy key>'


Ignition logo

Ignition (GitHub: daytona / ignition, License: MIT/GPL) by Johan Sahlén of Daytona Communication AB is a jQuery MVC framework. It was sent in by Wade Stebbings who said he’d struggled to find information on it after it was recommended by a friend. It’s definitely an interesting framework, even though it seems to have stalled development in 2009.

It supports URL routing:

var $i = new Ignition({ modules: ['UrlManager', 'HistoryDispatcher'] });

$i.addRoute('articles/(\d+)', function(article_id) {

And models:

$i.m('Article', {
  find_by_id: function(id, callback) {
    this.json($i.getUrl('article', { id: id }), { success: callback });

Controllers and programmatic views are also included:

$i.c('Articles', {
  show: function(id) {
    $i.m.Article.find_by_id(id, $;

$i.v('Articles', {
  show: function(data) {
    var list = $('<ul id="articles"></ul>');
    for (var i = 0; i < data.articles.length; i++) {
      var article = data.articles[i];
      var listItem = $('<li><a href="'+article.url+'">'+article.title+'</a></li>');


API documentation is available if you want to dig a little deeper into the framework: Ignition API documentation.


nextVal (GitHub: jukebox42 / nextVal, License: MIT) by John Norton is a form validation plugin. It uses a validate attribute with options that work a little bit like a mini validation DSL:

<input type="text" validate="email" placeholder="Please enter a proper email address" />

Then $(selector).nextVal() can be called on the form. Custom validation rules can also be added:

$(function() {
         ['matchpassword',function($o){return !($o.val() == $('#password').val());},''],
         ['xheader',function($o){return !$o.val().match(/^X-[a-zA-Z0-9_\-]+$/);},'Please enter a valid xheader. For example X-UserData1'],

The only problem I have with this approach is the use of the validate attribute. To my knowledge, there is no validate attribute, so this should probably use a data attribute instead. Also, HTML5 already provides some validation attributes (required, pattern, min and max, step, and maxlength).


jquery-ui-rails makes adding jQuery UI 1.8.18 and its associated assets easy to install in Rails projects. It’s configured to work with the Rails asset pipeline, so it’s easy to require specific modules and get jQuery UI projects off the ground quickly.