You are a Robot...

30 Jun 2014 | By Alex Young | Comments | Tags tutorials javascript games
That smiling face is you.

You are a robot, that smiling face represents you.

My digital residual self image isn’t what it once was, but surely I’m more than a smiling face glyph! JS Robot by Pavel Evsegneev an open source game for learning JavaScript. The GitHub repository is here: Ahineya / jsrobot.

The levels are unit tested with Mocha, and the author accepts pull requests for new levels. Levels are defined as text files, like this:

########
#_  $f #
########

The _ is the start position, $ and # are walls, and f is the finish. The player must write JavaScript that pushes the robot to the f position. The full list of symbols is defined in map.js:

var SYMBOL_TYPES = {
  '#': 'wall',
  '$': 'wall',
  'space': 'space',
  '_': 'start',
  'f': 'finish'
};

It’s a fun game that may have a few surprises for beginners learning JavaScript, and the code is clean. You could easily extend it to have fancier graphics or a different narrative, but I like the text-based interface. It would be nice to optionally play it in a terminal by installing it with npm.

s/Ampersand.js/Backbone and Express/

27 Jun 2014 | By Alex Young | Comments | Tags frameworks node

Ampersand.js from &yet is a new web framework. It follows the trends that I’ve been using for my own applications:

  • Everything is CommonJS
  • Client-side dependencies use npm (for a list of modules, see http://tools.ampersandjs.com)
  • State and data binding is Backbone-inspired

It has a heavy focus on client-side development, so it leans on the MVVM approach. Most of these ideas come together in the form documentation:

The quickest way to build out a starting point for a form in your project is to point ampersand-cli at a model file to generate a form for editing it. We’ll eventually make more “official” input views types. But the idea is, if you want to write a color picker, or a date input view, or a username-checker-input that does server-side validation, or a password field with a strength indicator, you can write a view for that and as long as it follows the form view conventions in the list above and it will still work happily with the rest of the form.

This is further explained explained in what is a view?

It doesn’t matter if your “view” is an instance of ampersand-view or not. Any object can be a view if it follows a few rules.

The example on that page looks like Backbone as well.

When generating a new Ampersand application, it prompts for the server-side module. You can use either Express or hapi. It makes a demo app, which almost entirely client-side JavaScript. The payload that gets served is just this:

<!DOCTYPE html>
<link href="/dailyjs.nonCached.css" rel="stylesheet" type="text/css">
<script src="/dailyjs.nonCached.js"></script>

It runs using a livereload module, so you can edit files and the client will be updated. As the documentation says, it treats the browser as a runtime.

Ampersand seems like a way to unify Node and Backbone development. I don’t yet know how well Ampersand works in production on services like Heroku, or how easy it is to test, but I’m definitely enthusiastic about the idea of blending Node and libraries like Backbone or AngularJS.

V8 Optimization Killers

26 Jun 2014 | By Alex Young | Comments | Tags node v8 performance

Bluebird gets a lot of respect for its performance and API style, and reading Optimization killers on the Bluebird wiki reinforced my own inclination to use it over the dozens of other competent promise libraries.

Dug up by diggan on Hacker News, this wiki page explores some ways seemingly innocent JavaScript can cause V8 to avoid optimisation. It contains a code sample that allows you to detect if a function has been optimised, which I’ve been playing with:

// Function that contains the pattern to be inspected (using with statement)
function codeToTest(a, b) {
  if (arguments.length < 2) b = 5;
}

function printStatus(fn) {
  switch(%GetOptimizationStatus(fn)) {
    case 1: console.log('Function is optimized'); break;
    case 2: console.log('Function is not optimized'); break;
    case 3: console.log('Function is always optimized'); break;
    case 4: console.log('Function is never optimized'); break;
    case 6: console.log('Function is maybe deoptimized'); break;
  }
}

// Fill type-info
codeToTest(1, 2);

%OptimizeFunctionOnNextCall(codeToTest);
// The next call
codeToTest(1, 2);

// Check
printStatus(codeToTest);

%OptimizeFunctionOnNextCall causes V8 to to check if a function can be optimised, and then marks it for optimisation. Running it and then calling %GetOptimizationStatus will get debugger information so you can see if a given function can be optimised.

To run this example, the Bluebird wiki suggests using the following Node options:

node --trace_opt --trace_deopt --allow-natives-syntax test.js

The --trace_opt option logs the names of optimised functions, and --trace_deopt logs “deoptimisations”. The --allow-natives-syntax option allows you to use the V8 functions that start with a percent, like %OptimizeFunctionOnNextCall.

If this all sounds interesting but you’re focused on client-side development, then you might like to look at the Web Tracing Framework from Google. It can use some of V8’s extra tracing options, and has both Chrome and Firefox extensions with rich instrumentation features. You’ll need to enable some flags to use it.

Node Roundup: husky, grunt-npmcopy

25 Jun 2014 | By Alex Young | Comments | Tags node modules npm grunt git

husky

husky (GitHub: typicode / husky, License: MIT, npm: husky) by typicode is a module for helping to avoid bad commits being pushed using Git hooks.

It basically sets up Git hooks for your Node projects:

So what makes husky different?

First, other modules often replace or delete existing hooks. husky won’t ever replace or modify an existing hook, so it’s a safer choice for a team or an open source project. In other terms, people who have set up their own hooks won’t be impacted by husky.

I think also that husky is more easier and straightforward to use compared to others. husky’s README is just a few lines and setting up hooks should be simple.

And last, usually other modules introduces unconventional package.json fields, husky uses only valid package.json fields.

grunt-npmcopy

grunt-npmcopy (GitHub: timmywil / grunt-npmcopy, License: MIT, npm: grunt-npmcopy) by Timmy Willison allows you to use the same package manager for Node and client-side projects. It helps place client-side dependencies in the right directory by using a Grunt task called npmcopy.

The npmcopy task takes source and destination options so you can avoid copying lots of extra files into your publicly accessible asset directories.

Have you ever wondered why we have so many package managers? NPM, Bower, Component. Why don’t we just pick one? Well, after much deliberation with developers like you, I’ve decided to support the idea that NPM might just be able to handle it all.

Small and Reusable Browser Modules: npm-dom

24 Jun 2014 | By Alex Young | Comments | Tags npm dom modules libraries

npm-dom (GitHub: npm-dom) by Azer Koçulu, Damon Oehlman, Max Ogden, Jake Verbaten, and Tim Oxley is a GitHub organisation that publishes DOM-related modules through npm.

So far there are small modules like new-element (https://github.com/npm-dom/new-element) and siblings (https://github.com/npm-dom/siblings), but also larger modules like domquery (https://github.com/npm-dom/domquery).

There are quite a few modules already. If you work with Browserify then you might like the way these modules can be consumed. As an example, take a look at class-list:

var elem = someElement;
var ClassList = require('class-list');
var cl = ClassList(elem);

cl.add('foo');
cl.remove('bar');
cl.toggle('baz');

Azer was inspired to create another organisation called npm-flickr, which is a set of Flickr-related libraries.

Gifffer, Composing Discrete Events with RxJS

23 Jun 2014 | By Alex Young | Comments | Tags gif animation reactive

Gifffer

Gifffer (GitHub: krasimir / gifffer, License: MIT) by Krasimir Tsonev is a small library for adding a play control to animated gifs. It works by drawing a play button over the image, and dynamically inserting an image element when play is clicked. To prevent the gif from playing when the page loads, the data-gifffer attribute is used instead of the src attribute.

Krasimir has a blog with gifs that illustrate browser features, so he wanted to be able to handle playing gifs more elegantly than the default behaviour. Here’s an example: Gifffer example. You can click it to toggle playback.

Composing Discrete Events with RxJS

Composing Discrete Events with RxJS by Sergey Bolshchikov is a post that compares addEventListener with RxJS. If you’ve ever used Reactive Extensions then you should be at home with the use of selectMany, combineLatest, and so on.

Here’s the full example:

var mouseDowns = Rx.Observable.fromEvent(document, 'mousedown');
var mouseMoves = Rx.Observable.fromEvent(document, 'mousemove');
var mouseUps = Rx.Observable.fromEvent(document, 'mouseup');

var moves = mouseDowns.selectMany(function(md) {
  var start = {
    x: md.clientX,
    y: md.clientY
  };
  return mouseMoves.combineLatest(mouseUps, function(mm, mu) {
    var stop = {
      x: mu.clientX,
      y: mu.clientY
    };
    return {
      start: start,
      stop: stop
    };
  }).takeUntil(mouseUps);
});

moves.subscribe(function(res) {
  var body = document.querySelector('body');
  body.innerHTML = 'Start: x = ' + res.start.x + ', y = ' + res.start.y + '; Stop: x = ' + res.stop.x + ', y = ' + res.stop.y;
});

Google's Web Starter Kit

20 Jun 2014 | By Alex Young | Comments | Tags node gulp sass boilerplate
Web Starter Kit

Web Starter Kit (GitHub: google / web-starter-kit, License: Apache 2.0) from Google is a boilerplate for developing responsive websites. It supports multiple devices, has a gulp.js build script, and has support for synchronising pages across devices during testing.

If you’re a Node developer, then you might like the gulp.js-based environment. Typing gulp will build and optimise the current project, and gulp serve will run a server. There’s also gulp pagespeed that uses Google’s PageSpeed insights.

The sync feature for testing is powered by BrowserSync. BrowserSync is a Socket.IO-based Node application that automatically sends changes to pages as you edit files. It also has a gulp.js module that you can use with your own projects.

If you’re wondering why a Node/Ruby project has come out of Google, then take a look at the Web Starter Kit contributors: it seems like it’s another project by Addy Osmani and Sindre Sorhus, just like Yeoman.

Although this is a boilerplate project, the style guide makes it look more like something like Bootstrap. If you find Bootstrap too heavy for your projects and would prefer something lighter with workflow tools, then give Web Starter Kit a try.

Bridge Node and PhantomJS with phridge

19 Jun 2014 | By Alex Young | Comments | Tags node modules npm phantomjs

I use PhantomJS for integration testing and PDF generation, but I find working with its API awkward. That means I often put as much logic as possible into a Node wrapper before handing off the bare minimum to PhantomJS.

Johannes Ewald sent in a module that attempts to improve on this workflow: phridge (GitHub: peerigon / phridge, License: Unlicense, npm: phridge).

For comparison, here is an example of a standard PhantomJS script:

phantom.addCookie('cookie_name', 'cookie_value', 'localhost', function() {
  phantom.createPage(function(page) {
    page.set('customHeaders.Referer', 'http://google.com', function() {
      page.set(
        'settings.userAgent',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)',
        function() {
          page.open('http://localhost:9901/cookie', function (status) {
            page.evaluate(function(selector) {
              return document.querySelector(selector).innerText;
            }, function (text) {
              console.log('The element contains the following text: ', text)
            }, 'h1');
          });
        }
      );
    });
  });
});

With phridge, however, you can do this:

phantom.run('h1', function(selector, resolve) {
  var page;

  // This code runs inside PhantomJS
  phantom.addCookie('cookie_name', 'cookie_value', 'localhost');

  page = webpage.create();
  page.customHeaders = {
    Referer: 'http://google.com'
  };
  page.settings = {
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)'
  };
  page.open('http://www.google.com', function() {
    var text = page.evaluate(function(selector) {
      return document.querySelector(selector).innerText;
    }, selector);

    // Resolve the promise and pass 'text' back to node 
    resolve(text);
  });
}).then(function(text) {
  // Inside node again
  console.log('The element contains the following text: '+ text);
});

