ngKookies, preCode.js

29 Dec 2014 | By Alex Young | Comments | Tags cookies angularjs html dm


ngKookies (GitHub: voronianski/ngKookies, License: MIT, npm: ngkookies) by Dmitri Voronianski is a replacement for the Angular $cookieStore provider. It’s a port of jquery-cookie that helps work around angular.js issue 950.

After loading it, you can set cookies with $kookies.set('name', 'value') and read them with $kookies.get. You can also delete cookies with $kookies.remove.

Each method accepts an options object that can include the path and expires arguments. You can also store JSON objects as cookies with $kookiesProvider.config.json = true.


Have you ever written a blog engine or CMS that has to display source code? If so you’ve probably run into the issue where human-readable HTML doesn’t work well with pre elements if initial indentation is included.

preCode.js (License: MIT) Leon Sorokin is a small script that finds <pre><code> blocks and strips the leading and proceeding whitespace, so syntax highlighters should be able to display code properly.

It’s written using the standard DOM API, so it shouldn’t need any dependencies. It’ll also fix whitespace in textarea as well.

Dynamic-json-resume, JSnoX

26 Dec 2014 | By Alex Young | Comments | Tags react json careers


I don’t know about you, but I hate putting together my résumé. I start to focus too much on the presentation even though you’re meant to keep it simple. Dynamic-json-resume (GitHub: jrm2k6/dynamic-json-resume, License: MIT, npm: json-resume-dynamic) by Jeremy Dagorn is a module for generating résumés from a simple JSON format. You can output PDFs, and use it with a Node application.

Because your CV is now represented by a structured data format, you can reuse it in other places. For example, your personal website could render it in a sidebar.

James Long’s article, Removing User Interface Complexity, or Why React is Awesome, inspired the project. React seems like the perfect way to manipulate and render your JSON CV.


What do you do if you like React but dislike JSX? Shawn Price sent in his coworker’s project, JSnoX (GitHub: af/JSnoX, License: MIT, npm: jsnox), which provides a simple React markup API that works in pure JavaScript:

var d = require('jsnox')(React)
var LoginForm = React.createClass({
  submitLogin: function() { ... },

  render: function() {
    return d('form[method=POST]', { onSubmit: this.submitLogin }, [
      d('h1.form-header', 'Login'),
      d('input:email[name=email]', { placeholder: 'Email' }),
      d('input:password[name=pass]', { placeholder: 'Password' }),
      d(MyOtherComponent, { myProp: 'foo' }),
      d('button:submit', 'Login')

This API sidesteps the issue of JavaScript’s lack of multiline string handling for embedded templates, while not requiring too much fiddly syntax for handling DOM attributes.

Holiday Hacking: Apps

25 Dec 2014 | By Alex Young | Comments | Tags apps tablets festive

What do you do when you leave your computer/laptop at home while you visit family for the holidays? I always do this, thinking that it’ll be better to spend some quality time with the family, but there are moments where people are doing their own thing and I wish I had a laptop to play with some code.

These days of course many of us tote around tablets or large phones, so there is some potential for hacking or at least learning about new programming techniques. One of my favourite apps is actually Vim, which you can get for iOS and Android:

To the uninitiated, Vim for a touchscreen sounds horrible, but it’s actually pretty good – because it’s modal you can enter Command-line mode with : and leave with the escape key easily enough. If you’re an experienced Vim user then it can be revealing to think about the mnemonics for commands rather than relying on muscle memory.

I also found that the big programming video services have iOS and Android apps, so you can study a new programming language, framework, or library:

I’ve actually used the Pluralsight app on Android during my commute to help me learn enough C# to implement the Windows portion of a Node/Windows/iOS/Mac application I work on professionally.

Because tablet operating systems support browsers, then there are a lot of apps that wrap the built-in JavaScript interpreter to allow you to practice writing JavaScript. For example:

And you can even write Node on iOS with Node - JavaScript Interpreter. There are manuals for Node on the Play Store as well. Or you can get a more broad manual management app like Dash. I found Dash useful for looking up Mozilla’s JavaScript documentation, and Node’s, when I was working offline on my Node book.

Apple and Google’s book stores also sell many technical books from the popular computer science book publishers, so you should be able to find something to do while your parents argue and your partner is walking the dog, wrangling toddlers, or snoozing after too much turkey.

Node Roundup: 0.10.35, Prettiest, Artisan Validator

24 Dec 2014 | By Alex Young | Comments | Tags node modules libraries command-line validation

Node 0.10.35

Node 0.10.35 was released today, which has some changes to timers relating to the unref behaviour:

  • timers: don’t close interval timers when unrefd (Julien Gilli)
  • timers: don’t mutate unref list while iterating it (Julien Gilli)

This was released soon after 0.10.34, which updated v8, uv, zlib, and some core modules including child_process and crypto.


What if you want to prevent a command-line script from executing more than once? Prettiest (GitHub: punkave/prettiest, License: MIT, npm: prettiest) from P’unk Avenue LLC combines data storage and locking, and should work well for Node command-line scripts made with modules like ShellJS.

This is the simplest example – it will track how many times it has been run:

var data = require('prettiest')();

data.count = data.count || 0;
console.log('I have been run', data.count, ' times.');

I’ve often wanted to persist data in command-line scripts, but didn’t want to bother with sqlite or JSON file serialisation, so this seems ideal for such cases. And even if you want the locking behaviour, your scripts can still be asynchronous.

Artisan Validator

Connor Peet is on a quest to create a simple and well-documented data validator for Node. Artisan Validator (GitHub: MCProHosting/artisan-validator, License: MIT, npm: artisan-validator) allows you to define rules that get validated against objects, so you can easily hook it into a Node web application:

var validator = require('artisan-validator')();
var rules = {
  username: ['required', 'between: 4, 30', 'alphanumeric'],
  password: ['required', 'longer: 5'],
  acceptTOS: ['required', 'boolean: true']

validator.try(req.body, rules).then(function (result) {
  if (result.failed) {
    res.json(400, result.errors);
  } else {

You can add custom validators with validator.validators.add, but there are quite a few built-in rules that cover JavaScript types, and various string and date formats. The error messages can be localised as well.

Particle Paintings, AMD to CommonJS with Recast

23 Dec 2014 | By Alex Young | Comments | Tags animation graphics modules amd



Tadeu Zagallo sent in a Canvas experiment that uses typed arrays, optimised sorting algorithms, and inlining and bitwise operators to boost performance. The Particture demo allows you to use your webcam for the source image, and draws images with a cool trail effect.

The repository at tadeuzagallo/particture has the source, and it uses dat.gui for the controls.


Many readers seem to be searching for solutions to the module refactor problem, where older projects are refactored to use modern module systems. Dustan Kasten wanted to convert projects that use AMD to CommonJS, and he’s used Recast to do this, through the recast-to-cjs project that is published by his company (Skookum Digital Works).

Dustan has written an article that shows how to convert a project to CommonJS: Converting a project from AMD to CJS with Recast. The AST is traversed to find AMD definitions, and then converted into equivalent CommonJS dependencies.

It’s possible that Node developers may end up doing something like this if ES6 modules become the norm, although I suspect ES6’s export and import statements will need manual intervention to take advantage of import obj from lib.

Holiday Reading for JavaScript Programmers

22 Dec 2014 | By Alex Young | Comments | Tags books tutorials

Hemingway and JavaScript

If you’re lucky enough to be enjoying a festive holiday right now, then you’re probably starting to get bored of Christmas movies and long dark teatimes of the soul. Rather than knuckling down with the family to watch Elf for the umpteenth time, why not load up your favourite reading device with some programming books and articles?

Angus Croll sent in a copy of his book If Hemingway Wrote JavaScript (No Starch Press, $15.95), which makes comparisons between literary figures and programming styles. This book started as a blog post about Hemingway, and there are amusing posts on his blog, like Animals writing JavaScript. I thought it would be hard to stretch the original idea out into an entire book, but Angus uses the concept to explore the broader question of how we write and think about JavaScript:

JavaScript has plenty in common with natural language. It is at its most expressive when combining simple idioms in original ways; its syntax, which is limited yet flexible, promotes innovation without compromising readability. And, like natural language, it’s ready to write. Some of JavaScript’s more baroque cousins must be edited with an IDE (integrated development environment—a sort of Rube Goldberg machine for coding). JavaScript needs nothing more than a text file and an open mind.

The question of style in programming is usually approached with defensive trepidation, but the literary conceit allows Angus to present different stylistic ideas without judging them. For example, Virginia Woolf’s poetic stream of consciousness is recreated with a mix of long lines and flexible use of semicolons:

If the semicolon is the period of JavaScript, then the comma operator is its semicolon. Programmer Woolf loves the comma operator, and in her happy numbers solution, she uses it to excess. The result is a dreamy, melancholic form of JavaScript (is there any other?) made dreamier still by the heavy, almost dangerous level of n alliteration and some gorgeously expressive pairings. In To the Lighthouse, Woolf writes of night’s shadows: “They lengthen; they darken”; in her happy numbers solution we get the wistfully poetic numerals.shift(), numerals.length.

I commute across London everyday and read to pass the time. Over the years I’ve moved from pulp sci-fi to 20th century modernists and the classics, so this book is ideal for me. I’m not sure how many literary programmers there are, however, so this is definitely a novelty that I will cherish.

Other readers have also recently sent in some interesting resources that you might like to read over the holiday. Thai Pangsakulyanont’s JavaScript for Automation Cookbook contains examples for Apple’s new scripting system that allows you to control Yosemite applications with JavaScript. It includes iTunes, Safari, system events, and how to use CommonJS modules with Browserify, so you can actually make maintainable automation scripts.

Eugene Abrosimov sent in a big list of Backbone.js tutorials, articles, videos, and examples. There should be a few things on there to load up Instapaper/Pocket if you use Backbone.

And, just over a week ago I received the first print of my book, Node.js in Practice (Manning, $39.99). I wrote it with Marc Harter, and we’ve designed the book for intermediate to advanced Node developers. Our publisher, Manning, also publishes Node.js in Action (Manning, $35.99) which is well suited to new Node programmers.

Rantjs, Avatar, esformatter

19 Dec 2014 | By Alex Young | Comments | Tags text graphics atom plugins


Rantjs (GitHub: svenanders/Rantjs, License: ISC, npm: rantjs) by Sven Anders Robbestad is a library for procedurally generating text. It takes a formatted constructor and then generates suitable sentences:

var rantjs = require('rantjs');
var rant = new rantjs.SimpleRant;
var sentence = rant.rantConstructor('<firstname male> likes to <verb-transitive> <noun.plural> with <pron poss male> pet <noun-animal> on <timenoun dayofweek plural>.');

console.log(sentence); // 'Sean likes to chop parrots with his pet cat on Saturdays.'

There are a lot of supported tags, with subgroups, so you can generate a activity video or adv emotion. You can also add your own tags.

The author suggests that this might be useful for generating random text in games, but I think it might also work well for generating random admin area sample text in a blog or CMS, and for creating text to use in testing.


If you’re looking for a way to generate default avatars, then take a look at Avatar (GitHub: MatthewCallis/avatar, License: MIT, npm: avatar-initials) by Matthew Callis. It can show the user’s initials in a styled or unstyled avatar, or optionally fall back to a Gravatar instead.

To use it, just instantiate Avatar with the container element:

var avatar = new Avatar(document.getElementById('avatar'), {
  useGravatar: false,
  initials: 'MC'

/* or */

  useGravatar: false,
  initials: 'MC'


Sindre Sorhus sent in atom-esformatter (GitHub: indresorhus/atom-esformatter, License: MIT), an Atom editor package for formatting JavaScript with esformatter. Esformatter itself supports lots of options for formatting JavaScript, like the indentation characters, line breaks, and whitespace handling.

Sindre’s Atom package lets you run esformatter from the Command Palette by typing esformatter, and you can run it on a selection or the whole file.

Esformatter supports plugins, so you can change its behaviour by loading other Node modules. There’s a list of plugins and also a plugin wish list. Sindre notes that it can be used with Gulp and Grunt, which might be a good way of processing open source JavaScript according to your project’s style guide before you release it.

React Roundup: rc-calendar, D3 React Reusable Charts, tcomb-form

18 Dec 2014 | By Alex Young | Comments | Tags libraries react components


rc-calendar (GitHub: react-component/calendar, License: MIT) by yiminghe is a port of kissyteam/date-picker that allows you to render calendars with React.render(<Calendar />, container). It has props for locale, showing today, and the select/blur events, and it includes some examples and tests.

The supported locales are en-us and zh-cn, so you can actually display a Chinese calendar UI. It also supports aria and keyboard accessibility.

D3 React Reusable Charts


D3 React Reusable Charts (GitHub: jdarling/d3rrc, License: MIT, npm: d3rrc) by Jeremy Darling is a graph library that supports bar charts, pie charts, scatter charts, and time series. It allows you to use a LineChart element. This code is taken from the multi-line chart example:


React makes graphs quite clean by allowing you to mix the markup and JavaScript data. For more examples, take a look at the full d3rrc example list.


tcomb-form (GitHub: gcanti/tcomb-form, License: MIT) by Giulio Canti is a UI library for making forms. As we all know, making forms is web development drudgery, so anything to take the pain away is welcome. Giulio’s library is “domain driven”, which means it’s able to generate a form based on the domain model.

There’s a personal form example that shows the kind of form I’ve spent all too much time creating in the past. The source uses a kind of strongly typed model definition approach:

var t = require('tcomb-form');

var Gender = t.enums({
  M: 'Male',
  F: 'Female'

var Country = t.enums({
  US: 'United States',
  IT: 'Italy'

var Person = t.struct({
  fullName: t.Str,
  nickname: t.maybe(t.Str),
  gender: Gender,
  country: Country,
  tags: t.list(t.Str)

var Form = t.form.create(Person, {
  auto: 'labels',
  fields: {
    gender: {

You don’t have to use this to define the actual models in your application. With this library, it might be better to use a lightweight model/view model approach, so you’d treat the tcomb models as view models that define the behaviour specific to forms.

Node Roundup: watch-network, MailDev, node-notifier


If you use something like Docker or Vagrant and want to listen for file notifications over the network, then watch-network (GitHub: efacilitation/watch-network, License: MIT, npm: watch-network) by Johannes Becker might come in handy. It can be used with Gulp, so you could run Gulp tasks when a specific network notification comes in.

Here’s a basic example:

var watch = WatchNetWork({
  configs: [{
    patterns: 'lib/*.coffee',
    tasks: 'something:important',
    onLoad: true

watch.task('something:important', function(changedFiles) {
  // ..


Here’s the use-case that Johannes described:

Scenario: You use Vagrant/VirtualBox in your workflow to have services and configurations in an encapsulated environment. For developing purposes you now sync a local directory into the VM using vboxfs, nfs, rsync or similar. In your VM you want to use watcher facilities for developing-concerns, but for some reason triggering inotify over the network seems to be troublesome or unreliable.



If you’ve ever felt like handling emails in web applications is messy, and you don’t feel like your emails are as good as they could be, then you’re not alone! I always feel like emails are annoying to develop, so I thought MailDev (GitHub: djfarrelly/maildev, License: MIT, npm: maildev) looked interesting. This module helps you test your project’s generated emails during development with a responsive web interface. It has a Node API, and there’s even a REST API so you could integrate it with other services.

Emails are displayed with WebSockets, so you don’t have to keep refreshing, and it’ll show HTML, text, and attachments.

I currently send all the generated emails to a temporary directory, then open them up when I need to. MailDev seems like a much better solution.


Mikael Brevik sent in node-notifier (GitHub: mikaelbr/node-notifier, License: MIT, npm: node-notifier), in response to the recent mention of trayballoon. Node-notifier tries to smooth out the differences between each platform, so you can use notification features that are present on all platforms more easily. It also supports actions on notifications.

Mikael notes that it works with node-webkit, which is cool if you’re making Node desktop apps, and it supports the following notification systems:

  • Mac: Notification Center, Growl
  • Windows: Toasters, trayballoon
  • Linux: notify-osd

Here’s an example:

var notifier = require('node-notifier');
  'title': 'My notification',
  'message': 'Hello, there!'

JavaScript Developer Survey 2014: Results

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

The JavaScript Developer Survey has now closed. As always the results are available to the community for further analysis:

Browser-based developers are still the majority.

97% of readers write client-side code, while 56% said they write server-side code. Last year server-side development was at 28%. I’d like to think that the interest and adoption of technologies like Node will contribute to the direction of ECMAScript, because some proposals seem to go against the strides that have already been made in the Node community (the module system, for example).

The DailyJS readership is very experienced (27% said 5-10 years), so perhaps I should do more to cover advanced topics?

78% of readers said they don’t use a language that compiles to JavaScript – both this year and last year. I’ve written more about technologies like TypeScript this year, partly because I respect that project in particular, but Dart is also compelling. However, Dart was one of the least popular compile-to languages (1%). TypeScript is more popular (5%), but CoffeeScript is still the most popular (16%).

It turns out most people like semi-colons. I think they’re going to stick around in the JavaScript community because they’re used in so many other languages, but it’s always possible that styles will change over time. According to the survey results, the stylistic choices are actually similar to some of the more popular JavaScript style guides.

ES6 features are getting popular: 24% said they use ES6. I suspect that more people actually do use them, because 'use strict' is something I’ve seen in lots of JavaScript best practice articles. Also, Node frameworks like Koa use cool features like generators quite well, so I think this figure will grow over the next year.

Testing: 29% said they write tests. I was interested to see that PhantomJS is a very popular test environment (38%). I’ve mentioned many times on DailyJS that I struggle a little bit when it comes to this type of testing, because the tests seem to become brittle and break over time. However, the number of people that use PhantomJS is close to Node, so presumably most people have found a way to make it work well enough.

Jasmine and Mocha are still the most popular test frameworks, and Karma is gaining on them now as well.

61% use JSHint for static analysis. That’s 2608 people, which surprised me because I don’t often use a linter. I think it might be down to people verifying open source client-side JavaScript, but it would be interesting to find out exactly why people are motivated to lint JavaScript.

Gulp (35%) is already almost as popular as Grunt (47%). It’s amazing how quickly Gulp has been adopted, although I’ve found I can understand Gulp more readily than Grunt scripts.

When it comes to client-side dependencies, CommonJS with Browserify is at 20%, with plain old files at 30%. I think that’s interesting because Browserify is my preferred solution, but I often use plain old files because I’m working on a legacy project where Browserify is a luxury we don’t have time for.

AngularJS is strangely popular (49%). I’ve noticed that many in the JavaScript community regard React (16%) as the latest hot framework and see it as an alternative to Angular, but they do different things so I prefer to use the appropriate tool for each project. Meteor is a lot less popular than the hype had me believe (6%), but it’s possible that DailyJS readers don’t like Meteor. It’s worth noting that Backbone.js is popular, with 31%.

SublimeText won the editor wars, although a fair few readers use IDEs like IntelliJ and Visual Studio.

The most popular minimum IE is IE 9. I find that’s interesting because I still get asked to support 8 for corporate networks that can’t seem to untangle themselves from web-based legacy software (do any readers use ADP for example?)

Here are the top “other” programming languages:

  1. PHP
  2. Java
  3. C#/.NET

I still find it strange that PHP is so popular, although it’s 6 on the TIOBE index, and this is primarily a web development blog after all.

Thanks to everyone who took part in the survey! If you’d like me to run another rather than waiting for a whole year, then get in touch with your ideas.

Survey Closed, Predicates, Shackles

15 Dec 2014 | By Alex Young | Comments | Tags surveys modules libraries assert

Survey Closed

The JavaScript Developer Survey 2014 has now closed. I received some updates for the survey to the GitHub repository, so you should see those the next time I run it. Thanks for the contributions!

I’ll work on writing up the results and post again when they’re ready.


Predicates (GitHub: wookieb/predicates, License: MIT, npm: predicates) by Łukasz Kużyński is a set of tools for type checking and assertions. For example:

var is = require('predicates');

is.string(1); // false
is.string('test'); // true
is.undefinedOr(is.string, undefined); // true

Assertions look like this:

var assertName = createAssert(is.string, 'Name must be a string');

var Person = function(name, surname, age) {

new Person('Tom', 'Welling', 33); // OK!

The Predicates API guide has a list of each available method, and there’s also an interesting API design document that provides some background to the project.


Shackles (GitHub: metaraine/shackles, License: ISC, npm: shackles) by Raine Lourie is a module for adding chaining to another library. Imagine if Underscore didn’t support chaining. You could use Shackles to create a fluent API, like this:

var chain = shackles(_);

var result = chain([1,2,3])
  .map(function (x) { return x*x })
  .filter(function (x) { return x > 2 })
  .value(); // [4,9]

You can insert values at any point in the chain with tap, and there’s also a log method that prints values with console. Logging can be overridden as well.

AsyncTask, DefineJS ES6 Features

12 Dec 2014 | By Alex Young | Comments | Tags es6 generators webworkers


Web workers are great, but who wants to go to the trouble of creating extra files just to run some code in parallel? AsyncTask (GitHub: gorillatron/async-task, License: MIT, npm: async-task) by Jørn Andre Tangen is a more generic web worker constructor that lets you define background tasks purely with JavaScript:

var task = new AsyncTask({
  doInBackground: function(a, b) {
    return a + b

task.execute(1, 2)
  .then(function(result) {
    result === 3

It has a fluent API, and has Karma/Mocha unit tests as well.

DefineJS: ES6 Generator Syntax

Recently I wrote about Mehran Hatami’s define.js project, which is a lightweight AMD implementation. It has just been updated to support ES6 generators for loading modules, which means you can do this:

var module = yield require('module');

It’s still asynchronous, but it looks synchronous. I think this is a really cool use of generators, and apparently several people asked Mehran to implement this so it seems like there’s demand for it.

New npm Site, Amelie Music Visualiser

11 Dec 2014 | By Alex Young | Comments | Tags npm audio

New npm Site


npm has a new website! There’s an announcement blog post that explains what has changed, and what’s next, including this information about private modules:

Our next immediate goal is to support private npm modules on the website. This will allow individuals and teams to publish, install, and view private code using all the familiar npm mechanisms.

The website is now responsive, so it’ll look better on mobile devices. I found it looked nicer when I tiled my browser windows, which I often like to do when juggling material for DailyJS posts.

Amelie Music Visualiser


Adam Timberlake sent in a music visualisation experiment made with React, D3, and SVG: (GitHub: Wildhoney/Amelie, Bower: amelie). It uses AnalyserNode to get frequency data from the audio file:

The AnalyserNode interface represents a node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations.

Because the AnalyserNode API does the more complicated FFT stuff, the source is actually fairly easy to understand. Take a look at Amelie.jsx to see how the colours are generated and then plotted using D3.js.

JavaScript for Kids, Eloquent JavaScript

10 Dec 2014 | By Alex Young | Comments | Tags books

JavaScript for Kids by Nick Morgan introduces programming by using JavaScript, HTML, and lots of games. It’s tailored for younger readers, but it’s more for teenagers than under 10s. You might be able to use it as a guide to teach someone under 10 though. Here’s a quote from the section on syntax:

Our program includes lots of symbols, including parentheses (), semicolons ;, curly brackets {}, plus signs +, and a few words that might seem mysterious at first (like var and console.log). These are all part of JavaScript’s syntax—that is, JavaScript’s rules for how to combine symbols and words to create working programs.

When you’re learning a new programming language, one of the trickiest parts is getting used to the rules for how to write different kinds of instructions to the computer. When you’re first starting out, it’s easy to forget when to include parentheses, or to mix up the order in which you need to include certain values. But as you practice, you’ll start to get the hang of it.

I remember when I was a kid, learning programming for the first time, and I was worried about learning the “best” programming language. I like the fact Nick suggests that you’re likely to learn other programming languages and points out the similarities.

The examples use HTML and JavaScript, so all you really need is a browser and editor. The earliest examples use the console debugger, so I can imagine kids turning up at school, opening the developer tools in a browser and impressing their friends with their newfound hacker skills.

The publisher (no starch press) has a discount for this book (today only): just enter LILCODER during checkout to get 40% off. The standard price for the e-book is $27.95.

No starch press also sent me the second edition of Eloquent JavaScript by Marijn Haverbeke. This book also introduces programming, so beginners may find it useful:

Besides explaining JavaScript, I also will introduce the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are typically simple and clear. But programs built on top of these rules tend to become complex enough to introduce their own rules and complexity. You’re building your own maze, in a way, and you might just get lost in it.

However, at over 400 pages this edition includes a lot of content, including a chapter on performance, and a full-stack worked example in the Skill-Sharing Website chapter. The book covers client-side JavaScript, including some fun Canvas drawing examples, and Node.

Both of these books complement each other, and JavaScript for Kids may work well as the source material for something like Code Club.

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!