Google's Cloud Platform Library

10 Oct 2014 | By Alex Young | Comments | Tags google modules libraries

JJ Geewax announced the gcloud node (GitHub: GoogleCloudPlatform / gcloud-node, License: Apache 2.0, npm: gcloud) client library for Node. It allows you to access things like the Google Cloud Datastore database and Cloud Storage. You should be able to use it with Google Compute Engine or a Google Developer’s service account.

I had a look at this module and there are a few interesting things to note:

  • They use Mocha for tests, and there are lots of tests
  • The API and code formatting are in line with the Node community
  • The documentation looks modern and uses AngularJS (it’s generated with dox)

There’s a blog post about the project here: gcloud-node - a Google Cloud Platform Client Library for Node.js which demonstrates the API.

With a little bit of configuration, getting data from the API is as simple as dataset.get:

dataset.get(dataset.key(['Product', 'Computer']), function(err, entity) {
  console.log(err || entity);

With cool Node libraries like this, AngularJS, and MEAN on Google Compute Engine, I’m just waiting for someone at Google to bring a first-party Node IDE to my Chromebook!

Angular Chart, pragmatic-angular, ng-boilerplate-app

09 Oct 2014 | By Alex Young | Comments | Tags modules libraries angularjs graphs boilerplates

Angular Chart

Angular Chart

Angular Chart (GitHub: jtblin / angular-chart.js, License: BSD) by Jerome Touffe-Blin is a set of native AngularJS directives for Chart.js.

It works by allowing you to define data and labels in the Angular controller, so your markup basically just has to define what kind of chart to use. The advantage of this is it’s reactive, so it works really well if your data changes.


What if you’ve got lots of jQuery plugins but don’t have AngularJS event bindings? Lars Gersmann has written pragmatic-angular (GitHub: lgersman / pragmatic-angular, License: GPL/MIT), which allows you to declaratively bind jQuery plugins to elements in markup.

If the plugin has custom events then you can handle them with ng-on. This works with both native and custom events, so you could use ng-on="{ click : onClick}" to add a click handler.

Even though the plugin is technically very simple, Lars has provided some useful real world examples in the readme so you can see how it’s used.


I’m a big fan of writing AngulaJS/Knockout/etc. applications with Browserify, so I thought Mattia Franchetto’s ng-boilerplate-app (GitHub: mtfranchetto / ng-boilerplate-app, License: MIT) was pretty cool. It’s a boilerplate for Angular/Bootstrap applications, and includes file watching, live reloading, CSS vendor prefixing, code coverage, and more.

Node Roundup: Nightmare, Prototypes, node-libpq and node-pg-native

08 Oct 2014 | By Alex Young | Comments | Tags modules libraries node npm phantom postgres



By far the most brittle and confusing part of testing is full stack integration testing. I’ve used lots of different approaches, whether they’re based on PhantomJS or Selenium, but they always cause me trouble.

One issue is often the API – PhantomJS itself has a strange API if you’re more used to Node development. That’s why I was excited to hear about Nightmare (GitHub: segmentio / nightmare, License: MIT, npm: nightmare), which aims to simplify Phantom’s API.

If you want to try it out be aware that you’ll need to install PhantomJS on your system. This can be done using Homebrew on a Mac, and there are packages for other platforms on the main site.

Nightmare has a chainable API that allows you to evaluate JavaScript on the target page’s DOM. If you’ve got a page with jQuery on it, for example, then you can access $ in the evaluate callback.

Here I’ve loaded a web app that starts a server (in app.js), then filled out a sign in form and submitted it. The code in the evaluate method will be executed on the page, so I can use jQuery to do DOM stuff.

var server = require('./app');
var Nightmare = require('nightmare');
new Nightmare()
  .type('input[name="email"]', '')
  .type('input[name="password"]', 'password')
  .evaluate(function() {
    return $('.sign-out').is(':visible');
  }, function(visible) {
    assert(visible, '.sign-out should be visible');
  .run(function() {

Naturally you can use this for the general chores you’d use Phantom for, but I think it might be quite cool for testing projects with complex client-side code.


Alex Fernández sent in prototypes (GitHub: alexfernandez / prototypes, License: MIT, npm: prototypes). This module modifies prototype objects, so use it with caution, but you might find some of the methods useful.

Here are some examples:

'hi.there'.substringFrom('.'); // 'there'

{ a: 1, b: 2 }.forEach(function(value, key) {
  console.log(key, value);

node-libpq and node-pg-native

node-libpq (GitHub: brianc / node-libpq, License: MIT, npm: libpq) by Brian M. Carlson is a set of native bindings to the PostgreSQL libpq C client library.

This module attempts to mirror as closely as possible the C API provided by libpq and provides the absolute minimum level of abstraction. It is intended to be extremely low level and allow you the same access as you would have to libpq directly from C, except in node.js! The obvious trade-off for being “close to the metal” is having to use a very “c style” API in JavaScript.

Brian is the author of the popular pg PostgreSQL library, and has also recently released node-pg-native. node-pg-native is a high performance PostgreSQL module that uses node-libpq.

Sean Levy sent in node-pg-native because he’s excited about the synchronous API:

var rows = client.querySync('SELECT NOW() AS the_date')
console.log(rows[0].the_date) //Tue Sep 16 2014 23:42:39 GMT-0400 (EDT)

It’s really that simple!

Definitive Guide to Generators, Golden Layout

07 Oct 2014 | By Alex Young | Comments | Tags libraries design layouts articles

Definitive Guide to Generators

Gajus Kuizinas read through many ES6 generator articles before he understood them properly. I admit I’ve had the same problem: beyond the basic API, how do you do things like delegate yield statements, or raise and handle errors? And even with a good understanding of the API it can be hard to know when to use generators.

This confusion resulted in Gajus writing a detailed article about generators. It has lots of examples, including a handy gif that illustrates the flow of execution in a debugger.

Gajus’ article covers pretty much everything I can think of, but even so I think it would be nice to see more practical examples to show you generators can improve real world code. I’ve been looking at how Koa projects use generators by searching for open source apps on GitHub, so that can be a useful way to see how people are using them.

Golden Layout

Golden Layout

If someone says “build me an admin area!” or “we need a dashboard!” I immediately reach for Bootstrap. But there are other options, and some may be a better fit depending on what you’re working on. Golden Layout is a new “layout manager” for web applications that supports resizable windows.

It reminds me a little bit of an X11 window manager, a concept that has been tried many times in web development but has always felt a little unnatural. The examples in Golden Layout feel fast and precise – there are no messy gradients or shadows. It may work well for projects that need to adapt to user generated data. This could be something like displaying tables or graphs, like an analytics tool or dashboard.

The examples include Highcharts, SlickGrid, and Angular. The tutorials expand on this further with RequireJS and more complex Angular projects.

This project is CC BY-NC 4.0, so you’ll need to license it for commercial use. It’s created and maintained by Hoxton One Ltd, a company based in London, and the source is on GitHub: hoxton-one / golden-layout.

RWDPerf, respimage

06 Oct 2014 | By Alex Young | Comments | Tags modules libraries responsive mobile


RWDPerf report

RWDPerf (GitHub: lafikl / RWDPerf, License: MIT, npm: rwdperf) by Khalid Lafi is a tool for analysing responsive pages. It calculates the page weight, so you can see what the download bloat is like.

It works using Chrome’s remote debugging API, so it should be more accurate than a DOM simulation. It accepts arguments on the command-line for configuring things like device scale factor, width, height, and user agent.

It also has an API, which is ideal for dropping it into a build script.


If RWDPerf indicates that your page has a lot of unused images, then you might want a better responsive image replacement library. Respimage (GitHub: aFarkas / respimage, License: MIT) by Alexander Farkas is a responsive image polyfill for picture and srcset.

Respimage works using the picture element or the srcset image attribute. The srcset implementation supports descriptors for width and density.

There’s also a JavaScript API, so you can also support dynamically generated content.

Slideshow, Unity and JavaScript

03 Oct 2014 | By Alex Young | Comments | Tags games slideshows node modules tutorials


What do you do when Apple and Microsoft do everything they can to pull us into their walled development environment gardens? One answer is to unify both environments using a sane Node API. Ralf S. Engelschall sent in Slideshow (GitHub: rse / slideshow, License: MPL, npm: slideshow), a module for remote controlling and monitoring presentation programs like PowerPoint and Keynote.

He also wrote slideshow-forecast, which is a cool CLI and GUI for monitoring slideshows:

The motivation for this is that for large presentations which have to be given in multiple variants for different timeslots it is very hard to determine the later presentation duration during preparation time. Instead of performing lots of different dry-runs after each preparation, this tool provides a duration prognosis already during preparation time.

The slideshow command-line program itself lets you drive an application with commands like boot, open file, and start. You can also goto a given slide and stop the presentation at the end.

Internally it uses Microsoft’s cscript or Apple’s osascript to communicate with the target application, so you don’t have to worry about strange AppleScript or COM incantations.

How to Make a 2D Space Shooter in Unity


The Unity game engine is hugely popular with game developers. Many of the indie games that I’ve enjoyed have been made with it, and if I had the time I’d love to make something with it. I was aware Unity supports C#, but I didn’t know it has a compiled JavaScript language as well.

Thomas Palef has written a new tutorial about using JavaScript with Unity called How to Make a 2D Space Shooter in Unity. It shows you how to get started making a game with Unity’s UI, and includes some simple JavaScript for handling firing a bullet.

If you’re interested in Unity but thought it was something that only desktop developers can get into then you might enjoy following this tutorial.

fixmyjs, Front-end Development Tools

02 Oct 2014 | By Alex Young | Comments | Tags modules libraries lint design chrome



Sindre Sorhus sent in fixmyjs (GitHub: jshint / fixmyjs, License: MIT, npm: fixmyjs) by Josh Perez. It automatically rewrites JavaScript based on linting rules. There’s a command-line tool available through npm, and a web version.

It supports things like semi-colon insertion, case correction, missing curly braces, and removes debugger statements. Sindre said Addy Osmani wrote an article about it, where he points out some important things that fixmyjs can get wrong:

As mentioned earlier, the current version of the module uses Escodegen, which rewrites your source and doesn’t take into account original styling information (i.e it will strip it). This makes it easier for the author to support complex new rules as they operate with an AST rather than relying on less reliable approaches like string replacement.

You can avoid this by using the legacy option.

If you use Atom, then you can install Sindre’s Atom plugin for fixmyjs. It uses legacy by default, and can be run on a whole file or a selection.

56 Expert’s Favourite Front-end Tools

Bauke Roesink sent in a big list of front-end development tools, picked by 56 experts. Coincidentally, I happened to notice Sindre Sorus is on the list.

Several people picked Chrome, probably because the development tools have progressed so much over the last year or so. It’s increasingly common to see people testing design ideas or puzzling over CSS quirks by editing HTML and CSS in the inspector. I’ve recently started using the device emulation tab a lot for responsive designs as well.

Node Roundup: Node 0.11.14, svgexport, node-webkitgtk

01 Oct 2014 | By Alex Young | Comments | Tags modules libraries node

Node 0.11.14


Node 0.11.14 has been released, with updates for uv, http_parser, npm, openssl, and v8.

There seem to be fixes for almost every core module: cluster has been reverted to the 0.10 setupMaster behaviour, console.dir accepts options, events now outputs the event that is leaking – there are loads more changes that you should be aware of before updating.

The version of uv included in 0.11.14 is rc1. Also, when I went to check the recent commits for uv I noticed it now has a cool dinosaur/unicorn logo.


svgexport (GitHub: shakiba / svgexport, npm: svgexport) by Ali Shakiba is a command-line tool for converting SVG files to PNG, JPEG, and PDF.

It’s based on PhantomJS, and the author has been using it to automatically convert icons for iOS and Android projects. This seems like a cool use for Node/Gulp/Grunt as part of a non-web-native build chain that I hadn’t thought of before.


node-webkitgtk (GitHub: kapouer / node-webkitgtk, License: MIT, npm: webkitgtk) by Jérémy Lal is a set of webkitgtk bindings for Node. The API is chainable, so you can do things like this:


It’s designed to be used headlessly, so it’s useful for things like generating website thumbnails, or maybe integration testing but I haven’t tried that.

HTMLjs, Building an Angular List

30 Sep 2014 | By Alex Young | Comments | Tags angularjs libraries html mvvm


HTMLjs (GitHub: nhanaswigs / htmljs, License: MIT) by Nhan Nguyen is a data-binding and template rendering library. It supports browsers back to IE7. Rather than using declarative HTML, it’s more JavaScript-driven. For example, given a simple input field, you could bind a validation handler to it like this:

var username ='')
  .required('Username is required.')
  .maxLength(15, 'Max length for username is 15 characters.');


I don’t think declarative templates are a bad thing, but the detail most people consistently get wrong with Knockout is incorrectly binding prototype methods or values. This API circumvents that by relying on simpler markup. The author has provided lots of examples so you can get a feel for how it works without downloading it.

Building an Angular List: Using ng-repeat

Building an Angular List: Using ng-repeat is a tutorial by David Posin about how to use ng-repeat. It’s a simple introductory tutorial, and David includes a screencast so you can see exactly how it works.

I noticed David uses the web-based Cloud9 IDE, so you can even follow along without installing anything if you’re really new to Angular.

js13k Winners, BottleJS

29 Sep 2014 | By Alex Young | Comments | Tags games events di libraries modules

js13k Winners

Pest Control

The js13k winners have been announced. First place went to Pest Control: Weasels by Siorki, which is like Lemmings in reverse – instead of saving little critters you have to kill them. It’s a surprisingly fun game!

Felipe Alfonso came second with Extreme Mini Massacre, and Aurélio Santos came third with ap11. This is like a simplified GTA 1 clone, all in 13k!

There are 129 games listed on the site. Most genres are covered, and there are even some pretty unique ones like Whistleblower which allows you to use the microphone to whistle different pitches to defeat enemies.

The js13k participants get t-shirts and 3.5” diskettes that contain all of the entries. Just to show off how small browser games can be… For those of us without disk drives, however, the source is at js13kGames on GitHub.


BottleJS (GitHub: young-steveo / bottlejs, License: MIT, Bower: bottlejs, npm: bottlejs) by Stephen Young is a dependency injection micro container.

It’s inspired by the AngularJS API. You can register services with bottle.service('Service', Service), and then construct them with bottle.container.Service. Bottle supports middleware, so you can inject functions that intercept requests for providers just before they’re made for the first time.

If you’re not using AngularJS and have trouble keeping larger applications maintainable and testable, then something like Bottle might help improve your application’s structure. The readme has examples and API documentation to get you started.

verb: A CAD Library for the Web

26 Sep 2014 | By Alex Young | Comments | Tags webgl graphics libraries modules

Peter Boyer shared two modules related to 3D graphics: Flood, a visual programming language, and verb, a library for working with NURBS surfaces.

Flood (GitHub: pboyer / flood, License: MIT) behaves a bit like a 3D modelling application. It uses a Scheme interpreter that’s written with JavaScript, with immutable data and first order functions.

The beta application allows you to sign in with a Flood account, Google+, or Facebook. You can add nodes that perform arithmetical operations, shapes, and even functions.


It’s built with Grunt and Bower, and uses libraries like three.js and Bootstrap.

Peter’s other project is verb (GitHub: pboyer / verb, License: MIT), a library for creating and manipulating NURBS surfaces. It works with browsers and Node and supports advanced tools like derivative evaluation, adaptive tessellation, and intersection.

The examples include things like arcs, Béziers curves, and various extrusions. You can rotate the examples if you click and drag.

NURBS are used in CAD, I don’t think they’re particularly popular for game graphics, so presumably Peter intends to use this with the Flood project.

PrototypeJungle, Slick, Cash

25 Sep 2014 | By Alex Young | Comments | Tags modules libraries browser svg


PrototypeJungle (GitHub: chrisGoad / prototypejungle, License: MIT) by Chris Goad is a tree-based object model and inspector. The inspector makes all of the underlying data structures visible, so you can explore and manipulate it.


For example, this is a bar chart, displayed with SVG. You can drill down into each bar and edit things like the bar height, colour, stroke, and so on.

Elements of the model can be serialized and saved in files, and represent things of various complexities, from simple infographic marks such as bars or bubbles, to axes or legends, to complete charts.

Often, an element serves as a prototype (in the general sense). For example, consider a prototypical bubble or bar which is instantiated once for each data point. When an instance of an element is wanted, a special variety of deep copy is made which inherits as appropriate from the original using JavaScript’s prototype formalism. Subsequent adjustments to the original will be inherited by all of the instances, at least in those aspects that have not been overriden.

Chris says it’s at an early stage, but I think it’s a pragmatic look at data visualisation that readers might find interesting.

Slick, Cash

Ken Wheeler sent in some client-side projects that he’s been working on. One is Slick (GitHub: kenwheeler / slick, License: MIT), a carousel that supports a huge amount of things: CSS3 animations when available, touch and mouse gestures, infinite loop, autoplay, adaptive height, lazy loading, fade effects, and it’s responsive as well.

It has an API so you can dynamically add and remove slides. It depends on jQuery 1.7+.

Ken’s other project is cash, a jQuery alternative. It supports lots of methods from jQuery’s API, and is written using separate modules so the source is quite easy to follow. The build system is Gulp. You might find it interesting if you like using or writing small libraries that don’t depend on jQuery and want to see how DOM stuff works without legacy cruft.

Node Roundup: npm 2.0, nvm for Windows, xtpl

24 Sep 2014 | By Alex Young | Comments | Tags modules libraries node npm windows templating

npm 2.0

npm 2.0 has been released, and the announcement post has lots of details on the fixes it includes and the project’s evolving release process. One major change is run-script now accepts arguments:

In npm@2.0.0, Ben changed npm run-script to allow you to pass arguments into scripts. That’s a breaking change. It’s as simple as that. Think of npm 2 as a step on the road towards getting npm right with semver. (There will be more. npm 3 will be out before the end of the year.)

The npm blog also has a post about multi-stage installs:

Multi-stage installs will touch and improve all of the actions npm takes relating to dependencies and mutating your node_modules directory. This affects install, uninstall, dedupe, shrinkwrap and, obviously, dependencies (including optionalDependencies, peerDependencies, bundledDependencies and devDependencies).

This post mentions that npm should be getting progress bars soon, and changes that bring it closer to supporting transactional installation.

nvm for Windows

Apparently, most Node version managers for Windows use batch files, so Corey Butler decided to try a different approach:

This version of nvm has no dependency on node. It’s written in Go, which is a much more structured approach than hacking around a limited .bat file. It does not rely on having an existing node installation. Plus, should the need arise, Go offers potential for creating a Mac/Linux version on the same code base with a substantially easier migration path than converting a bunch of batch to shell logic.

You can get the source from GitHub at coreybutler / nvm, and he’s got binary releases as well.

Corey also sent something called Fenix Web Server (GitHub: coreybutler / fenix, License: GPL), which is a static desktop web server powered by node-webkit:

You can quickly fire up/kill web servers through a GUI or the command line. It has push-button sharing capabilities (localtunnel). There’s also a visual webhook receiver for viewing incoming requests, which also leverages localtunnel.

I like the idea of being able to easily create a static server and then share content with a tunnel.


Yiming He sent in xtpl (GitHub: kissyteam / xtpl, License: MIT, npm: xtpl), an Express/Koa wrapper for eXtensible Template Engine. This template language is similar to others like ejs, but also allows you to add your own synchronous or asynchronous commands.

You can actually add commands to the template language, and they can be inline, block, and asynchronous. Here’s an example:

XTemplate.addCommand('xInline', function(scope, option, buffer) {
  buffer = buffer.async(function(newBuffer) {
    setTimeout(function() {
      newBuffer.write(option.params[0] + 1).end();

  return buffer;

The API documentation has more examples, and xtpl’s readme has some Koa samples as well.

Automatically Start Development Servers with Katon

23 Sep 2014 | By Alex Young | Comments | Tags modules libraries node

Katon (GitHub: typicode / katon, License: MIT, npm: katon) by Typicode is a tool for managing development servers. You can use it with client-side projects, Node applications, and even other server-side technologies.

To use it, npm install -g katon and then run sudo katon install && katon start. This sets up the daemon that will monitor your development servers.

Then all you need to do is navigate to one of your projects and tell Katon how it starts. For example, katon add 'npm start', or katon add 'grunt server'.

The project is inspired by Pow and actually started life as a third-party tool for Pow.

Once you’ve set up a project you can get to it using a .ka subdomain. Pow uses .dev, but the author of Katon switched to .ka because .dev is a proposed TLD.

Here’s Katon running with Express:

Katon, Express

And Typicode sent a screenshot of Rails as well:

Katon, Express

Katon will appeal to those of you that switch between projects regularly. It’s also useful if you run web applications that depend on several microservices that you want to run locally.

On a related note, I often use localtunnel for sharing in-development work with people who are outside my network.

fake-identity, Leaflet.FreeDraw

22 Sep 2014 | By Alex Young | Comments | Tags modules libraries testing graphics maps


fake-identity (GitHub: travishorn / fake-identity, License: MIT, npm: fake-identity) by Travis Horn is a library for generating fake identities. You can use Identity.generate to create a single fake object, or Identity.generate(n) to get an array of n objects.

Here’s an example of the output:

  firstName: "Amelia",
  lastName: "Wright",
  emailAddress: "",
  phoneNumber: "(555) 555-0155",
  street: "7327 Central Avenue",
  city: "Oxford",
  state: "TX",
  zipCode: "75045",
  dateOfBirth: Fri Jul 20 1962 00:00:00,
  sex: "female",
  company: "Contoso Pharmaceuticals",
  department: "Legal"

I find I have to do this quite often for testing. I usually use Faker to make users – in fact, I had to do this very task today! I think fake-identity would have made my job easier in this case, because the schema I’m using is similar.



Leaflet.FreeDraw (GitHub: Wildhoney / Leaflet.FreeDraw, License: MIT) by Adam Timberlake is a library for Leaflet that adds support for creating polygons.

Use Leaflet.draw for drawing pre-defined polygons and linear shapes – Leaflet.FreeDraw’s selling point is that it allows you to freely draw a polygon like Zoopla. Hulls are also supported to normalise polygons when users draw an insane polygon – currently Leaflet.FreeDraw supports Brian Barnett’s Graham Scan module and my adaptation of the concave hull algorithm.

The readme is pretty solid, and explains how to handle polygon mutation, intersection, and elbow creation. The demo allows you to draw and edit polygons, with planes flying over the map.

I actually saw a similar polygon drawing UI widget on Ikea’s solar panel quote page today. You can draw a polygon over your house so it can use the shape to estimate how well solar panels should work for your property.

SVG Circus, Cheers

18 Sep 2014 | By Alex Young | Comments | Tags svg animation scraping dom

SVG Circus

SVG Circus

SVG Circus by Alex Kaul is a site for generating SVG animations. You can use it to make spinners for loading indicators, or other animations if you get creative.

It’s built with AngularJS and Bootstrap, and the Bootstrap customisation looks pretty cool. Animations can be exported as XML with embedded JavaScript for animation.


Yesterday I mentioned ineed, a scraper API based around a streaming tokenizer. Most of my Node scraping work has been written with Cheerio, which is a small jQuery-inspired API for Node. Cheers (GitHub: fallanic / cheers, License: MIT, npm: cheers) by Fabien Allanic is a Cheerio-based scraper library:

The motivation behind this package is to provide a simple cheerio-based scraping tool, able to divide a website into blocks, and transform each block into a JSON object using CSS selectors.

It works by using configuration objects that describe metadata based on CSS selectors, so it may help you to be more pragmatic about how you scrape documents.

Hello.js, ineed

18 Sep 2014 | By Alex Young | Comments | Tags libraries apis parsing


Andrew Dodson sent in hello.js (GitHub: MrSwitch / hello.js, License: MIT, npm: hellojs), a client-side API wrapper for OAuth2-based REST APIs. It presents a unified API that normalizes paths and responses for Google Data Services, Facebook Graph and Windows Live Connect.

One of the advantages of hello.js is it’s modular. There are hello.js modules for Dropbox, LinkedIn, SoundCloud, and Yahoo.

The module API allows you to define things like jsonp functions, so it should be flexible enough to handle a lot of modern services.

HelloJS has been on Hacker News, with a discussion on security, and endorsements from users:

HelloJS is great. I’ve used it in my last project. It just works. It’s well tested, and well documented. There’s very little option twiddling required. It just worked seamlessly when I was trying to setup Twitter, Google, LinkedIn and Facebook OAuth logins.


Ivan Nikulin wrote in to say parse5 has a new SAX-style HTML parser which powers the ineed project:

ineed allows you collect useful data from web pages using simple and nice API. Let’s collect images, hyperlinks, scripts and stylesheets from

var ineed = require('ineed');

  function (err, response, result) {

Internally, ineed uses streams of HTML tokens so it doesn’t have to spend time building and traversing a DOM tree. It seems like an ideal way to handle lots of otherwise awkward scraping tasks.

JavaScript for Automation in Yosemite

17 Sep 2014 | By Alex Young | Comments | Tags apple scripting

I seem to remember that I once wrote on DailyJS about how Apple should start using JavaScript instead of AppleScript, and the possibility of cross-platform scripting with JavaScript. It looks like this is finally happening in Yosemite, highlighted in Apple’s JavaScript for Automation documentation (and HN).

What does it look like? Here’s a sample for Mail:

var Mail = Application('Mail');

var message = Mail.OutgoingMessage({
  subject: 'Hello world',
  visible: true


It goes further, though, with the Objective-C bridge:

JavaScript for Automation has a built-in Objective-C bridge that offers powerful utility such as accessing the file system and building Cocoa applications.

The primary access points for the Objective-C bridge are the global properties ObjC and $.

There are mappings for Objective-C methods and data types, and you can load frameworks that are built with bridge support using ObjC.import.

This bridge layer should make it possible to build native Cocoa applications that are partly drive by JavaScript, allowing you to potentially centralise some business logic into JavaScript that can run in Apple’s environment or the equivalent for .NET.

This is made possible thanks to the design of the Open Scripting Architecture, and JavaScript is the second language after AppleScript that has been added.

On the commercial project I work on our Mac team recently tested JavaScript support for our scripting API. It’s definitely going to make it easier for me to automate things!

Tutorial: Build a Game with Phaser

16 Sep 2014 | By Thomas Palef | Comments | Tags games tutorials phaser
This is a guest post written by Thomas Palef, the author of Discover Phaser and the 12 Games in 12 Weeks challenge.


In this tutorial I will show you how to use Phaser to build a really simple retro breakout clone. Phaser is a simple yet powerful JavaScript framework for making HTML5 games.

Game screenshot

You can play the finished game we are going to make here.

Set Up

You should download this empty template that I made for this tutorial. In it you will find:

  • phaser.min.js, the Phaser framework v2.0.5
  • index.html, where the game will be displayed
  • main.js, a file where we will write all our code
  • assets/, a directory with 3 images (ball.png, paddle.png and brick.png)

You should also download the code editor Brackets, that will make it easier for starting a web server during development.

Empty Game

Let’s start by creating an empty Phaser project. Add this code inside the main.js file:

// Define our main state
var main = {
  preload: function() {
    // This function will be executed at the beginning     
        // That's where we load the game's assets  

  create: function() { 
    // This function is called after the preload function     
        // Here we set up the game, display sprites, etc. 

  update: function() {
    // This function is called 60 times per second    
        // It contains the game's logic     

// Initialize Phaser, and start our 'main' state 
var game = new Phaser.Game(400, 450, Phaser.AUTO, 'gameDiv');
game.state.add('main', main);

This will create a 400x300 black rectangle on the screen. All we have left to do is to fill the preload, create, and update functions to build our breakout clone.

Add the Paddle

Let’s focus on creating the paddle first. We load it in the preload function, initialize it in the create function, and make it move in the update function:

preload: function() {
  // Load the paddle image
  game.load.image('paddle', 'assets/paddle.png');

create: function() { 
  // Initialize the physics system of the game

  // Create a variable to handle the arrow keys
  this.cursor = game.input.keyboard.createCursorKeys();

  // Create the paddle at the bottom of the screen
  this.paddle = game.add.sprite(200, 400, 'paddle');

  // Enable the physics system for the paddle

  // Make sure the paddle won't move when hit by the ball
  this.paddle.body.immovable = true;

update: function() {
  // If the right arrow is pressed, move the paddle to the right
  if (this.cursor.right.isDown) 
    this.paddle.body.velocity.x = 350;

  // If the left arrow if pressed, move left
  else if (this.cursor.left.isDown) 
    this.paddle.body.velocity.x = -350;

  // If no arrow is pressed, stop moving
    this.paddle.body.velocity.x = 0;  

Test the Game

Now it’s time to test our game. Open the whole directory in the Brackets editor, select the index.html file, and click on the small bolt icon in the top right corner. It will launch a live preview of the game, where you should have a paddle that you can move with the arrow keys.

If you don’t want to use Brackets, then you’ll have to use a local web server to test the game.

Add the Bricks

Now let’s add a dozen bricks to the game.

Start by adding this to the preload function:

// Load the brick sprite
game.load.image('brick', 'assets/brick.png');

Then add this to the create function:

// Create a group that will contain all the bricks
this.bricks =;
this.bricks.enableBody = true;

// Create the 16 bricks
for (var i = 0; i < 5; i++)
  for (var j = 0; j < 5; j++)
    game.add.sprite(55+i*60, 55+j*35, 'brick', 0, this.bricks);

// Make sure that the bricks won't move
this.bricks.setAll('body.immovable', true);

Add the Ball

Now that we have a paddle and some bricks, it’s time to add the ball.

Add this in the preload function:

// Load the ball sprite
game.load.image('ball', 'assets/ball.png');

And add this in the create function to initialize the ball:

// Create the ball with physics
this.ball = game.add.sprite(200, 300, 'ball');

// Add velocity to the ball
this.ball.body.velocity.x = 200; 
this.ball.body.velocity.y = 200;

// Make the ball bouncy 
this.ball.body.collideWorldBounds = true;
this.ball.body.bounce.x = 1; 
this.ball.body.bounce.y = 1;

Handle Collisions

The only thing left to do is handle collisions. And it turns out this is super simple with Phaser – just add these 2 lines of code to the update function:

// Make the paddle and the ball collide
game.physics.arcade.collide(this.paddle, this.ball);

// Call the 'hit' function when the ball hit a brick
game.physics.arcade.collide(this.ball, this.bricks, this.hit, null, this);

Next, create the new hit function, just below the update function:

hit: function(ball, brick) {
  // When the ball hits a brick, kill the brick

And we are done! you can now play a really simple breakout clone made in less than 50 lines of JavaScript.


The game is working, but it’s a little bit boring. With Phaser it’s really simple to add sounds effects, animations, transitions, and so on to make a game better.

If you want to learn more about Phaser, I can recommend you to check out the first and only Phaser ebook currently available: Discover Phaser.

Phaser cover

Melchior.js, ng-admin

15 Sep 2014 | By Alex Young | Comments | Tags libraries modules angularjs ui


Melchior.js (GitHub: voronianski / melchior.js, License: MIT, npm: melchiorjs) by Dmitri Voronianski is an implementation of the Chainable Module Definition concept introduced by John Wu.

The idea behind chainable modules solves several nasty AMD patterns like long lines of declaring dependencies and provides simplicity and readability with its’ visual-friendly and clean syntax.

As CommonJS is more good for non-browser environments, chaining modules with requires fit perfectly for in-browser use cases.

Here’s an example of the API:

// create module

// define dependencies
.require('dependencyDuo', 'duo')

// define module body
.body(function () {
  // `dependencyUno` is available here!

  // aliased `dependencyDuo` is available as `duo`!

  // return methods for other modules
  return {
    method: function () { ... },
    anotherMethod: function () { ... }

The readme has more examples including one for AngularJS. This API does seem more idiomatic than most module loaders, so it’ll be interesting to see if it catches on.


François Zaninotto sent in ng-admin (GitHub: marmelab / ng-admin, License: MIT), a cool project that adds an administration interface to RESTful CRUD APIs.

There’s a demo on Amazon and documentation that shows how to configure ng-admin to use your application’s entities. It copes with field mappings, and references. References can be 1-N, N-1, and many to many.

François suggests that ng-admin is useful because if you’re creating a lot of projects with different backends (MongoDB, MySQL, Node, Python) you can still add a platform-agnostic administration UI.

The same authors also made gremlins.js.