The phantom object has its own API that is specific to phridge. Phridge works by starting a small HTTP server from within PhantomJS to act as an API entry point from Node. It uses a shared secret to reduce the potential for abuse – this is documented in the readme, under a note on security.

The approach used by phridge is similar to my own homebrew solutions that have evolved over the last year or two, so I’m hoping I can replace my ad-hoc code with phridge to make my PhantomJS dependent projects more maintainable.

Node Roundup: Node 0.8.27 and 0.10.29, BipIO, Reducto

18 Jun 2014 | By Alex Young | Comments | Tags node modules npm

Node 0.8.27 and 0.10.29

You may be surprised to see a Node 0.8 release here, but 0.8.27 and 0.10.29 have been updated to fix an OpenSSL and UTF-8 encoding issue:

Additionally these releases address the fact that V8 UTF-8 encoding would allow unmatched surrogate pairs. That is to say, previously you could construct a valid JavaScript string (which are stored internally as UCS-2), pass it to a Buffer as UTF-8, send and consume that string in another process and it would fail to interpret because the UTF-8 string was invalid.

This breaks backward compatibility for the specific reason that unsanitized strings sent as a text payload for an RFC compliant WebSocket implementation should result in the disconnection of the client. If the client attempts to reconnect and receives another invalid payload it must disconnect again. If there is no logic to handle the reconnection attempts, this may lead to a denial of service attack.

