Managing Node.js Callback Hell, this Considered Harmful

25 Apr 2014 | By Alex Young | Comments | Tags node tutorials

Marc Harter, who is working with me on Node.js in Practice, recently published Managing Node.js Callback Hell:

Callback hell is subjective, as heavily nested code can be perfectly fine sometimes. Asynchronous code is hellish when it becomes overly complex to manage the flow. A good question to see how much “hell” you are in is: how much refactoring pain would I endure if doAsync2 happened before doAsync1? The goal isn’t about removing levels of indentation but rather writing modular (and testable!) code that is easy to reason about and resilient.

The example he uses is nested asynchronous file operations, with a counter to determine completion. This is compared to a version that uses async, and another that uses promises with q.

The post was originally published on StrongLoop’s blog, here: Managing Node.js Callback Hell with Promises, Generators and Other Approaches. StrongLoop’s blog is worth subscribing to if you’re a Node developer – it has general tutorials and coverage of interesting npm modules.

Tom Boutell sent in a blog post about OO in JavaScript, called “this” considered harmful (sometimes):

Most JavaScript implementations of “classes” do have certain features in common. They rely on the “this” keyword to refer to the current object; after all, it’s built into the language. They provide a convenience function to implement subclassing, because it’s tricky to get right, especially in older browsers. And they have a really tough time handling callbacks in methods, because “this” ceases to refer to the object you expect.

Tim Oxley posted some comments discussing how to use Function.prototype.bind as well.

Query IndexedDB Like MongoDB

24 Apr 2014 | By Alex Young | Comments | Tags indexeddb storage apis

Kent Safranski sent in Indexed, a library that wraps around IndexedDB with a friendly MongoDB-inspired API.

