ES6 Metaprogramming, Barn

09 Dec 2014 | By Alex Young | Comments | Tags es6 proxies redis browser localStorage

ES6 Metaprogramming

The last time I seriously looked at JavaScript metaprogramming I tried all kinds of dubious things like exploiting the with statement. With ECMAScript 6 proxies, the situation might be about to change. In Meta programming with ECMAScript 6 proxies, Dr. Axel Rauschmayer writes about the concept of metaprogramming, the different approaches (introspection, self-modification, intercession), and provides JavaScript examples.

This article includes an overview of proxies and what they’re useful for, and shows how they can be used for intercepting method calls. He also mentions how proxies impact performance:

Data binding is a complex topic. Given its popularity and concerns over proxies not being performant enough, a dedicated mechanism has been created for data binding: Object.observe(). It will probably be part of ECMAScript 7 and is already supported by Chrome.

This is an in-depth article that is worth taking some time over, but will influence many people who are creating the next generation of ECMAScript 6-based APIs.


Barn (GitHub: arokor/barn, License: MIT, npm: barn) by Aron Kornhall is an API for localStorage that is based on Redis. The idea is to make operations atomic, so they survive things like a tab being closed or unexpected exceptions.

If you’re used to Redis, then you might like this:

var barn = new Barn(localStorage);

barn.set('key', 'val');
console.log(barn.get('key')); // val

barn.lpush('list', 'val1');
barn.lpush('list', 'val2');
console.log(barn.rpop('list')); // val1
console.log(barn.rpop('list')); // val2

Internally a mutating flag is used to provide a locking mechanism around the localStorage access. I think this should prevent issues that you might get when performing multiple writes, because the Web Storage specification says writes don’t wait until the data has been written to disk.

Barn itself is based on NSStorage, which is also written by Aron. NSStorage is a smaller module that provides namespacing for the Web Storage API.

Mask.js, Sloc

08 Dec 2014 | By Alex Young | Comments | Tags build-tools browser jquery


Mask.js (GitHub: bguzmanrio/maskjs, License: GPL) by Borja Guzmán is a library for validating input fields against dates, numbers, and text. It allows people to type in dates using numbers so they don’t have to type in the necessary punctuation.

It prevents invalid input from being typed and allows you to skip between numbers, so it’s less rigid than some implementations.

The API uses methods on Mask:

  $el: $(''),
  mask: 'HH:mm',
  errorFunction: function() {},
  defaultValue: '12:00'


If you want to generate metrics for a project like source code length, how do you do things like ignore comments and empty lines? Sloc (GitHub: flosse/sloc, License: MIT, npm: sloc, Bower: sloc-bower) by flosse handles these edge cases and more. It also supports lots of languages, including JavaScript, CoffeeScript, Lua, and Swift.

It comes with a command-line script that you can run with sloc file.js, and it’ll automatically recurse directories. There are options for ignoring files (--exclude pattern) and selecting an output format (--format [json|csv|cli-table]).

Sloc has a Node module, so you can require('sloc') and run sloc(source, language) to get an object with various statistics. The project itself is well-tested, and has some cool usages like atom-sloc.

Node Advisory Updates and Node Forks

05 Dec 2014 | By Alex Young | Comments | Tags community node

As someone who works professionally with Node and writes about it regularly, I’ve naturally been following the discussions about Node forks and the Node advisory board. I’ve been collecting articles in Instapaper and highlighting things like crazy to figure out what’s going on.

On Wednesday TJ Fontaine posted an advisory board update on the official Node blog. The board has had three meetings so far which you can follow on GitHub: nodejs-advisory-board/meetings.

The most recent minutes mention the ongoing discussions about the Node trademark:

The group will utilize Mongo, Eclipse, and Docker as examples projects to draw from. Agreed that there is no certification products and since there is no process to do that, there will be no certification for training or product compatibility. Project teams should be publishing the acceptance testing and organizations that want to test against the test suite and should be posting the results to the node.js repo

The advisory board have decided that the Node project should be run based on a consensus, rather than a dictatorship:

One thing that we all agree on, is that we’re not going to be using the Benevolent Dictator model. In fact, recently the project hasn’t been operating that way. We can be more clear about that in our documentation. We all agree we want a healthy and vibrant team, a team focused on making progress for Node.js, not for progress’s sake, but for the betterment of the software project and the community we serve.

The goal of the team, especially that of the project lead, is to drive consensus and ensure accountability.

This is followed by a list that indicates how API changes will be handled in the future. Also, there is news about Node 0.12:

Finally, we are very close to releasing v0.12, there’s only one major patch we’re waiting to land. Once that’s done we’ll be releasing v0.11.15 as a release candidate.

StrongLoop’s blog has a related post about their position on a major Node fork called io.js:

As it has been widely reported, last week a fork of Node went live called io.js. Io.js represents a technical exploration by key developers in the Node core community with the intent to accelerate the release of recent technical innovations, many of which were developed by StrongLoop developers.

At StrongLoop, we’ve always participated in leadership, advisory and technical efforts in the Node ecosystem when appropriate and will continue to do so. We actively play a role in the Node Advisory Board established by Joyent in October 2014.

Although this sounds like StrongLoop is endorsing Node for now, the author indicates that StrongLoop remains open to changes in the future:

We will continue to recommend the version that currently has the best community support, is most compatible with the tools and frameworks we develop and that we can support for our customers. Of course, our preference over time is to support a version that satisfies these requirements and adheres to an open governance model.

There’s an article on Wired that quotes Mikeal Rogers citing Joyent’s control as a reason for the fork:

“We don’t want to have just one person who’s appointed by a company making decisions,” says Mikeal Rogers, a Node community organizer involved in the fork. “We want contributors to have more control, to seek consensus.”

Of course other contributing factors must be the perceived slow progress of the 0.12 release. It’s possible that io.js will exist as a novel fork that influences mainstream Node, or it could be like Chrome vs. previous less popular WebKit browsers. My advice is to follow both and avoid judging either too soon.

Tweene, JSON Forms

04 Dec 2014 | By Alex Young | Comments | Tags libraries animation json forms


Tweene (GitHub: SkidX/tweene, License: Artistic License 2.0, npm: tweene, Bower: tweene) by Federico Orrù is an API that wraps around popular animation libraries so you can switch implementation more easily. Rather than having to worry about whether you need to use translateX or just x, you can use Tweene’s API instead.

These are the supported libraries right now:

To create animations, you have to make tween instances using Tweene, and then call methods that set the duration and easing. It actually has several API styles based on GASP, jQuery, and Velocity, but I prefer the fluent API:

  .to({ opacity: 0, left: '+=50px' })
  .on('complete', completeCallback)

The documentation for Tweene is detailed, and there are some examples on CodePen.

jQuery JSON HTML Forms

Cezary Wojtkowski sent in jquery-html-json-forms, a project that aims to support the W3C HTML JSON form submission specification:

This specification defines a new form encoding algorithm that enables the transmission of form data as JSON. Instead of capturing form data as essentially an array of key-value pairs which is the bread and butter of existing form encodings, it relies on a simple name attribute syntax that makes it possible to capture rich data structures as JSON directly.

This basically means you can use an enctype attribute of application/json in forms. This makes it a lot easier to create forms that send data to JSON APIs, rather than using the standard form encoding.

Cezary’s project allows you to use enctype='application/json' and then get JSON out with $(formElement).JSONencode(). You can also enable and disable the plugin.

The HTML JSON form specification is new to me, but it seems really cool for those of us who create lots of JSON APIs.

Node Roundup: Mailman, trayballoon, unembed

03 Dec 2014 | By Alex Young | Comments | Tags node libraries modules email windows scraping


Mailman (GitHub: vdemedes/mailman, License: MIT, npm: mailman) by Vadim Demedes is a module for sending emails that supports generators. It uses nodemailer for sending email, and consolidate.js for templates, which means it supports lots of different template languages.

Generators are used for sending emails, so you can do this:

var mail = new UserMailer({ to: '' }).welcome();
yield mail.deliver();