The post includes an example with Buffer, and demonstrates how even if you’re not explicitly creating Buffer instances from strings Node might still do it behind the scenes.

BipIO

BipIO (GitHub: bipio-server / bipio, License: GPLv3) an API platform for consuming and composing APIs based on graph definitions and pipelines. You can run your own server, and there’s a closed source web UI that you can sign up to:

If you’re familiar with Yahoo Pipes, IFTTT, Zapier, Mulesoft, Cloudwork or Temboo - the concept is a little similar. The server has a small footprint which lets you create and automate an internet of things that matter to you. It can be installed alongside your existing open source app or prototype for out-of-band message transformation, feed aggregation, queuing, social network fanout or whatever you like, even on your Rasberry Pi.

It uses MongoDB and RabbitMQ, and the readme has help for setting it up on a server with Monit.

Reducto

Reducto (GitHub: michaelleeallen / reducto, License: MIT, npm: reducto) by Michael Allen is configuration framework for Express that aims to simplify the creation of routes for APIs.

The main goal of reducto is to break apart the routing mechanism into smaller, more cohesive components. By reducing your app to just middleware, data transforms, and reusable service calls you end up with a smaller set of code to reason about and thus make your app easier to write and maintain.

You can create routes using JSON files that map middleware, service handlers, data fixtures, and transform functions to routes. It also supports services, which are callable HTTP endpoints. It comes with an example application that shows weather for a given zip code.