You can insert objects like this:

  name: 'John Doe'
  email: ''
}, function(err, data) {
  if (err) {
  } else {

And fetch them again with find:

  _id: 28972387982
}, function(err, data) {

You can even use MongoDB-style operators:

  someNumber: { $gt : 25 }
}, function(err, data) {

You’ll probably like this if you work with databases in Node. It’s actually part of a larger project called Riggr, a framework based around RequireJS, Knockout and jQuery. Although I think indexed.js is cool enough that it should be a separate module, rather than being bundled in with Riggr.

Kent wrote a detailed blog post about indexed.js here: Indexed: Query IndexedDB Like Mongo.

Node Roundup: npm-pkgr, Promised Land, Stash.js

23 Apr 2014 | By Alex Young | Comments | Tags node modules npm caching


npm-pkgr (GitHub: vvo / npm-pkgr, License: ISC, npm: npm-pkgr) by Vincent Voyer caches npm install results based on your package.json and npm-shrinkwrap.json files.

Depending on your set up, this should reduce the time taken to deploy Node projects. The basic usage is npm-pkgr instead of npm install, and npm-pkgr --production to use npm-shrinkwrap.json.

Promised Land

Promised Land (GitHub: FredyC / promised-land, License: MIT, npm: promised-land) provides a way of wrapping modules with an EventEmitter that allows you to use promises across your application.

For example, let’s say you’ve got a module that connects to a database. Once the connection is ready, it does this:

var Land = require('promised-land');
Land.emit('database:connected', db);

Any other module that needs to know when the database is ready can now do so with promises:

var Land = require('promised-land');
Land.promise('database:connected').then(function(db) {

It also allows events to be repeated, in a stream-like way:'database:row').onValue(function(val) {

The project has tests and more examples in the readme.


Stash.js (GitHub: tadeuzagallo / stash.js, License: MIT, npm: stash.js) by Tadeu Zagallo is a multilayer cache manager. That means you can define and use different storage systems for caching, based on “drivers”.

So far the author has added a driver for ephemeral storage and localStorage support for browsers.

Cache items have methods for determining cache miss, locking, and setting values:

var stash = new Stash.Pool();
var item = stash.getItem('my/key/path');
var data = item.get();

if (item.isMiss()) {
  data = 'example';
  item.set(data, cacheDuration);

What lock does here is dependent on the cache policy. There are four policies that are explained in the readme.

DOM4 Elements, ng-Fx

22 Apr 2014 | By Alex Young | Comments | Tags libraries dom queryAll

DOM4 Elements

DOM4 Elements (GitHub: barberboy / dom4-elements, License: MIT) by Ben Barber is a polyfill for document.query and document.queryAll, from the DOM Level 4 ParentNode interface.

Using document.queryAll returns a new class called Elements, which extends Array.prototype so you can do things like document.queryAll('.classname').map(fn).

Browser support is documented by Testling, and the project includes a small test suite.


ng-Fx (GitHub: Hendrixer/ng-Fx, License: MIT) by Scott Moss is an AngularJS version of Animate.css.

You can use classes to apply effects, then directives to control their behaviour:

<ul ng-init="foods=['apple', 'chips', 'muffin']">
  <li class='fx-fade-down fx-easing-bounce' ng-repeat="food in foods">

Some options are controlled by classes where I expected to see directives – I think the author has tried to use CSS as much as possible rather than using JavaScript to write out style tags to do the necessary styling. For example: fx-speed-800 compared to ng-fx-speed="800". A hypothetical ng-fx-speed could accept any speed rather than predefined ones.


21 Apr 2014 | By Alex Young | Comments | Tags data-binding mmvm libraries

Ripple.js (GitHub: ripplejs / ripple, License: MIT) from is a library for templating and data binding. It’s based around templates, and has a chainable API, allowing plugins to be added to components:

var Person = ripple('<div>{{name}}</div>')

var person = new Person({
  name: 'Tom'


The plugins can add directives in a similar way to AngularJS: take a look at each, for example.

There’s a JSFiddle Markdown example that uses a template embedded in a script element, and two plugins: and ripple.markdown. The plugins allow changes to be observed on the textarea and Markdown is set to render using a directive on a div element.

One of the features that I like is the pattern for view composition. Views can be embedded, and data will still be synced when it changes.

Also, the library seems well tested, so you can get more usage ideas from the tests.

Live Reloading Chrome Apps, Chrome Extensions with React, sendMessage Tutorial

18 Apr 2014 | By Alex Young | Comments | Tags chrome extensions browsers

Live Reloading Chrome Apps

The Chrome Store itself is a pile of rubbish apps with very few exceptions.

Working with Chrome extensions and apps is pleasant enough in some ways – the JavaScript APIs are generally intuitive, and you can make native-feeling UIs without too much effort. However, the development experience feels a little bit dated and painful in places.

Konstantin Raev sent in Live Reloading Chrome Apps, an article about using Gulp with Chrome apps. It shows how live reloading isn’t as easy as it could be, and how to fix it. There’s also a full example on GitHub: bestander / clock-chrome-app-livereload-example.

Creating Chrome Extensions with React

Brandon Tilley sent in Creating Chrome Extensions with React:

If you’re into client-side web development to any extent, you’ve probably heard of Facebook’s React library. I was working on a Chrome extension, and decided to see how well React fit in to the development I was doing.

He also uses Browserify as well, which I’m interested in because I tried using RequireJS for sharing code between Chrome extensions and Firefox add-ons, and I struggled to get it to work in Firefox. My Firefox add-ons are using the Jetpack SDK rather than the old XUL way.

Passing data around in Chrome extensions

Passing data around in Chrome extensions by Erica Salvaneschi is an introduction to using chrome.runtime.sendMessage and addListener:

We wanted to get data from the current web page and then use it to populate a form that appears in a new window. It was easy to create a context menu item that triggered an event, but sending data based on the current page to the new window wasn’t obvious.

You might find this useful if you’re just getting into Chrome extensions and want more concrete examples than what Google provides.

Browser Synths with Code Studio

17 Apr 2014 | By Alex Young | Comments | Tags node modules audio
Code Studio running polytropon.

Code Studio (GitHub: substack / code-music-studio, License: MIT, npm: code-music-studio) by substack is a tool for “designing musical algorithms”. It provides a browser-based interface that allows you to return functions that manipulate amplitudes. You can experiment and share sounds using, or install it with npm and run it locally.

If you want to find some code to play with, look at substack’s Twitter account, or /-/recent.

The audio API is based on baudio, which works by accepting a function that takes a time value and returns an amplitude value between -1 and 1.

That means you can generate a sound just by running something like this:

return function(t) {
  return sin(441);
  function sin(x) { return Math.sin(2 * Math.PI * t * x); }

That example creates a function called sin that generates values for a given pitch. Code Studio will render an oscilloscope so you can visualise the output as well as hear it. The waveform is rendered using amplitude-viewer, another module by substack that creates graphs with SVG.

If you’re interested in the server-side portion of the code, then take a look at bin/cmd.js. This uses Node’s http module, and ecstatic for static assets.

I think my favourite example so far is polytropon. It has a function called Moog, so you can’t go wrong!

Node Roundup: Do We Need peerDependencies, lazy-install, Time Require

16 Apr 2014 | By Alex Young | Comments | Tags node modules npm benchmarks

Do We Need peerDependencies?

Isaac Schlueter asked this question on Twitter:

Recently, peerDependencies has gotten more and more contentious. Srsly considering deprecation/removal. Thoughts?

The discussion on Twitter and GitHub seems strongly for removing peerDependencies. I agree with it simply because I hate explaining how it works.

Eran Hammer made an interesting point about the idea of a compatibleWith property:

What we need is compatibleWith concept that simply warns you when you are using bad combinations. I think we can rename peerDeps and with some minor adjustment keep the functionality without annoying everyone. Making it a warning sign instead of a blocking feature would remove the “hell” part and those who chose to ignore warnings (as many already do with node versions) can continue to ignore.


If that isn’t enough npm craziness for you, then how about this? lazy-install (GitHub: adamrenklint / lazy-install, License: MIT, npm: lazy-install) by Adam Renklint can be used to install dependencies based on “group” names.

Let’s say you wanted to specify dependencies for your production and test environments. Your package.json could look like this:

  "name": "myProject",
  "lazyDependencies": {
    "server": {
      "express": "4.0.0"
    "test": {
      "mocha": "1.18.2"

Then in your code you can run lazy.install to trigger an npm install with the right options. In fact, the module itself is basically a wrapper around npm.

Time Require

Time Require

How much time did that require take to require? Now you can find out, with time-require! (GitHub: jaguard / time-require, License: MIT, npm: time-require).

It shows the execution time for each module by changing require, and then displaying the elapsed time for each file once the 'exit' event is emitted on the process object.

You can use it by adding a require('time-require') as the first line of your main script.

Responsive SVG with VLEX

15 Apr 2014 | By Alex Young | Comments | Tags responsive vlex


VLEX (GitHub: indus / VLEX, License: MIT) by Stefan Keim is a library for defining the logic necessary to resize SVG images. It works using a vlex attribute that controls how things are resized, and there’s also a VLEX function for initialising and updating elements.

A “vlexpression” contains property descriptions separated by semi-colons. Using a $ allows predefined values to be referenced: $x is element.clientWidth, and $cX is $x / 2 – the horizontal centre. Using a colon allows a value to be set: key:value.

Given those rules, you can centre a circle with cx:{$cX};cy:{$cY}.

Internally it splits the expression with String.prototype.split(';'), and then splits on : to get the keys and values. It’s a fairly simple parser, but it seems small and flexible enough to do get some clever effects using SVG. Take a look at the examples in the readme to see what’s possible.

Reactive X-Tags

14 Apr 2014 | By Alex Young | Comments | Tags elements xtag

Reactive Elements

Here’s a cool idea I haven’t seen before: ReactiveElements with X-Tag. X-Tag is a library from Mozilla that uses JavaScript to provide support for the current W3 Web Components draft. This basically allows modern browsers to use custom elements:

X-Tag allows you to easily create elements to encapsulate common behavior or use existing custom elements to quickly get the behavior you’re looking for.

X-Tag provides several powerful features that streamline element creation such as: Custom events and delegation, mixins, accessors, component lifecycle functions, pseudos and more.

The PixelsCommander / ReactiveElements project by Denis Radin is a small MIT licensed library that builds on X-Tag so you can use it with React.js.

First you create a React component definition:

MyComponent = React.createClass({
  render: function() {
    return <ul><li>React content</li></ul>;

xtag.registerReact('my-react-component', MyComponent);

And then you can use my-react-component in your HTML and see items if it has been specified as an attribute.

I like the idea of combining these two libraries, it has an AngularJS feel while embracing upcoming standards.

The BMEAN Stack and Offline-First Design

11 Apr 2014 | By Daishi Kato | Comments | Tags express node caching
This is a guest post written by Daishi Kato.

Many of you would know the MEAN stack, the software stack consisting of MongoDB, Express, AngularJS and Node. However, the BMEAN stack might be new to you. The B stands for Breeze, a data management library with support for client caching.

The current trend in web development is mobile first design. Recently, the “offline first” approach got attention for contributing toward better mobile user experience. Breeze allows you to develop offline web applications easily thanks to support for querying the client’s cache.

Breeze provides a sample BMEAN application called Zza, but it’s not an offline application. I thought there could be a simpler but more practical application using social-cms-backend.

Social-cms-backend is Express middleware and it demonstrates how to develop a simple Twitter clone in a matter of minutes. I updated social-cms-backend so that it supports Breeze and you don’t have to code the server side logic.

Using the new social-cms-backend and the BMEAN stack, I developed a sample application called notes-app-sample. It’s an offline application with HTML5 cache manifest thanks to connect-cache-manifest.

The usage of the application is pretty straightforward: you write text which will be stored in localStorage. Once you login, you can synchronize data with MongoDB on the server. The login is handled by passport, and currently it works with the Facebook strategy.

The source code of notes-app-sample is available here and the working application is available here.

I hope these sample applications give you some ideas about how to use Breeze with your MEAN apps.

Game Graphics with CutJS

10 Apr 2014 | By Alex Young | Comments | Tags html5 graphics 2d games
CutJS demos and examples.

CutJS (GitHub: piqnt/cutjs, License: MIT) is a new game graphics library by Ali Shakiba. It’s aimed at 2D graphics for cross-browser development, with support for desktop and mobile browsers.

The API is jQuery inspired, but because it works with the Canvas the author has introduced an interesting way of styling elements called “pinning”:

A CutJS app consists of a tree of nodes, each node is pinned (transformed) against its parent and have zero, one or more image cutouts. Image cutouts comes from either image textures or Canvas drawing.

Each rendering cycle consists of ticking and painting the tree. On ticking nodes adjust themselves to recent updates and then on painting each node transforms according to its pinning, pastes its cutouts and then delegates to its children.

Cut “apps” are created by calling Cut with a function, and then textures can be added and manipulated with tween animations and events.

// Create new app
Cut(function(root, container) {
  // Subscribe to Cut.Mouse
  Cut.Mouse(root, container);

  // Set view box
  root.viewbox(500, 300);

  // Create an image node
    // on mouse click on this node
    .on(Cut.Mouse.CLICK, function(ev, point) {
      // Tween scale values of this node
        scaleX: Math.random() + 0.5,
        scaleY: Math.random() + 0.5
      return true;

// Register an image texture
  name: 'base',
  imagePath: 'base.png',
  cutouts: [
    { name: 'box', x: 0, y: 0, width: 30, height: 30 }

There’s a cool Asteroids game example that shows off some of the main features of the library.

Node Roundup: npm and Heartbleed, sipster

09 Apr 2014 | By Alex Young | Comments | Tags node modules npm audio telephony voip

npm and Heartbleed

The npm blog has an article about npm and Heartbleed:

We started patching machines within 30 minutes of the revelation of the bug, and our last vulnerable machine was patched at 7.30am Pacific today.

There has been no evidence so far that our keys were compromised during this period, but nevertheless we are regenerating all our SSL keys anyway and will be rolling them out over the next couple of days (we are very cautious about testing and rolling out new certs since an earlier incident in which we broke a lot of older npm clients while doing so).


Brian White sent in sipster (GitHub: mscdex / sipster, License: MIT, npm: sipster), a pjsip binding for Node. This is the basis for the SIP driver used by Asterisk 12+. He hasn’t yet been able to get a working build environment set up for Windows, but it should work for Unix systems.

Here’s a list of what Brian says it can do so far:

  • Make and receive calls
  • Play either individual or a playlist of wav files (ulaw, alaw, or pcm)
  • Record audio to wav file (ulaw, alaw, or pcm)
  • Hook up audio streams from different calls (e.g. create your own conference or record a mix of streams to wav)
  • Adjust volume levels of audio streams
  • Detect/Send DTMF digits
  • Hold/un-hold
  • Call transfer

The API is event based – for example: call.on('dtmf', cb), and I think the C++ binding is a cool example of a Node native module: src/

AngularJS Localization

08 Apr 2014 | By Alex Young | Comments | Tags ui libraries AngularJS

Sebastian Tschan, also known as blueimp, is the author of the hugely popular jQuery-File-Upload project. It turns out he also writes AngularJS modules. His recent AngularJS project is dedicated to localization, and works well with a Grunt task that builds locales:

By running grunt locales:build you can get a set of JavaScript locale files that can be used to help translate content.

The basic angular-localize directive is used by adding the localize attribute to a tag. The text in the element will be used as the translation key, but you can use localize="key" to specify the key instead, which is useful if the final content hasn’t yet been copy edited.

The localize directive also observes data-* attributes and passes them as objects to translation functions, so data can be inserted into text dynamically.

There’s also a localize service for translating text in your JavaScript code, and there’s even a localizeFactory for creating your own attribute-based localize directives.


07 Apr 2014 | By Alex Young | Comments | Tags frameworks ui libraries microsoft

I haven’t had good experiences with continuous integration systems. They seem to work fine for a few months until they go senile and I have to nuke and reinstall them. Kent Safranski sent in Avow-CI (GitHub: Fluidbyte / avow-ci, License: MIT), an open source CI server that’s built on Node and MongoDB – hopefully this one will be different!

Avow supports Git web hooks, so you can automatically run tests when commits are pushed. It can also be configured to build a specific branch, and allows manual builds to be run.

To add a project to Avow you’ll need to add an avow.json file to the project’s root directory. This describes the build process as an array of tasks. Tasks are run with require('child_process').spawn, so you could technically trigger anything – I’d like to try it with xcodebuild if I have time.

Sometimes I wish CI servers were just cron jobs that check for a non-zero exit code, but I might be able to learn to like a simple RESTful web application if it can run for a few months without exploding. The fact Avow accepts an array of commands to run is nicely simple and flexible, but I’m not sure I like the idea of having to add an avow.json file to my projects.

One thing I like about Avow is the structure of the code: the “models” are just properties on module.exports, and the HTTP routing layer is also super simple. You should take a look if you make Node web applications.

JavaScript OCR

04 Apr 2014 | By Alex Young | Comments | Tags ocr libraries emscripten
What should happen.

Konrad Dzwinel sent in a JavaScript OCR demo. It uses getUserMedia to get images from the camera, glfx.js and JCrop for user-driven image correction, and ocrad.js to handle the character recognition.

The Ocrad.js demo managed to recognise the text in my sample image. I noticed it didn’t work with white on black text – it had to be inverted for the correct text to be recognised.


Ocrad.js is an Emscripten-based translation of Ocrad by Antonio Diaz Diaz. Kevin Kwok, who put together Ocrad.js, also ported GOCR to JavaScript with Emscripten as gocr.js.

GOCR was started by Joerg Schulenburg, but has had other contributors since the original release back in 2000. Kevin compares both libraries and his experiences getting them running in JavaScript:

Anyway, I tried to compile GOCR first and was immediately struck by how easy and painless it had been. I was on a roll, and decided to do Ocrad as well. It wasn’t particularly hard- sure it was slightly more involved but still hardly anything.

He also mentions Tesseract, which is a popular OCR system but also widely known to be very large:

In fact, what’s absolutely stunning is the sheer universality of Tesseract. Just about everything which claims to have text recognition as a feature is backed by it. At one point, I was hoping that Mathematica had some clever routine using morphology and symbolic new kinds of sciences and evolved automata pattern recognition. Nope! Nestled deep within the gigabytes of code lies the Chuck Testa of textadermies: Tesseract.

I thought Konrad’s demo was cool – being able to edit the brightness, contrast, and crop the image was a nice use of client-side technology. However, so far I’ve had the problem Kevin mentioned: occasional blocks of nothing, or seemingly random text, then suddenly excellent results.

Introducing WinJS

03 Apr 2014 | By Alex Young | Comments | Tags frameworks ui libraries microsoft
The WinJS documentation.

WinJS (GitHub: winjs / winjs, License: Apache 2.0) is a new UI-oriented library from Microsoft for developing cross-platform applications with JavaScript.

Microsoft have been pushing WinJS applications for a while as Windows 8 apps that are written with JavaScript instead of what we typically think of as .NET programming languages. This library is a set of UI controls that support desktop and mobile devices, and also some modern JavaScript APIs for things we’ve come to expect: promises, networking, data binding, and templates.

The UI style fits in with Windows 8, and although WinJS applications should run in modern browsers, there’s talk of specific support for Windows Phone 8 and other Microsoft platforms in the future.

There’s an announcement post on the Microsoft News Center:

Today we’re also announcing that Microsoft Open Technologies has brought the Windows Library for JavaScript (WinJS) cross-platform apps and is open sourcing it under the Apache 2.0 license. Find the source code on GitHub. Use this powerful Windows development framework to build high-quality web apps across a variety of browsers and devices beyond Windows, including Chrome, Firefox, Android, and iOS.

I’ve been running examples on to get a feel for the API style, and it makes heavy use of promises and traditional OO wrappers:

WinJS.Binding.processAll(document.querySelector('#basicBindingOutput'), bindingSource)
  .done(function() {
    WinJS.log && WinJS.log('Binding wireup complete', 'sample', 'status');

Some corners of the UI widgets still need aesthetic attention – the date and time pickers don’t look particularly great on Chrome on my Mac. But the APIs seem consistent and similar to other popular open source projects.

If you’re looking to make Windows 8-style applications and love JavaScript, then this is definitely worth following. The added benefit is you can run these web apps in non-Microsoft browsers as well.

Node Roundup: Money and npm, Isaac Schlueter Interview, KOAN

02 Apr 2014 | By Alex Young | Comments | Tags node modules realtime npm

Nebulous Profit Meditations

Isaac Schlueter wrote a long article on the npm blog about how npm Inc. will make money. It has some hints about the future of advertising on npm:

In my opinion, a good example of advertising done very well is the hosting page on The services offered are beneficial to WordPress users, and are offered in such a way as to avoid distracting from the core product. The focused curation increases the value, and provides a strong incentive for the advertised products to maintain their quality or risk losing their position. We will be pursuing similarly focused and curated advertising partnerships on the npm website, in ways that benefit our users as well as our technology partners.

And GitHub’s influence:

When I describe our plans to people, they often nod and say, “Oh, the GitHub model, ok.” I’m sure that “public for free, private costs money” isn’t new with GitHub. However, pursuing that kind of model, while at the same time acknowledging that coding is a social activity, really was a master stroke in the history of software development. I’m very thankful that they’ve helped pave the way for people to recognize this pattern.

Meet the Face Behind npm

The Modulus hosting company blog has an interview with Isaac, with some history prior to Node and npm:

At Yahoo!, I grew increasingly frustrated that I had to switch back and forth between PHP and JavaScript, and Google had just open sourced their V8 engine, so I started trying to seriously get into doing JavaScript on the server. I got involved with the K7 project, and started studying web servers in more detail. There was also SpiderApe, and v8cgi, and a bunch of other projects. Narwhal caught my eye, and I spent a bunch of time messing with that.

I seem to remember making IRC bots with Rhino and Java sockets, then Node came along and changed everything!


KOAN (GitHub: soygul / koan) by Teoman Soygul is a full stack boilerplate that uses Koa, AngularJS, Node, and MongoDB. Unlike other similar projects, this one has WebSocket features baked in.

A KOAN app uses JSON-RPC for syncing data with the server, and the readme has details on how to deploy this to Heroku (using labs:enable websockets).

jQuery 1.11.1, 2.1.1, PositionCalculator, YModules

01 Apr 2014 | By Alex Young | Comments | Tags jquery plugins module-loaders

jQuery 1.11.1 Beta 1 and 2.1.1 Beta 1 Released

New jQuery betas are out. These are maintenance releases with bug fixes, including a tweak that helps create builds with custom names, so you can use a different name in AMD loaders like RequireJS.


PositionCalculator (GitHub: tlindig / position-calculator, License: MIT) by Tobias Lindig is a jQuery UI Position replacement:

This plugin will not manipulate any CSS settings or DOM-trees, it only calculate values. To be more exact, it calculates the difference of current position to target position and the overflow over boundary. Thus you are all paths open to implement the positioning according to your requirements. You can apply the new position by using top and left or using the css3 transform function or by setting margin. It is up to you.


Vladimir Varankin sent in YModules (GitHub: ymaps / modules) by Dmitry Filatov is an asynchronous modular loading system that works with Node and browsers.

The syntax looks like this:

  function(provide, loader) {

  loader('//', function() {

  function(provide, $) {
    function MyModule() { /* do something here */ }

modules.require('my-module', function(MyModule) {
  // `MyModule` will be available here after
  // Its dependencies will be resolved and its `provide` will fire.

It has a feature that allows existing modules to be redeclared, which can help with component-based libraries:

modules.define('button', function(provide) {
    function Button() { /* our button's constructor */ });
    Button.prototype.doAction = function() {};


// on the end user's space we could redefine the same Button
modules.define('button', ['jquery'], function(provide, $, Button) {
  // We're declaring the same module "button",
  // so we have an access to the module's previous definition
  // through the last define's argument (`Button` here), which
  // is appended automatically and known as "previousModuleDeclaration"
  Button.prototype.doAnOtherAction = function() {};

modules.require('button', function(Button) {

Building a Node OAuth2 Server

31 Mar 2014 | By Alex Young | Comments | Tags node oauth2 authentication

Most of you have probably written an OAuth2 client using Node. I’ve used the passport module for Express and found it worked very nicely. But what about creating an OAuth2 server?

Writing a server takes more work, but as long as you’re clear about the authorisation flows that you want to use then it’s certainly possible. Erica Salvaneschi wrote Building a Node OAuth2 server, a post about our experiences building an OAuth2 service for a commercial project we’re working on at Papers:

This article is a walkthrough of Papers’ test-driven implementation of an OAuth server using Node. We decided to go for what’s known as resource owner password flow and chose node-oauth2-server to build our server.

The sample code was written using test-driven development, and depends on Express, Mongoose, bcrypt, and Mocha and SuperAgent for testing. We’ve kept the issues open on the sample code so you can give us feedback, which we’re interested in seeing as we’re new to OAuth2.