Mailman expects a specific directory layout for views, but the added level of structure might help if you’ve got a big mess of email-related code in your current projects.



trayballoon (GitHub: sindresorhus/trayballoon, License: MIT, npm: trayballoon) by Sindre Sorhus is a module for showing system tray balloons in Windows. You can set the text and image to display, and a callback that will run when the balloon disappears:

  text: 'Unicorns and rainbows'
  icon: 'ponies.ico',
  timeout: 20000
}, function() {
  console.log('Trayballoon disappeared');

It also has a command-line tool which you could use to display notifications when things like tests fail. trayballoon works by bundling an executable called nircmdc.exe which is called with child_process.spawn.


Given some “embed code” for sites like YouTube and Vimeo, unembed (GitHub: colearnr/unembed, License: MIT, npm: unembed) by Prabhu Subramanian will extract the markup and produce a JSON representation. This might be useful if you’re scraping sites that use embed codes, like blogs and forums.

I’ve never thought of applying the tiny modules philosophy to scraping, but it seems like a great way of sharing all of those hacks we use to extract data in a more structured way.

Why You Should Donate to Mozilla

02 Dec 2014 | By Alex Young | Comments | Tags community mozilla

Firefox donations

Recently Firefox prompted me to donate to Mozilla. The ad appeared on the Firefox Start Page, but you might not always see it – sometimes there’s a message that reads “Let the world know you #ChooseIndependent with Firefox.” I switch between browsers for testing quite a lot, so I’m not particularly tied to one browser. However, that day I’d been using the latest Firefox and the Firefox Developer Edition, so I was in a good mood about Mozilla and decided to donate a few dollars.

I happen to think that you should donate as well, and here’s why. The Mozilla Foundation has been involved with some projects that have been immensely useful and powerful: Firefox, PDF.js (Mozilla Labs), asm.js, and Rust spring to mind. Take a look at the Mozilla Research Projects list for more.

Something that JavaScript developers can’t live without is the Mozilla Developer Network documentation. I almost felt like I was donating to support that site alone!

Like you I also use Chrome, and I actually like Google’s email indexing and Google Now – the way it shows delivery information for recent purchases is awesome. So I’m not pro-Firefox due to any privacy issues. And Safari is totally gorgeous on Yosemite. It definitely feels like Firefox’s competition is strong, and the mainstream technology press is down on Firefox. The last few releases have felt as fast as Chrome though, and the UI is evolving to something clean and minimalist that I like.

I think Mozilla does a lot for us JavaScript developers. If you’d like to donate, go to There’s also a FAQ about donations. You can now even donate bitcoin!

JavaScript Developer Survey 2014

01 Dec 2014 | By Alex Young | Comments | Tags community surveys

Here is the JavaScript Developer Survey for 2014! You have two weeks from now to complete the survey (the 15th of December).

I asked for help with the questions last year, and collected pull requests and issues to improve the survey. You can view the survey repository at alexyoung/dailyjs-survey. Many thanks to everyone who has helped so far.

Please fill out the survey and share it with your fellow JavaScript programmers! I make sure the data is open so it’s not just used for planning DailyJS content, you can use it as well.

Here’s the survey link again: JavaScript Developer Survey for 2014

The survey is now closed.

Mermaid: Like Markdown for Diagrams

28 Nov 2014 | By Alex Young | Comments | Tags svg libraries diagrams


When I work on books my editor always seems to push for more diagrams. Diagrams are useful, but drawing tools are a chore to use. When I get really stuck I resort to pen and paper or ASCII art. Writing suffers from the same issue: people love playing with writing tools and fonts before realising writing in Markdown or something similar is far more productive.

That’s why I thought Mermaid (GitHub: knsv/mermaid, License: MIT, Bower: mermaid) sounded cool:

Generation of diagrams and flowcharts from text in a similar manner as markdown.

Ever wanted to simplify documentation and avoid heavy tools like Visio when explaining your code?

This is why mermaid was born, a simple markdown-like script language for generating charts from text via javascript.

Rather than playing with stroke styles and colours, fonts, and other distractions, you can focus on the meaning the diagram is trying to encapsulate. Mermaid does allow you to include styles so you can change fill colours and strokes, but the text-based syntax might be easier to work with than GUI drawing tools under some circumstances.

I noticed Mermaid has two Jison files, which seems like a sensible way to parse the diagram syntax. For example, flow.jison is used to generate the parser that parses text graph definitions.

d3 is used for drawing, so you should be able to use Mermaid anywhere you use d3. It comes with a Gulpfile for generating optimised builds, and there are some Karma tests as well.

Material Design's Delightful Details with SVG Morpheus

27 Nov 2014 | By Alex Young | Comments | Tags animation svg libraries


SVG Morpheus (GitHub: alexk111/SVG-Morpheus, License: MIT, Bower: svg-morpheus) by Alex Kaul is a library for morphing between SVG icons. It implements the delightful details transition, as described by Google’s material design documentation:

The most basic use of animation is in transitions, but an app can truly delight a user when animation is used in ways beyond the obvious. A menu icon that becomes an arrow or playback controls that smoothly change from one to the other serve dual functions: to inform the user and to imbue your app with a moment of wonder and a sense of superb craftsmanship. Users do notice such small details.

You might have noticed this in Android recently: the first-party Android apps now have a nice transition for the back icon. This is visible in the Play Store app, for example.

Alex’s library allows you to do this with SVG icons, so you can employ the same effects in your web apps. All you need to do is add an SVG icon set to a document, then instantiate SVGMorpheus:

var myIcons = new SVGMorpheus('#myIconSet', options, callback);'icon1');