Hya: JavaScript Synths and Plugins

17 Jun 2014 | By Alex Young | Comments | Tags audio midi
A Hya session.

Cristiano Belloni has relaunched KievII Host as Hya.io. This is a web-based plugin-based audio application that supports hardware MIDI though Web MIDI, audio synthesis, sequencers, and lots of plugins.

The project has a blog with announcements about updates, plugins, and some technical background. The web interface is closed source, but the plugins Cristiano has written are open source. For example, hy-osc is an oscillator, and kmx is a mixer.

Hya supports AMD and ES6 modules. They use a simple JSON object that describes the plugin, and a constructor function. You can bind to the Hya GUI using various events, like handleMouseOver and handleMouseDown. The post Developing a canvas plugin for Hya.io explains how to create plugins in detail.

The documentation has details on MIDI interaction and the initPlugin constructor. It’s amazing to think that you could connect a MIDI control surface or keyboard to a web application.

Miminal Promises with Thenable

16 Jun 2014 | By Alex Young | Comments | Tags es6 promises async

Thenable

If you want to use ES6 promises using the Promise object in a library or module, then there’s a new implementation that you might want to check out. Thenable (GitHub: rse / thenable, License: MIT) by Ralf S. Engelschall is a Promise implementation based on Promises/A+.

This is a strictly-compliant Promises/A+ 1.1.1 implementation in just 2KB of (compressed) code, which passes the official Promises/A+ Test-Suite and includes back-references to the relevant specification statements. It just provides a minimum Promise functionality, because it is intended to be directly embedded into ECMAScript 5 based libraries and frameworks, in order to dependency-free leverage from Promises and be able to return “thenable” Promise objects to applications.

Because Thenable is a minimum implementation of Promises/A+, it’s suited to the creation of libraries that are forwards compatible, rather than for consumption in JavaScript applications. To reinforce the point, Ralf hasn’t published it to npm or Bower.

Instead, please download the raw thenable.min.js and include it verbatim into your library/framework. The usual approach for this is to temporarily emulate a CommonJS environment within your library/framework to get its Thenable object.

