Protip

I wrote a short protip this morning about the European mirror for npm. Developers in Europe (such as myself, based in Manchester, UK), will find this Germany based mirror significantly faster and possibly more reliable.

You can force the use of the European mirror by simply appending the --registry http://registry.npmjs.eu flag to the end of your command, however, I recommend you just set up an alias, e.g:

1
$ alias enpm="npm --registry http://registry.npmjs.eu"

How much faster?

Rather than just claim it is faster, I want to take this blog post further and prove that it’s faster.

Quick test

Let’s pick a package with a few dependencies, grunt.

First, let’s run npm cache clean to remove any data in the npm cache folder. Without supplying a path, this clears the entire cache. A quick run of npm cache ls confirms this.

Timing

How do we actually go about timing an npm install? Well, there’s a basic command called time that’s built into most shells and allows us to easily see the execution time of a command (both “real time” used and system time). This is accurate enough for what we need.

Let’s give it a go:

1
2
$ time npm install grunt
# =4.71s user 1.69s system 29% cpu 21.573 total

Now let’s clear the cache again and try the European mirror:

1
2
$ time npm install grunt --registry http://registry.npmjs.eu
# =3.75s user 1.48s system 44% cpu 11.799 total

21.573s vs 11.799s means it’s almost twice as fast for me to use the European mirror of the npm registry.

Damn, now I don’t have long enough to make a coffee.

npm list

npm list (or npm ls which is my preferred shorthand) is a useful way to determine what npm packages are currently installed. The issue is, you get all their dependencies too (and their dependencies dependencies and their dependencies dependencies dependencies…). A bit frustrating, since this list is usually exceptionally long and no amount of nesting formatting can fully combat this.

Added depth

Turns out there’s an easy way to combat this, although it’s not in the documentation for npm ls.

By adding --depth=0 to the end of the command, it only draws out the top of the dependency tree. Happy days:

1
$ npm ls --depth=0

Go global

This even works for globally installed packages too, by adding the standard -g flag.

I’m getting errors!

When I first tried this, I ended up with a bunch of nonsensical errors (e.g. “npm ERR! max depth reached” among others), although there was nothing really wrong.

You can combat this by adding "$@" 2>/dev/null to the end. This essentially ignores the pointless errors by redirecting them to /dev/null. Nothing to see here, move along :)

The complete command

1
$ npm ls --depth=0 "$@" 2>/dev/null

If you don’t want to type this out all the time (I certainly don’t), you can alias it up:

1
$ alias npmls="npm ls --depth=0 "$@" 2>/dev/null"

Then usage is as simple as:

1
$ npmls

I was too busy to write any blog posts last week, but this more than makes up for it…

Stop the press!

Having spent copious amounts of time emulating native iOS page transitions with JavaScript, HTML5 and CSS3 in the past, everything is about to change.

My new Cordova / PhoneGap plugin allows you to use the real native iOS transitions without ever leaving your web view!

I’ve turned page transitions around (poor pun, I know).

Page transition

Video demo

This is so good, for the first time on my blog, it demands a video demo. Yes, that really is a Cordova web view with a single HTML page.

Down to business

If you’re a Cordova / PhoneGap developer, I’m sure you’re already desperate to get started, so I’ll cut to the chase.

Install

The source code is available on Github.

Assuming you’re using Cordova 3.x and the CLI, installation is as simple as using the cordova plugin add command:

1
cordova plugin add https://github.com/leecrossley/cordova-plugin-native-transitions.git

You do not need to reference any JavaScript, the Cordova plugin architecture will add a nativetransitions object to your root automatically when you build.

Transitions

Flip

Flip page transition, with support for flipping left or right:

1
2
3
var duration = 0.5, // animation time in seconds
direction = "right"; // animation direction - left || right
nativetransitions.flip(duration, direction, onComplete);

Curl

Curl page transition, with support for flipping curling up or down:

1
2
3
var duration = 0.5, // animation time in seconds
direction = "down"; // animation direction - up || down
nativetransitions.curl(duration, direction, onComplete);

Fade

A simple fade page transition:

1
2
var duration = 0.5; // animation time in seconds
nativetransitions.fade(duration, onComplete);

Example

Here’s an example of how I suggest you use the plugin in your code, so that you get a realistic transition:

1
2
3
4
setTimeout(function() {
// Change your html here
}, 50);
nativetransitions.flip(duration, direction);

More transitions?

If you’d like to add more transitions (possibly custom transitions of your own) please pull request. If you’d like something in particular, let me know and I’ll see if I can implement it for you.