The options include easing and duration, so you get some control over the transition.

The project’s documentation has more details on the API and the expected markup structure.

PowerArray, Atomus

26 Nov 2014 | By Alex Young | Comments | Tags array testing libraries modules


PowerArray (GitHub: techfort/PowerArray, License: BSD) by Joe Minichino is a small library that attempts to replace native Array methods with faster ones. You can use PowerArray.prototype.forEach to iterate over values using a simple for loop, which is known to be faster than Array.prototype.forEach. However, it also includes PowerArray.prototype.binarySearch which performs a binary search on the array.

Thanks to Oliver Caldwell’s post for a quick version of the algorithm. Also note the contribution of Yehonatan and other authors of comments to the post which helped to optimise the implementation of binary search further.

Oliver wrote this about the binary search algorithm:

A binary search searches by splitting your array into smaller and smaller chunks until it finds your desired value. Unlike the normal indexOf which searches from left to right in a simple iteration. The binary search Wikipedia article explains it best (as always). There are a couple of downsides; It will be slower with smaller data sets (this needs proving) and the array you are searching needs to be sorted.

To use the binary search you’ll need to sort the array first, and there’s PowerArray.prototype.numericSort which just uses Array.prototype.sort with return < ? -1 : 1.

The project includes some benchmarks so you can try it out for yourself.


Everytime I use a Node/DOM testing library my tests seem to suffer from bitrot and stop working after a few months. So I was glad to see a new one by Krasimir Tsonev called Atomus (GitHub: krasimir/atomus, License: MIT, npm: atomus). It’s based on jsdom, so you get a window object and browser instance that lets you trigger events like clicked and blurred.

The following snippet is taken from the bundled AngularJS test:

var b = atomus()
.html('<html><body><div ng-controller="Controller"><register-form></register-form></div></body></html>')
.external(__dirname + '/data/angular.js')
.external(__dirname + '/data/angular.register-form.js')
.ready(function(errors, window) {
  if (errors !== null) console.log(errors);

  var Controller = function($scope) {
    var runTests = function() {

      var register = b.$('#register-button');
      var message = b.$('#message');
      var username = b.$('#username');
      var password = b.$('#password');


      assert.equal(message.text(), 'Missing username.');

The b.clicked(register) line causes the #register-button element to be clicked, and then there are some standard Node assert calls to ensure the document was updated as expected.

I’ve used other libraries like this, including Zombie.js. They all work in a slightly different way – Zombie.js also uses jsdom but some use PhantomJS or drive browsers with Selenium. It’s worth trying a few out to see what works for your project.

Paperclip.js, bem-react

25 Nov 2014 | By Alex Young | Comments | Tags templates reactive react


Paperclip (GitHub: mojo-js/paperclip.js, License: MIT, npm: paperclip) by Craig Condon is a template engine that’s a bit like React, except it translates HTML templates into JavaScript document fragments rather than using a virtual DOM. The template is then cloned when it’s used, and requestAnimationFrame is used to prevent unnecessary DOM operations.

Craig provided some examples so you can see how it compares to other projects:

Paperclip has been used for two years in production at ClassDojo, so it sounds battle tested. It has unit tests that run in browsers and Node, and you can also use the module itself in Node.


bem-react (GitHub: dfilatov/bem-react, License: MIT, Bower: bem-react, npm: bem-react) is a module for React that provides features to support the BEM methodology which was developed by Yandex.

BEM is a methodology of web projects development, that allows you to divide an interface into logically independent blocks. At the same time BEM contains specific tools for the typical web developers’ tasks automatization. And finally BEM gives us opportunity to create libraries of web-components for fast and efficient web-development.

With this module, you can use “bemjson” in templates instead of jsx or JavaScript, and manipulate CSS classes based on BEM.

I noticed there’s a demo app in bem-react/example that highlights the bemjson special fields, component use, and component composition.

Define.js, Combokeys

24 Nov 2014 | By Alex Young | Comments | Tags amd modules keyboard


DefineJS (GitHub: fixjs/define.js, License: MIT, npm: definejs) by Mehran Hatami is a new module loader. It implements the AMD pattern and also supports Promised Modules, and other new nonstandard related module techniques.

You can specify the module’s global name by including a global attribute on the script tag:

<script global="definejs" src="define.js"></script>

Now you can declare a module with definejs.define() and load dependencies with definejs.require. Promised modules are implemented by returning new Promise when declaring a dependency.

The author has included tests written with the Karma test runner, so you can run the tests against a real browser.


Shahar Or sent in a keyboard shortcut library called Combokeys (GitHub: mightyiam/combokeys, License: Apache 2.0), a fork of the popular Mousetrap project.

It has some cool changes: it’s been refactored to use CommonJS, and it doesn’t automatically listen on document. You can now specify which element it listens on for keyboard shortcuts. That was actually one thing that prevented me from using Mousetrap in a project.

txtjs, Useuses

21 Nov 2014 | By Alex Young | Comments | Tags text typesetting


Ted Patrick sent in txtjs (GitHub: diverted247/txtjs, License: BSD), a typesetting engine. It provides font and glyph rendering that is indepenent of the OS and browser by using SVGPath on a canvas element.

The documentation has lots of examples so you can see how it handles things like character styling with multiple fonts and alignment. The project comes with a warning that says txtjs should be used for “creative applications” where the layout requirements exceed the capabilities of the DOM. I imagine it could be useful in a scenario where tight control is required for graphic design projects.

txtjs is part of CreateJS, an open source set of libraries including EaselJS and TweenJS.


Useuses (GitHub: SpoonX/useuses, License: BSD-2-Clause, npm: useuses) by Wesley Overdijk is a library for handling “soft” dependencies. Given a JavaScript file, you can express the dependencies with @uses ./my-dependency.js in a comment.

Once you’ve defined dependencies you can create builds with the command-line tool, like this:

useuses -i example/main.js -o example/dist/built.js -w

There’s also a Node API, so you could hook it into a Grunt or Gulp. Wesley had created an earlier version that was for Grunt, but this is a rewritten, more generic version. He’s written a blog post about JavaScript dependency management that describes the module in more details.

Parrot, Flush Timeouts

20 Nov 2014 | By Alex Young | Comments | Tags timers api libraries modules


Parrot (GitHub: sailorjs/parrotjs, License: MIT, Bower: parrotjs) by Kiko Beats is a library for wrapping API calls to your server. You can register different environments, which makes it easy to switch between development and production. You can also register URLs with different protocols, so it’s possible to make WebSocket or Ajax requests.

It has a fluent API, so you can chain calls. If you wanted to register your production and development servers, then you’d call endpoint.add:

  .add(name: 'development', url: 'http://localhost:3000')
  .add(name: 'production', url: '')

Specific API URLs can be added as well:

  .add(name: 'signup', path: 'user', method: 'post')
  .add(name: 'login', path: 'user/login', method: 'post');

Making an Ajax request to the signup route would just be parrot.ajax('signup', function(err, res) {.

This seems preferable to some client-side HTTP APIs. The author intended it to be used with Sails.js, but you could use it with other frameworks as well.


I’ve noticed a few libraries recently that aim to improve the JavaScript timer API. Alex Lawrence sent in flush-timeout (GitHub: efacilitation/flush-timeouts, License: MIT, Bower: flush-timeouts, npm: flush-timeouts), a module for overriding setTimeout.

Here’s a quick example:


var i = 0;

function demo() {
  console.log('i:', i);

setTimeout(demo, 500);
setTimeout(demo, 1000);
setTimeout(demo, 1500);



This will cause demo to immediately run three times, and then print Done. If you removed global.flushTimeouts then it would execute based on the delays passed to setTimeout.

flush-timeouts might be useful when you’re trying to queue up tasks with setTimeout but have additional logic that determines if it’s safe to run all the tasks at once. Or perhaps you’ve got tests for code that depends on setTimeout and don’t want to wait. The author has supplied tests and build scripts so you can pick it apart to see how it works.

Node Roundup: Taunus, Root Path, Mongorito

19 Nov 2014 | By Alex Young | Comments | Tags node libraries modules google frameworks



Taunus (GitHub: taunus/taunus, License: MIT, npm: taunus) by Nicolas Bevacqua is an MVC framework that offers full-stack progressive enhancement. It uses server-side rendering, and will also use the browser’s history API for routing if it’s available.

Taunus can deal with view caching on your behalf, if you so desire, using asynchronous embedded database stores on the client-side. Turns out, there’s pretty good browser support for IndexedDB. Of course, IndexedDB will only be used if it’s available, and if it’s not then views won’t be cached in the client-side besides an in-memory store. The site won’t simply roll over and die, though.

It supports both Hapi and Express, so there’s some flexibility on the server. The server-side component is mainly dedicated to rendering.

There’s a getting started guide that shows how to set up a Taunus project and how to do basic things like adding a layout.

Root Path

Chris Morrell wrote a detailed response to a StackOverflow question about finding the root path for a Node project.

This resulted in the App Root Path Module (GitHub: inxilpro/node-app-root-path, License: MIT, npm: app-root-path), a small module that returns the path to the current module’s main directory. It returns a string, so you just have to do require('app-root-path') and pass the output to require.

Chris notes that the basic method for this is: path.resolve(__dirname).split('/node_modules')[0];, but there are edge cases where require.main.filename is used instead. This is all explained in the StackOverflow post.

Mongorito for ES6

If you’re using an ES6-based HTTP framework like Koa, then you might feel your database library could do with generator support as well. Fortunately, Vadim Demedes has rewritten his MongoDB module, Mongorito (GitHub: vdemedes/mongorito, License: MIT, npm: mongorito) to use ES6 generators.

Now you can load items like this:

var posts = yield Post.find();

Saving works the same way:

yield; // document created

var id = post.get('_id'); // _id automatically had been set after .save()

It’s based on the monk MongoDB module, and has good test coverage. I’ve never used a module like this in production, but I definitely like the idea of generator syntax for databases.

React Google Maps, TypeScript Tests

18 Nov 2014 | By Alex Young | Comments | Tags libraries testing typescript google-maps react

React Google Maps

React Google Maps

React Google Maps (GitHub: tomchentw/react-google-maps, License: MIT, Bower: react-google-maps, npm: react-google-maps) by Tom Chen is a React component for creating Google Maps. It has a mixin called GoogleMapsMixin that you can use to create React components for your own maps.

Tom has posted some examples that demonstrate things like click events and geolocation. These examples are based on Google’s developer documentation so you can see how React compares to the original Google APIs.

TypeScript Data Structures and Tests

Adrien Cadet sent in some TypeScript projects: Ludivine, a TypeScript data structure library, and Oscar, a test harness.

Ludivine has a wiki that describes each of the interfaces and classes. For example, LinkedList inherits from several interfaces to implement a linked version of IList.

Oscar has a getting started guide that explains how to create tests and test suites:

class MyTestClass extends UnitTestClass {
    firstTest() : void {
        // ... AAA stuff

    secondTest() : void {
        // ... another AAA stuff

This example is for testing a class called UnitTestClass. Each method that ends in Test will be run by the test suite runner.

Protractor-perf, lining.js

17 Nov 2014 | By Alex Young | Comments | Tags libraries testing performance angularjs


Protractor-perf (GitHub: axemclion/protractor-perf, License: MIT, npm: protractor-perf) by Parashuram can help you test for performance regressions while running Protractor AngularJS tests.

To use it, you can add performance-based assertions that are ignored by Protractor. These performance statements will only be used when tests are run with the protractor-perf command-line tool.

The available metrics are quite sophisticated – for a list of metrics take a look at the browser-perf metrics. Some examples are evaluateScript (the time spent evaluating the page’s scripts) and meanFrameTime (average time taken to render each frame).


Lining.js (GitHub: zmmbreeze/lining.js, License: MIT) by mzhou is a library for addressing lines within an element. To use it, add the data-lining attribute to an element, then add CSS to style each line. You can even apply styles to ranges with the data-from and data-to attributes.

There’s a JavaScript API which is event based. For example:

var poem = document.getElementById('poem');

poem.addEventListener('beforelining', function(e) {
  // prevent lining if you want
}, false);

var poemLining = lining(poem, {
  autoResize: true,
  from: 2,
  to: 3,
  lineClass: 'my-class'

The author suggests that it can be used for creative typography, and poems are used in the documentation which is a nice example. It also supports effects, so you can do things like animate sections of text using transitions.

Easier OAuth with Grant

14 Nov 2014 | By Alex Young | Comments | Tags oauth express middleware libraries modules node

OAuth always seems like an attractive alternative to rolling your own authentication, but it usually ends up being much harder than it looks. Grant (GitHub: simov/grant, License: MIT, npm: grant) by Simeon Velichkov aims to solve this. It’s built on Guardian.js, which was made by Nijiko Yonskai at Mashape (Nijiko has written quite a few Node modules that I’ve written about).

Grant is Express middleware that accepts options for the OAuth server. You can include things like the permissions you want to request, so for Facebook this might include friends_groups:

"facebook": {
  "key": "...",
  "secret": "...",
  // by default request publish permissions via /connect/facebook
  "scope": ["publish_actions", "publish_stream"],
  // set specific callback route on your server for this provider only
  "callback": "/facebook/callback"
  // custom override keys
  "groups": {
    // request only group permissions via /connect/facebook/groups
    "scope": ["user_groups", "friends_groups"]
  "pages": {
    // request only page permissions via /connect/facebook/pages
    "scope": ["manage_pages"],
    // additionally use specific callback route on your server for this override only
    "callback": "/pages/callback"

One nice touch is you can provide options for different environment, so it’s fairly easy to add settings for development or a CI server. Simeon has an app on Heroku that allows you to try out each provider with a friendly form:

I also noticed the same author has written a REST API wrapper called Purest. It embeds configuration details for dozens of providers, including Tumblr, Twitch, Google, and imgur.

To use it, you have to create an access token, then you can connect to a provider:

var Purest = require('purest');
var google = new Purest({ provider:'google' });

google.get('channels', {
  api: 'youtube',
  qs: {
    access_token: 'token',
    forUsername: 'user'
}, function (err, res, body) {});

This Google instance can be used to access YouTube’s API:

    forUsername: 'username'
  .request(function (err, res, body) {});

The documentation includes an excellent example that uses the request module’s streaming API to pipe files from one service to another.

Mithril: A Tiny MVC Framework

13 Nov 2014 | By Alex Young | Comments | Tags libraries modules frameworks mvc

Stephan Hoyer sent me an MVC framework called Mithril (GitHub: lhorie/mithril.js, License: MIT, npm: mithril) that’s getting a lot of positive feedback due to its small size and great documentation.

Mithril was created by Leo Horie, and it provides models, views, controllers, and the benefits that a virtual DOM brings. It also has a routing layer that is used for manipulating the browser’s URL.

What makes Mithril cool is the choices Leo has made: many MVC frameworks provide features that I don’t need, but I always find I want routing, data syncing features, and something like React’s virtual DOM.

There’s a short sample on Mithril’s homepage that shows most of these features:

var app = {};

app.PageList = function() {
  return m.request({ method: 'GET', url: 'pages.json' });

app.controller = function() {
  var pages = app.PageList();
  return {
    pages: pages,
    rotate: function() {

app.view = function(ctrl) {
  return [
    ctrl.pages().map(function(page) {
      return m('a', { href: page.url }, page.title);
    m('button', { onclick: ctrl.rotate }, 'Rotate links')

m.module(document.getElementById('example'), app);

This example shows how to fetch data from a server and map it to the UI using a controller and a view. I like the way the app object is just a plain old object rather than a Mithril-specific construct, and the syntax for creating elements is succinct and easy to understand (m('button', ...)).

Mithril doesn’t provide two-way data-binding, but Leo has an example that shows you how to implement it:

// A data store
var name = m.prop('');

// binding the data store in a view
m('input', { oninput: m.withAttr('value', name), value: name() });

I took this from the m.request documentation which has loads of useful examples for working with web services.

Whether or not Mithril suits your requirements will depend on your project, but it has an excellent selection of features. There are testimonial tweets on the homepage where people are saying things about switching from AngularJS, which definitely grabbed my interest when I first saw the site.

Node Roundup: Eskimo, Serve-Me, Google BigQuery and Cloud Pub/Sub

12 Nov 2014 | By Alex Young | Comments | Tags node libraries modules google frameworks



Eskimo (GitHub: niftylettuce/eskimo, License: MIT, npm: eskimo) by niftylettuce is a framework for Node web applications. It has a command-line tool that is used to manage projects, known as igloos. You can add new models, views, and controllers, or create all three with mvc.

Once you’ve installed Eskimo with npm, you can generate a new app with eskimo create projectname. Projects use Express, the electrolyte dependency injection module, Redis, and MongoDB. You’ll need to run npm install from the freshly created project to get the dependencies required for running the tests.

The authors have put sensible commands in package.json for npm start and npm test, so it works like most Node web applications. It also has a Vagrant file, so you should be able to test out deploying your applications without too much hassle.

Initially the documentation made me think it was an alternative to Yeoman, but it’s actually an MVC web framework based on Express. The documentation and examples currently need expanding, but I found some cool tutorials on niftylettuce’s blog.


Serve-Me (GitHub: muit/serveMe, License: MIT, npm: serve-me) by Muitxer is a small web framework that’s a bit like a mix of a static server and Sinatra. You can quickly configure it serve static pages, then add server-side route handlers with ServeMe.Routes.add('name', fn). The function has to return a string, which is why it’s more like Sinatra than Express.

The reason I liked Serve-Me is it has no dependencies – the author has used Node’s core modules for everything. The source is quite short, so you might find it interesting if you’re learning Node’s core modules.

Google Cloud Platform Updates

Google’s Cloud Platform Node module now has support for BigQuery and Cloud Pub/Sub. I read about this on Jonathan Beri’s Google+ account:

gcloud-node, the Google Cloud Client Library for Node.js, has added support for BigQuery and Cloud Pub/Sub. These Cloud APIs join Cloud Datastore and Cloud Storage. Grab it with ‘npm install –save gcloud’ or check out the source on GitHub.

The module is available at GoogleCloudPlatform/gcloud-node on GitHub. There’s a full TodoMVC example that demonstrates some of the module’s features.