It has a noConflict option for browsers, and supports AMD, CommonJS, and browsers.

If you want to use Promises/A+ in your applications, Ralf recommends Bluebird, and there’s a large list of other implementations on the promises spec wiki: promises-spec / implementations.md.

Web Worker Contest, Steady.js, Jasmine Integration Tests

13 Jun 2014 | By Alex Young | Comments | Tags jasmine testing webworker ui

Web Worker Contest

The Web Worker Contest, sent in by Stefan Trenkel, is a JavaScript game where two programs compete to conquer a two-dimensional space using simple movement commands.

On a playing area of 100 x 100 square fields two JavaScript programs compete against each other. From a randomly allotted starting point they must conquer as many fields as possible. The winner is who occupies most fields at the end. A move is to conquer from the current field either the upper, lower, right or left adjacent field. The new field can be occupied only if it was not previously occupied by the opponent’s program. If a move is possible (the new field is free) the current position changes to the desired field. If a move is not possible (the field is occupied by the opponent or you want to leave the playing area), you stay on the current position. Fields that one has previously occupied can be used again (but do not count double). The programs do not have any information about the playing area.

The contest is based on the Web Worker API:

Your own Web Worker is simply a local JavaScript file with appropriate code. In this case your own Web Worker is not uploaded to the server. This option is primarily for testing and optimizing your own Web Worker. If you want to participate in the WWC you have to upload your Worker on the Upload page.

You can view running games and read more about the concept in the guide.

Steady.js

Steady.js (GitHub: lafikl / steady.js, License: MIT) by Khalid Lafi is a library for elegantly responding to onscroll events. With Steady.js, the onscroll handler collects data, then offloads the work to requestAnimationFrame. It throttles events, and works like @media-query.

Steady.js is based around “trackers”: these provide the logic that the data collector uses. An example of a built-in tracker is scrollTop which indicates how far a scrollable element has moved from the top.

Basic usage looks like this:

var s = new Steady({
  conditions: {
    width: 400,
    scrollX: 0,
    max-bottom: 200
  },
  throttle: 100,
  handler: fn
});

s.addCondition('scrollX', 0);

The documentation has an example of a custom tracker that you can extend with your own behaviour.

Jasmine Integration Tests

jasmine-integration by Jordi Noguera is an integration testing extension for Jasmine. It allows you to run tests in browsers by using an iframe, or in headless mode using PhantomJS.

The documentation shows how to use it with Grunt, so you can execute your tests against a browser with grunt jasmine:server, or in headless mode using grunt jasmine:server:ci.

Jordi has written a sample app with tests called node-todo which demonstrates how the same specs can be used for browser testing and headless tests on the command-line.

Why Ramda?, Two-Way Data Binding Review

12 Jun 2014 | By Alex Young | Comments | Tags ui data-binding functional mvvm

Why Ramda?

Scott Sauyet sent in Why Ramda?, a post that attempts to explain the Ramda library:

To those not used to functional programming, Ramda seems to serve no purpose whatsoever. Most of its major capabilities are already covered by libraries like Underscore and LoDash.

These folks are right. If you want to keep coding with the same imperative and object-oriented styles you’ve been using, Ramda does not have much to offer you.

However, it does offer a different style of coding, a style that’s taken for granted in purely functional programming languages: Ramda makes it simple for you to build complex logic through functional composition. Note that any library with a compose function will allow you do functional composition; the real point here is: “makes it simple”.

The article builds on the functional composition idea and leads up to the kind of data-focused programming that Ramda makes possible.

Two-Way Data Binding Review

Two-Way Data Binding by Nikita Vasilyev is a review of two-way data binding in Backbone, React, Angular, Meteor and plain JavaScript.

It highlights an issue that some libraries might have if they change fields at the wrong time:

The problem is that data flows from an input field to a model, and then back to the same input field, overriding the current value even if it’s exactly the same.

React.js doesn’t have Backbone’s problem with moving the cursor position. Its virtual DOM, a layer between the actual DOM and React’s state, prevents React from unnecessary DOM changes.

There’s also an informative comment by Leo Horie about the effort required to learn each framework:

Something that strikes me about the framework versions is the amount of framework-specific knowledge required to get these examples working. It’s one thing to say “here’s a version in framework X”, and it’s quite another to actually write the code (from the standpoint of someone who’s still considering framework options and who is not familiar with the lingo and caveats for any of them.)

Node Roundup: npm's New Web Framework, Notes from the Road, TJ Fontaine Interview

11 Jun 2014 | By Alex Young | Comments | Tags node modules npm interviews

npm’s New Web Framework

In Nearing Practical Maintainability on the official npm blog, there’s a discussion about the decision to use hapi.js for npm’s new site:

Both Hapi and Express rate extremely well against our juding criteria. To choose between the two, it pretty much came down to the framework architecture: Hapi’s plugin system means that we can isolate different facets and services of the application in ways that would allow for microservices in the future. Express, on the other hand, requires a bit more configuration to get the same functionality (it’s certainly capable!).

The current npm-www has a lot of dependencies that you might have seen before: browserify, uglifyjs, moment, ejs, and nodemailer are all popular modules. I think using something like hapi.js or Express makes sense, even if it just gives the project some architectural hints.

While, yes, we could use barebones Node.js and roll our own framework, we want to avoid the same “special snowflake” situation that we’re currently in. Plus, by using a framework, we can focus more on pushing out the features our community wants and needs, instead of debugging some weird nook and/or cranny that someone forgot about.

Notes from the Road

Notes from the Road is a post on Node’s official blog by TJ Fontaine about the Node on the Road events:

These Node on the Road events are successful because of the incredible support from the community and the existing meetup organizations in their respective cities. But the biggest advantage is that the project gets to solicit feedback directly from our users about what is and isn’t working for them in Node.js, what modules they’re using, and where they need Node to do better.

From these experiences TJ has written up some notes about Node’s release schedule, future documentation improvements, and the path to becoming a Node contributor:

In an effort to make it easier for users to contribute to Node.js the project has decided to lift the requirement of signing the CLA before contributions are eligible for integration. Having to sign the CLA could at times be a stumbling block for a contribution. It could involve a long conversation with your legal department to ultimately contribute typo corrections.

TJ Fontaine Interview

Meanwhile, the Node hosting company Modulus has interviewed TJ Fontaine, where some of these points are reiterated:

If you’re looking for ways to contribute to Node itself, the website will be soon be going through an overhaul to improve our documentation. We’re going to be adding a lot more documentation, cleaning up what we already have, as well as designing the pieces to help internationalize the site. Node’s community is globally diverse, we should be working to enable Node users everywhere they are.

Node Hardware Hacking with Tessel

10 Jun 2014 | By Alex Young | Comments | Tags node hardware
Node-compatible hardware.

Imagine being able to run npm install gprs to add GPRS tracking support to a hardware project… Well, now you can with Tessel!

The idea behind hardware platforms like Tessel is to make it easier for software developers to interface with hardware. This is ideal if you’ve ever thought it would be nice to hook up a movement sensor to a camera to take a photo whenever your dog or cat moves.

Microcontrollers are chips that contain a processor, memory, and I/O. You can hook them up to sensors for input, and things like servos and speakers for output. Unfortunately microcontrollers have limitations – once you start adding the amount of RAM and processing power required for a high-level language like JavaScript then the costs add up. Also, while they can be programmed, most of them aren’t trivial to program – some have to be flashed with special hardware.

This is why Arduino was such a big deal: it made it easier for programmers and non-technical tinkerers to upload code to a microcontroller using a computer and USB cable.

Tessel and Espruino have iterated on Arduino by using slightly more powerful hardware to allow JavaScript to run. Espruino’s strength is it uses a specialised version of JavaScript that means it can use cheaper, low-powered hardware.

On the other hand, Tessel has built-in Wi-Fi and an ARM Cortex-M3 microcontroller. Because it’s so powerful, it can run thousands of standard Node modules straight from npm. And even better, Tessel has a wide selection of hardware modules, including:

  • Accelerometer
  • Audio (MP3/AAC/WMA/MIDI/FLAC/Ogg Vorbis)
  • Bluetooth LE
  • Camera
  • MicroSD
  • Relay (for controlling higher-powered devices)
  • Servo