This is pretty flippin’ amazing stuff (OK, I’ll stop now).

Playing media on repeat

Playing media is easy with Phonegap / Cordova using the core media plugin. I’m using it in the game I’m writing.

The issue is, I wanted to be able to play a background music loop on repeat (don’t worry, the user can switch this off in my apps settings, or simply mute the sound).

iOS

There’s an “iOS Quirk” that makes this really easy for iOS devices. From the documentation:

numberOfLoops: Pass this option to the play method to specify the number of times you want the media file to play”
1
2
var myMedia = new Media("/audio/my.mp3");
myMedia.play({ numberOfLoops: 2 });

It’s a bit frustrating that you can’t do numberOfLoops: -1 to repeat indefinitely, but I can live with it. The issue is, you can’t do this on Android.

Android

Here’s my work around (that I also for iOS too to keep the JavaScript consistent). It’s really frustrating because this could easily be built into the plugin’s native component.

1
2
3
4
5
6
7
8
9
10
var myMedia;
var loop = function (status) {
if (status === Media.MEDIA_STOPPED) {
myMedia.play();
}
};
myMedia = new Media("/audio/my.mp3", null, null, loop);
myMedia.play();

I’m using the mediaStatus callback that executes when the media status changes, to check to see if the media has stopped playing (it’s finished) and to play the media again.

Can we have a repeat: true please?

Pause for debugging

I blogged a while ago about the Grunt JavaScript task runner, a great way to automate your JavaScript tasks.

On complex projects, with numerous multitasks that display output, it occurred to me that you might want to be able to pause the task runner after each task. You may perhaps need to assess the output or check something, then decide whether or not to continue running the remaining tasks.

grunt-pause

I’ve implemented a Grunt plugin (in a slightly unorthodox manner) to facilitate the pausing, “grunt-pause.js“. It uses the hooker to watch for task changes, then fires off a dynamically added task after each change. The inquirer node package then kicks in to prompt the developer to either continue (default), or clear the task queue and end the task runner.

Grunt core

Personally, I think this should be part of the Grunt core. It would be much easier to implement (not hooky hacky), and could be enabled simply with a “—pause” argument on the command line.

If this package gets used, I’ll consider a pull request to Grunt core for version 0.5.0. This package will still be useful for version 0.4.x etc.

Usage

1
npm install grunt-pause ## --save-dev

Add the grunt-pause reference to the very top of your Gruntfile.js:

1
var pause = require("grunt-pause");

Add the pause init call at the top of the module.exports function of your Gruntfile.js::