Naturally all of these toys come at a price: Tessel with a single module costs $99. You can also buy Tessel with all available modules for $599.

I have an Espruino, but I don’t have a Tessel yet. I like the idea of using npm install with Tessel, but Espruino is already easy to connect to sensors and other hardware, particularly for those with Arduino experience.

My recommendation is to try Tessel if you’re perplexed by hardware but good at Node, and have some free time and cash.

jsEq, Angular-breadcrumb

09 Jun 2014 | By Alex Young | Comments | Tags angularjs equality

jsEq

jsEq (GitHub: loveencounterflow / jseq, License: ISC) is a deep equality test suite:

There are a couple of related, recurrent and, well, relatively ‘deep’ problems that vex many people who program in JavaScript on a daily base, and those are sane (deep) equality testing, sane deep copying, and sane type checking.

It highlights how much variance there is between different equality implementations, including lodash, Underscore, Node’s assert.deepEqual, and more.

The project uses dependencies from npm, so even though it uses lots of dependencies it’s easy to install and run the tests.

The readme has a list of axioms that are used to design the tests. So far, Underscore and lodash seem to be winning:

I sorted the results, and seeing that underscore got the highscore (pun intended), it surprised me to see that it insisted on treating +0 and -0 as not equal. Ultimately, this led to the discovery of the second Axiom, and with that in my hands, it became clear that underscore got this one right and my test case got it wrong: Since there are known programs that behave differently with positive and negative zero, these two values must not be considered equal.

The output of the test suite looks incredibly cool – you can easily see the output of a huge amount of tests. There’s a glorious console screenshot in the readme.

Angular-breadcrumb

Angular-breadcrumb (GitHub: ncuillery / angular-breadcrumb, License: MIT) by Nicolas Cuillery is a module for generating breadcrumb navigation. You can use the ncy-breadcrumb directive to apply it.

It’s based on the AngularUI Router, and Nicolas has been writing pretty solid documentation in the Angular-breadcrumb wiki.

MotorCortex.js, Testing AngularJS with Jasmine

06 Jun 2014 | By Alex Young | Comments | Tags animation jasmine testing angularjs

MotorCortex.js

Think of dancer dancing or a human just walking the street. It is extremely unnatural to think that each part of the body acts independently. A centralized mechanism controls all parts in order to produce a smooth, elastic and natural movement. The “motor cortex”, is the specific part of the brain that does exactly this job.

The idea of declarative templates seems to be spilling into the world of client-side animation. MotorCortex.js (GitHub: andreas-trad / motorcortexjs, License: WTFPL) by Andreas Trantidi is a new library that builds on Velocity.js to provide an animation API that’s based on CSS syntax.

With MotorCortex.js, external *.mss files determine animation parameters. These are based on the CSS parameters that are supported by Velocity.js:

.section:myEvent{
  duration: 400;
  top: 300px;
}

For more examples with the associated CSS and JavaScript, see http://motorcortexjs.com/#examples.

Testing AngularJS with Jasmine

David Posin sent in Angular and Jasmine: Injecting into the test environment. He’s been using Jasmine for tests in both Node and client-side JavaScript, so he wanted to use it with Angular as well:

Angular requires a very specific environment in which to function. The result of that can be a significant amount of boilerplate when creating tests for Angular applications in Jasmine. The good news is that the amount of redundancy can be minimized with careful test organization.

The way he does this is by creating embedded suites:

The spec file will have one describe that contains that spec’s entire content. Inner describe clauses will be used to manage and break up the tests. Inside of the main over-arching describe we will add variables to contain the services that all the clauses will need.

I too find it frustrating to have to switch my preferred test library because of a framework’s design, so it’s interesting that he managed to get Jasmine working in the end. It can be quite hard to think the Angular way for relative newcomers.

Receiving Emails with Node

05 Jun 2014 | By Alex Young | Comments | Tags node modules npm email servers

One of the things I like to evangelise about Node is the fact it’s good for creating any network servers, not just web stuff. Florent Galland sent in Mailin (GitHub: Flolagale / mailin, License: MIT, npm: mailin), which allows your web apps to receive inbound emails. What’s cool about Mailin is it runs as an SMTP server, so rather than having to configure a mail server you can just use Mailin by itself.

Mailin’s homepage has a cool demo that allows you to send it an email and see it appear on the page. This works using Mailin’s webhook.

Mailin

You can configure the webhook when the server is started:

mailin --webhook http://example.com/incoming_emails

The documentation explains how to install it with authbind for safe binding to port 25, otherwise sudo or a root user would be required.

The documentation also mentions optional spam detection support.

Mailin is built with the simplesmtp module. This provides a Node API for building SMTP servers. It has an API that should be familiar to anyone who has written HTTP code with Node:

simplesmtp.createSimpleServer({ SMTPBanner: 'My Server' }, function(req) {
  req.pipe(process.stdout);
  req.accept();
}).listen(port);

simplesmtp even supports connection pools, and TLS. I love the idea of using Node for servers that I can customise, but I’m not a security expert so I don’t know what the implications of using these modules in production might be. Maybe it’s time I read Node Security!

Node Roundup: browser-perf, node-modules, module.exports vs. exports

04 Jun 2014 | By Alex Young | Comments | Tags node modules npm

browser-perf

browser-perf (GitHub: axemclion / browser-perf, License: BSD-2 Clause, npm: browser-perf) by Parashuram Narasimhan is a Node-based browser performance testing tool. It collects various metrics from browsers and then displays graphs using the results.

It runs as a command-line script which allows you to specify which browsers you’d like to use:

browser-perf http://example.com --browsers=chrome,firefox --selenium=ondemand.saucelabs.com --username=username --accesskey=accesskey

There’s also a Node API:

var browserPerf = require('browser-perf');
browserPerf('http://example.com/test', function(err, res) {
  // res - array of objects. Metrics for this URL
  if (err) {
    console.log('ERROR: ' + err);
  } else {
    console.log(res);
  }
}, {
  selenium: 'http://localhost:4444/wd/hub',
  browsers: ['chrome', 'firefox']
  username: SAUCE_USERNAME
});

There’s a wiki page with more details.

The author has also written a blog post about browser-perf with a screenshot.

node-modules.com

Gregor Elke sent in node-modules.com, an alternative search engine for npm. It was created by Mathias Buus Madsen and Tobias Baunbæk, and supports GitHub sign in for customisation. It only requires access to your public details, and seems to sort results fairly well.

module.exports vs. exports

Cho S. Kim sent in a post about understanding module.exports and exports:

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file. The keyword require returns an object, which references the value of module.exports for a given file. If a developer unintentionally or intentionally re-assigns module.exports to a different object or different data structure, then any properties added to the original module.exports object will be unaccessible.

Mock APIs with APItizer

03 Jun 2014 | By Alex Young | Comments | Tags testing jquery

When I’m developing APIs for desktop and mobile projects, I’ve found some people like to mock up APIs in tools like Apiary first. This allows non-web developers to create API specifications that can generate sample data for actual HTTP requests.

Sometimes when you’re doing client-side development you want something similar. APItizer, by Mihael Konjević lets you mock APIs with a JSON schema, so you can try out requests from libraries like jQuery without having to hassle a server-side developer.

When developing single page apps, it is beneficial to develop frontend and backend in parallel. To achieve that, you need to mock the API. CanJS implements this elegantly with the can.fixture plugin (used by APItizer). can.fixture intercepts Ajax calls and returns response defined by the fixtures.

To mock an API you need three things:

  1. A JSON schema
  2. To register it with APItizer: apitizer.addSchema('user', schema)
  3. Some sample data: apitizer.fixture.resource('/users', apitizer.schemaStore('user', 10))

Schemas just need to define the properties used by your resources:

var schema = {
    type: 'object',
    properties: {
        id: {
            type: 'integer'
        },
        username: {
            type: 'string'
        },
        password: {
            type: 'string'
        }
    }
};

This will give you some sample users that you can interact with using the standard RESTful CRUD routes.

APItizer also allows you to add custom endpoints and response delays, so you can simulate network latency. Full examples can be found in the project’s readme file.

If you’re working on a UI-heavy Knockout or Angular project, then this might help avoid worrying too much about the server as you try out UI ideas.