1
2
module.exports = function (grunt) {
pause.init(grunt);

Sample output

Sample screenshot of the console output:

Console Screenshot.

Improvements?

You might not want to have the pause between all tasks, perhaps we could pass an array of exclusions or inclusions when we call pause.init(grunt)?

As always, issues and pull request on the git repo.

What’s new

It’s now even easier to find Cordova / PhoneGap plugins on plugreg. To keep up to date with the latest plugreg and plugin related information follow @plugreg on twitter.

Features

Here are some of the new features that have been implemented for v0.7:

  • Plugin details. New design and more info has been added:
    • Version number
    • Last modified
    • Stars
    • Issues
  • Avatars. Now hotlinks to gravatar or github identicons
  • Homepage. A new homepage design, giving various stats, such as:
    • Total number of plugins
    • Total number of authors
    • Recently Added Plugins (and when they were added)
    • Recently Updated Plugins (and when they were updated)
    • Authors with the Most Plugins (and how many plugins each)
    • Authors with the Most Stars (combined from all their plugins)
    • Plugins with the Most Stars (and how many stars)
    • Plugins with the Most Issues (and how many issues)
  • Search. Search is now weighted based on plugin stars
  • Plugin list. Now contains the number of plugin stars

Refresh

All plugin details are now updated/refreshed every 30 minutes (this includes issues / stars etc).

API

A basic API is now available listing details of all the indexed plugins - get in touch for more details if you’d like to use it.

Bugs

There are also many, many bug fixes.

Future updates

Further updates are on the way shortly. If you’d like to suggest an improvement or report an issue, you can do so on Twitter @plugreg

It’s happening again

Beep, beep, beeeeeeep

The node package manager “npm“ is once again grinding to a halt. A post-mortem was published on the official nodejs blog after the recent downtime (November 4th / November 15th 2013), but it’s problems are far from resolved (as demonstrated today).

npm Cardiac Arrest

Keep it beating, keep it awesome

With no other alternative, npm is fundamental to node. More infrastructure is needed to continue to operate the npm registry (multi-master approach and throw hardware and people at it).

In my personal opinion (and I know others echo this sentiment) there also needs to be a change to the way npm handles its dependencies. When currently installing a package, half of the registry is downloaded with it. There are ideas, such as materialising a vector of [package, version] -> hash, but this is exceptionally tricky.

The npm registry has served over 150 million requests and 33 million package downloads in the last week. This is 10 times as many requests and downloads as this time last year, with all signs pointing to further exponential growth.

I’ve donated and I also continue to host my personal node projects on nodejitsu. If you’re a developer that’s ever used npm, donate now on the official site and keep npm everything it needs to be for the community.

Thanks

We all do it

If you’re a JavaScript developer (or even more likely if you’re a developer that dabbles with JavaScript) you’ll have written code like this many times:

1
2
3
4
document.addEventListener("click", function() {
// handler code ...
alert("document clicked and fired ugly nested function");
});

You might be thinking what’s wrong with that, but I hope you’re thinking I’m better than that, I’d do something like this:

1
2
3
4
5
6
var doStuff = function () {
// handler code ...
alert("document clicked and fired alert function");
};
document.addEventListener("click", doStuff);

Great. What do you do if the alert text is dynamic? I’ve seen all kinds of ugly messes that usually lead back to the first approach or result in timing and scoping issues.

This problem isn’t just limited to event handlers, ugly nested anonymous functions are frequently used in callbacks and iterators. This results in poorer performance and uglier, less maintainable and bug prone code.

The right frame of bind

Yes, I really did just make that joke, it’s been a long week. In all seriousness Function.prototype.bind is your friend here, it’ll help you clean up your messy code, like any good friend should. There are other ways to do this of course (JavaScript is wonderful for that):

1
2
3
4
5
6
var doStuff = function (message) {
// handler code ...
alert(message);
};
document.addEventListener("click", doStuff.bind(null, "document clicked"));

Clean, reusable and easier to maintain. Better than inlining or manipulating variables at a higher scope.

A good curry

You can’t beat a good curry, especially if you find yourself nesting iterator functions (ewww). I suggest you take a look at functional.js, or you can read earlier posts on my blog (first post here).

console.log()

If you’ve ever touched JavaScript in your life, you’ll no doubt know about console.log() for debugging. It allows you to log debug information to the console (on most browsers).

The problem

If you log large amounts of debug information, it is hard to interpret your console output effectively. In fact, you probably make this even worse by wrapping even more debug information around what you’re looking for, to help identify it! e.g.

1
2
3
4
console.log("MY GROUP");
console.log(info1);
console.log(info2);
console.log("MY GROUP END");

The solution

console.group()

Using console.group() allows you to (go on, guess) group your console output:

1
2
3
console.group("My group");
console.log(info1);
console.log(info2);

console.groupEnd()

Using console.groupEnd() allows you to terminate logging to the currently defined console group:

1
2
3
4
console.group("My group");
console.log(info1);
console.log(info2);
console.groupEnd();

console.groupCollapsed()

The big hitter, collapse your group by default with console.groupCollapsed() instead of console.group():

1
2
3
4
console.groupCollapsed("My group");
console.log(info1);
console.log(info2);
console.groupEnd();

Objects and arrays

console.table()

If you’re logging objects and/or arrays in your groups, there’s another winner for you in the form of console.table():

1
2
3
4
5
6
console.groupCollapsed("My group");
console.table({
info1: { message: "message 1" },
info2: { message: "message 2" }
});
console.groupEnd();

Console Output

See the jsfiddle here - ensure you open the console, then click run.

Happy, clean debugging!

The swipe gesture

It’s pretty standard to bind swipe events to elements. For the game I’m currently writing, I needed to do something a little different. I wanted to be able to allow the user to swipe across multiple elements and handle this in an elegant and resource efficient way.

The solution

After testing many solutions, here’s what I came up with (and I think it’s the optimum solution). I’m using zeptojs and it’s touch module, although this solution would work with jquery (if you insist), you’d just need to swap out the e.touches with e.originalEvent.touches:

1
2
3
4
5
6
7
var multiSwipe = function (e) {
var touch = e.touches[0],
element = $(document.elementFromPoint(touch.clientX, touch.clientY));
// ...
};
$(".parent").bind("touchmove", multiSwipe);

Essentially, I’m binding the touchmove event to a parent element, then detecting which element is at the current touch point each time the touchmove event is fired. Pretty simple when it’s written for you.

This code is about 10 times smaller than my first attempt and works 10 times faster. document.elementFromPoint is a very effective way to return the topmost element which lies under a given point.

Hammer got it wrong, you can touch this.