<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>by Pedro Teixeira</description><title>Metaduck</title><generator>Tumblr (3.0; @metaduck)</generator><link>http://metaduck.com/</link><item><title>The Module Pattern and Inheritance: A Better Way</title><description>&lt;p&gt;Recently &lt;a href="http://metaduck.com/post/11734854536/dump-this-and-prototype"&gt;I blogged&lt;/a&gt; about how I like to build my JavaScript &amp;#8220;classes&amp;#8221;. I personally prefer the module pattern: it provides true encapsulation and doesn&amp;#8217;t expose unnecessary methods and properties, which you get when you use the typical prototype pattern.&lt;/p&gt;

&lt;p&gt;One of the downsides of it, I&amp;#8217;ve been told, is that it doesn&amp;#8217;t easily allow to build classes that you can inherit from. That is true if you mix the styles, specially if you want to inherit from a class that is built this way. But if you are willing to use this technique throughout all the inheritance chain, I will demonstrate that it provides a much more powerful and sane way of doing inheritance.&lt;/p&gt;

&lt;p&gt;One of the fallacies of using inheritance in JavaScript in the typical prototypical way - and in the model of most OO programming languages I know - is that inheritance, as it is, is a leaky abstraction. Most of the time you have to be aware of some of the implementation details of the super class to be able to inherit from it properly. For instance, since the entire prototypical chain uses the object that is bound to &lt;code&gt;this&lt;/code&gt;, you have to be careful that you don&amp;#8217;t override any of the properties that are being used down the chain.&lt;/p&gt;

&lt;p&gt;For instance, if you are inheriting from Node.js EventEmitter pseudo-class, you have to be careful to never override any of the properties it initializes and changes.&lt;/p&gt;

&lt;p&gt;Let me give you an example of where this fails:&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s say you have an Animal class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Animal() {
  this.walked = false;
}

Animal.prototype.walk = function walk() {
  console.log('walking...')
  this.walked = true
}

Animal.prototype.hasBeenWalked = function hasBeenWalked() {
  return this.walked
}

module.exports = Animal
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And let&amp;#8217;s say you want to inherit from it. If you save the previous module into a local file named &amp;#8220;animal.js&amp;#8221;, you can then inherit from it and build a Cat specialization like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var Animal = require('./animal')
  , inherits     = require('util').inherits
  ;

function Cat() {
  Animal.call(this);
}

inherits(Cat, Animal);

Cat.prototype.pat = function pat() {
  console.log('purr');
};

Cat.prototype.lasagna = function() {
  console.log('lasagna!');
  this.walked = true;
};

module.exports = Cat;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I introduced an error here: the Cat.prototype.lasagna method sets a the &lt;code&gt;this.walked&lt;/code&gt; property to true. Now if you use this cat class and don&amp;#8217;t call the lasagna method, it all works fine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; var Cat = require('./cat')
undefined
&amp;gt; var garfield = new Cat()
undefined
&amp;gt; garfield.hasBeenWalked()
false
&amp;gt; garfield.walk()
walking...
undefined
&amp;gt; garfield.hasBeenWalked()
true
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But if you call the lasagna method, it all goes wrong:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; var Cat = require('./cat')
undefined
&amp;gt; var garfield =new Cat()
undefined
&amp;gt; garfield.hasBeenWalked()
false
&amp;gt; garfield.lasagna()
lasagna!
undefined
&amp;gt; garfield.hasBeenWalked()
true
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This happens because the cat object is being used like a property global namespace for storing all and every property of this object. Global namespaces tend to become overcrowded and clashes happen if there is no alternative.&lt;/p&gt;

&lt;p&gt;Fortunately, there is an alternative.&lt;/p&gt;

&lt;h2&gt;Using the Module Pattern&lt;/h2&gt;

&lt;p&gt;Let&amp;#8217;s do the previous example using the module pattern:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Animal() {

  var walked = false

  function walk() {
    console.log('walking...')
    walked = true
  }

  function hasBeenWalked() {
    return walked
  }

  return {
    walk: walk
  , hasBeenWalked: hasBeenWalked
  }
}

module.exports = Animal
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now that we have an Animal class, let&amp;#8217;s build the Cat one:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var Animal = require('./animall')

function Cat() {
  var cat = {}
  var walked = false

  cat.__proto__ = Animal()

  cat.pat = function pat() {
    console.log('being patted')
  }

  cat.lasagna = function lasagna() {
    console.log('Lasagna!')
    walked = true
  }

  return cat
}

module.exports = Cat
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, if you instantiate a Garfield and then invoke the mischieving lasagna method, it all still works:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; var Cat = require('./cat')
undefined
&amp;gt; var garfield = Cat()
undefined
&amp;gt; garfield.hasBeenWalked()
false
&amp;gt; garfield.lasagna()
Lasagna!
undefined
&amp;gt; garfield.hasBeenWalked()
false
&amp;gt; garfield.walk()
walking...
undefined
&amp;gt; garfield.hasBeenWalked()
true
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, in this case, for every object instance you actually have two separate objects: the animal object and the cat object.&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s like our brains: the lizzard brain, the mammal brain and the human brain. They&amp;#8217;re all layered on top of each other, overriding the lower parts, but they do not use the same space.&lt;/p&gt;</description><link>http://metaduck.com/post/23920791086</link><guid>http://metaduck.com/post/23920791086</guid><pubDate>Mon, 28 May 2012 10:01:00 +0100</pubDate></item><item><title>Some JavaScript Functional Sugar</title><description>&lt;p&gt;I used to do a lot of Ruby, and now I&amp;#8217;m doing only JavaScript. I really like Node and JavaScript, but since I&amp;#8217;m lazy, I miss some of the niceties of the Ruby language. One of these niceties is that you can use a method reference when iterating over an Enumeration.&lt;/p&gt;

&lt;p&gt;For instance, if you had a collection of User objects, you can extract all the name attributes by using:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;users.map( &amp;amp;:name )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I recently realized that we can have a similar solution in JavaScript that I think is even more elegant:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function prop(propName) {
  return function(obj) {
    return obj [propName ];
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you can use this prop function as the property accessor shortcut:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;users.map( prop('name') );
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hurray JavaScript!&lt;/p&gt;</description><link>http://metaduck.com/post/22833289460</link><guid>http://metaduck.com/post/22833289460</guid><pubDate>Fri, 11 May 2012 09:49:15 +0100</pubDate></item><item><title>Transcript:

Some two and a half years ago a friend told me...</title><description>&lt;iframe src="http://player.vimeo.com/video/40516392" width="400" height="300" frameborder="0"&gt;&lt;/iframe&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;&lt;strong&gt;Transcript:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Some two and a half years ago a friend told me about Node.js. “It’s JavaScript on the server, and it’s making a buzz, you should totally check it out”. At the time I was doing Ruby dev work. I knew JavaScript, I kind of liked it, so I gave it a try.&lt;/p&gt;

&lt;p&gt;Downloaded node, installed it, did my first “hello world” script in 20 seconds, and bam! I had coded an HTTP server. No fluff code, no boilerplate. And it really performed well! I was immediately hooked.&lt;/p&gt;

&lt;p&gt;I submitted a talk proposal about it for the following Codebits conference (which is an amazing conference that is held in Lisbon about all things computer-related). It was about Node internals. I had played with event-driven systems using Event Machine in Ruby land, and I wanted to know more about how it worked internally. I learned about the event loop, ticks, callback dispatching, asynchronous I/O, the thread pool, the works. The talk got accepted and I kept learning.&lt;/p&gt;

&lt;p&gt;At the time I didn’t have any devent source of learning material, the best thing around were the Node API docs, which were a bit scarce - I found myself digging into the source code a lot. I then started doing some screencast tutorials, and I started each one with the desire to learn about a certain subject.&lt;/p&gt;

&lt;p&gt;Then a friend of mine challendged me to write something about Node.js in the form of a book. I followed the lead and started doing just that. Some frantic writing and some long nights after I had a english-challenged piece of text that I started selling.&lt;/p&gt;

&lt;p&gt;Then I decided to go to jsconf.eu. I had watched almost all the available video material, all the epic moments: Douglas Crockford saying IE must die, the Socket.io presentation, Ryan Dahl announcing Node.js. I wanted to experience it.&lt;/p&gt;

&lt;p&gt;I arrived at the conference, and just before the first talk I introduced myself to Marak Squires from Nodejitsu and asked him something something about his hook.io project. Immediately he said “let’s go grab a coffee and I’ll just show how to do it in my laptop”. And he did, just then and there. I continuously kept having great conversations with great people in the community. The talks were amazing too, track A and track B was great. And sometimes I just remained talking with some people in “track C”. And then out for drinks. Not much sleep. And then more talks.&lt;/p&gt;

&lt;p&gt;Wfter I came back home I just kept talking about the whole experience to my family and friends over and over.&lt;/p&gt;

&lt;p&gt;I was simply amazed by the friendlyness and talent of the JavaScript community.&lt;/p&gt;

&lt;p&gt;Traveling and going to conferences is expensive. “I wish we had something like this back in Portugal” - I thought.&lt;/p&gt;

&lt;p&gt;Me, Nuno, Tiago, Bruno, Heitor and Luis started putting this conference together, and quickly learned that putting conferences is two things: hard and expensive. We’ve learned a lot and will most surely learn a lot during the days that lead to the conference, but we want to put out a great experience for the attendees, the speakers and the sponsors.&lt;/p&gt;

&lt;p&gt;We’ve got a bunch of great speakers lined up, most of them coming from far away places just to speak to us. If you’re in Portugal you shouldn’t miss this. If you’re not in Portugal, you should come here. Lisbon is such a great city, and again, the speakers we have lined up are amazing.&lt;/p&gt;</description><link>http://metaduck.com/post/21267356021</link><guid>http://metaduck.com/post/21267356021</guid><pubDate>Tue, 17 Apr 2012 14:58:00 +0100</pubDate><category>nodejs</category><category>javascript</category><category>conferences</category><category>node.js</category></item><item><title>Banzai - Document Processing Pipelines in Node.js</title><description>&lt;p&gt;&lt;a href="https://github.com/pgte/banzai"&gt;Banzai&lt;/a&gt; is a document processing framework for Node.js.&lt;/p&gt;

&lt;p&gt;You define a set of pipelines into which you push documents. Each document in a pipeline has a given state. A state transition triggers a state entry handler that can transform the document and interact with the outside world. The documents ends in a defined or in an &amp;#8220;error&amp;#8221; state.&lt;/p&gt;

&lt;h2&gt;Rollback and Playback&lt;/h2&gt;

&lt;p&gt;You can roll-back the state of a document to a certain previous state, and playback the pipeline flow. This can be useful, for instance, if a given document enters an error state because of a bug or a networking problem somewhere. You can correct the bug, roll-back to a previous state and play the pipeline from thereon, hopefully escaping that error condition.&lt;/p&gt;

&lt;p&gt;Each state transition has a &amp;#8220;next state&amp;#8221;, a priority and a optional pre-condition. The candidate transitions (there can be more than one) are evaluated in the given priority, and if there is a pre-condition, it is evaluated, and if there is a match, the corresponding state transition handler is triggered.&lt;/p&gt;

&lt;p&gt;Each state transition can have an &amp;#8220;undo handler&amp;#8221;, that takes care of undoing the document. This can be useful if external services were changed and you need to revert those changes when you revert a transition.&lt;/p&gt;

&lt;h2&gt;All JavaScript&lt;/h2&gt;

&lt;p&gt;The state transition handlers and the pre-conditions are all defined in JavaScript and are asynchronous, meaning that you can perform I/O inside them.
The pipeline definition is also written in JavaScript.&lt;/p&gt;

&lt;h2&gt;Architecture&lt;/h2&gt;

&lt;p&gt;A Banzai deployment has 4 main components: the document store, the state store, the workers and the work queue.&lt;/p&gt;

&lt;h3&gt;The Document Store&lt;/h3&gt;

&lt;p&gt;The document store is where - you guessed it - the documents are stored. The document is retrieved when entering a state transition, passed into the state transition handler and saved when the handler is done. This way a state transition can be picked by any worker and the document is always persisted, surviving failures.&lt;/p&gt;

&lt;h3&gt;State Store&lt;/h3&gt;

&lt;p&gt;The state store is where the state for each document transitioning or that has transitioned a pipeline is stored. There you can also find some additional meta-data, like all the transitions that occurred and their start and end times plus some meta-data that the state transitions can save.&lt;/p&gt;

&lt;h3&gt;Workers&lt;/h3&gt;

&lt;p&gt;Workers are processes that are listening for state transitions and that pick up the work of invoking the state transition handler and deciding the next state.&lt;/p&gt;

&lt;h3&gt;Work Queue&lt;/h3&gt;

&lt;p&gt;The Work Queue is an event queue that persists and distributes the transitions to be picked up by the workers.&lt;/p&gt;

&lt;h2&gt;Adapters&lt;/h2&gt;

&lt;h3&gt;Doc Store and State Store&lt;/h3&gt;

&lt;p&gt;Currently the only supported database is CouchDB, but technically any document database is supported. It should, by the way, store every version of the documents (as CouchDB does) if you want to be able to roll-back to certain versions of the documents.&lt;/p&gt;

&lt;p&gt;The module for supporting CouchDB is &lt;a href="https://github.com/pgte/banzai-couchdb-store"&gt;banzai-couchdb-store&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Queue&lt;/h3&gt;

&lt;p&gt;Currently we support Redis (any version &amp;gt;= 2.1.7) if you use the &lt;a href="https://github.com/pgte/banzai-redis"&gt;banzai-redis&lt;/a&gt; module, but 
any queueing system that allows the same semantics should work.&lt;/p&gt;

&lt;h3&gt;Show me the code!&lt;/h3&gt;

&lt;p&gt;Check out &lt;a href="https://github.com/pgte/banzai/blob/master/README.md"&gt;the project README&lt;/a&gt;.&lt;/p&gt;</description><link>http://metaduck.com/post/13942856644</link><guid>http://metaduck.com/post/13942856644</guid><pubDate>Fri, 09 Dec 2011 00:14:00 +0000</pubDate><category>node.js</category><category>javascript</category><category>couchdb</category></item><item><title>Dump "this" and "prototype"</title><description>&lt;h2&gt;(How I like to build classes in Javascript)&lt;/h2&gt;

&lt;p&gt;When developing server-side Javascript for Node.js, generally I tend to encapsulate classes inside CommonJS modules and expose the constructor function as module itself.&lt;/p&gt;

&lt;p&gt;As an incomplete example of how I used to do it, let’s build a module that exposes a rectangle class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Rectangle(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

Rectangle.prototype.area = function() {
  return this.width * this.height;
};

module.exports = Rectangle;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s say you save this module under the name “rectangle.js”, on the current directory.&lt;/p&gt;

&lt;p&gt;Then, to instantiate a rectangle you must do:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var Rectangle = require('./rectangle');
var rectangle = new Rectangle(1,2,3,4);
rectangle.area(); // -&amp;gt; 12
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All is fine and dandy, right?&lt;/p&gt;

&lt;p&gt;Nope. This way you can tamper with the rectangle object, changing properties and even overriding functions. I think this is not a major problem, but exposes a major design flaw, which I’ll cover later.&lt;/p&gt;

&lt;p&gt;Now you want to add a private function. You have two main options: 1) add it as a function on the module scope or 2) add it as a function on the Rectangle.prototype object, but giving it an underscore so everyone knows they shouldn’t be calling.&lt;/p&gt;

&lt;p&gt;Lets’ say for the purpose of the example, that you want to add a provate function named “coalesce”, which you want to call after the constructor.&lt;/p&gt;

&lt;h2&gt;1) Add it to the module scope&lt;/h2&gt;

&lt;pre&gt;&lt;code&gt;function coalesce() {
  var self = this;
  ['x', 'y', 'width', 'height'].forEach(function(prop) {
    if (!self[prop]) { self[prop] = 0; }
  });
}

function Rectangle(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
  coalesce.apply(this);
}

Rectangle.prototype.area = function() {
  return this.width * this.height;
};

module.exports = Rectangle;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we can see the constructor calling the “coalesce” function using the function.apply(), which sets the “this” scope, which then the coalesce function can use as the object.&lt;/p&gt;

&lt;h2&gt;2) Add it as a function on the Rectangle.prototype&lt;/h2&gt;

&lt;pre&gt;&lt;code&gt;function Rectangle(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
  this._coalesce();
}

Rectangle.prototype.area = function() {
  return this.width * this.height;
};

Rectangle.prototype._coalesce = function() {
  var self = this;
  ['x', 'y', 'width', 'height'].forEach(function(prop) {
    if (!self[prop]) { self[prop] = 0; }
  });
};

module.exports = Rectangle;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This way is simpler, but we’re exposing the coalesce function, which is ugly.&lt;/p&gt;

&lt;h2&gt;The problem&lt;/h2&gt;

&lt;p&gt;As I said earlier, this pattern exposes the methods and the data on the rectangle object.&lt;/p&gt;

&lt;p&gt;The ultimate goal would be to expose the methods and encapsulate the data. How can we do that?&lt;/p&gt;

&lt;p&gt;Here is a solution I like to use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Rectangle(x, y, width, height) {

  function area() {
    return width * height;
  };

  function coalesce() {
    if (! x) { x = 0; }
    if (! y) { y = 0; }
    if (! width) { width = 0; }
    if (! height) { height = 0; }
  }

  coalesce();
  return {
    area: area
  };
}

module.exports = Rectangle;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And a client of this module would look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var Rectangle = require('./rectangle');
var rectangle = Rectangle(undefined, undefined, 3, 4);
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;What have we done here?&lt;/h2&gt;

&lt;p&gt;The constructor simply returns an object that has the methods we want to expose. The data is encapsulated inside the constructor function, which also contains all the functions (private and public) that have privileged access to these.&lt;/p&gt;

&lt;p&gt;Then we’re dropping the using of “new” notation on the class clients (which could cause a lot of problems on the previous model if module clients omitted it).&lt;/p&gt;

&lt;p&gt;This pattern also allows for object methods (private or public) to call each other with no restraints, since we are not relying on the leaky this object.&lt;/p&gt;

&lt;h2&gt;What about inheritance?&lt;/h2&gt;

&lt;p&gt;A useful way of declaring that a class (or pseudo-class, if you will) inherits from another one is having the constructor prototype pointing to an object that it “inherits” behavior from. Node (and almost all the Javascript frameworks) has convenience function for doing this in util.inherit().&lt;/p&gt;

&lt;p&gt;For instance, say you want our Rectangle class (as in our first incarnation) inheriting from the Node EventEmitter class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var inherit = require('util').inherit
  , EventEmitter = require('events').EventEmitter;

function Rectangle(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

inherit(Rectangle, EventEmitter);

Rectangle.prototype.area = function() {
  return this.width * this.height;
};

module.exports = Rectangle;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Convenient, heh? (You must be careful to call inherit before setting the prototype properties, or else they will be nuked).
How can we then implement inheritance if we’re not using the tradicional Javascript constructor functions?&lt;/p&gt;

&lt;p&gt;Here is a way:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var EventEmitter = require('events').EventEmitter;

function Rectangle(x, y, width, height) {
  var that;

  function area() {
    return width * height;
  };

  function coalesce() {
    if (! x) { x = 0; }
    if (! y) { y = 0; }
    if (! width) { width = 0; }
    if (! height) { height = 0; }
  }

  coalesce();

  that = {
    area: area
  };

  that.__proto__ = EventEmitter.prototype;

  return that;
}

module.exports = Rectangle;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, we’re using the __proto__ object, which is reserved in Javascript for the actual prototype object. So if you call any EventEmitter-specific methods like on() and emit(), the runtime will look into the rectangle object, and if not found, will search inside the prototype chain.&lt;/p&gt;

&lt;p&gt;Mind you that the __proto__ object is not entirely portable to all Javascript platforms and browsers, but there are ways around that.&lt;/p&gt;</description><link>http://metaduck.com/post/11734854536</link><guid>http://metaduck.com/post/11734854536</guid><pubDate>Fri, 21 Oct 2011 17:01:00 +0100</pubDate><category>javascript</category><category>node.js</category></item><item><title>"Javascript classes, prototypes and closures". Latest 28 Node Tuts screencast is out.</title><description>&lt;a href="http://nodetuts.com/tutorials/28-javascript-classes-prototypes-and-closures.html#video"&gt;"Javascript classes, prototypes and closures". Latest 28 Node Tuts screencast is out.&lt;/a&gt;</description><link>http://metaduck.com/post/10685330318</link><guid>http://metaduck.com/post/10685330318</guid><pubDate>Mon, 26 Sep 2011 13:47:33 +0100</pubDate><category>node.js</category></item><item><title>HTTP Mocking made easy with nock</title><description>&lt;p&gt;I love testing and I love small easily testable modules in Node.&lt;/p&gt;
&lt;p&gt;Recently I had to build a library module that interacts with some web services via HTTP.&lt;/p&gt;
&lt;p&gt;To test this module as it was would mean that I would have to have a sandboxed account on the other end. I also would have to have setup and teardown routines that would reset the sandbox to a known state, etc, etc.&lt;/p&gt;
&lt;p&gt;What I really wanted for the unit tests was to test the module in isolation. In this case, it would mean capturing the HTTP requests and replying a pre-made response.&lt;/p&gt;
&lt;p&gt;Enter &lt;a title="nock" href="https://github.com/pgte/nock"&gt;nock&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Nock is an HTTP mocking and expectations library for Node.js&lt;/p&gt;
&lt;p&gt;With Nock you can easily mock a GET request:&lt;/p&gt;
&lt;p&gt;&lt;span&gt; &lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var nock = require('nock');

var scope = nock('http://myapp.iriscouch.com')
                .get('/users/1')
                .reply(200, {_id: "123ABC", _rev: "946B7D1C", username: 'pgte', email: 'pedro.teixeira@gmail.com'});&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or a POST request with a specified body (string or json-encoded object):&lt;/p&gt;
&lt;p&gt;&lt;span&gt; &lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var scope = nock('http://myapp.iriscouch.com')
                .post('/users', {username: 'pgte', email: 'pedro.teixeira@gmail.com'})
                .reply(201, {ok: true, id: "123ABC", rev: "946B7D1C"});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or a PUT or a DELETE in the same fashion.&lt;/p&gt;
&lt;p&gt;You can also specify the response as a string:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var scope = nock('http://api.app.com')
                .post('/users', {username: 'pgte', email: 'pedro.teixeira@gmail.com'})
                .reply(201, "OK");
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or as a JSON-encoded object:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var scope = nock('http://api.app.com')
                .post('/users', {username: 'pgte', email: 'pedro.teixeira@gmail.com'})
                .reply(201, {ok: true, _id: "abcdef", _rev: "1234"});&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or from the contents of a file: &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var scope = nock('http://api.app.com')
                .post('/users', {username: 'pgte', email: 'pedro.teixeira@gmail.com'})
                .replyWithFile(201, __dirname + '/assets/reply.json');&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Filtering paths and bodies&lt;/h2&gt;
&lt;p&gt;If you have time-dependent or random data you want to filter out from the request path or body, you can use a regular expression, much like String.prototype.replace:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var scope = nock('http://api.app.com')
                .filterPath(/timestamp=[^&amp;amp;]*/g, '')
                .post('/users', {username: 'pgte', email: 'pedro.teixeira@gmail.com'})
                .replyWithFile(201, __dirname + '/assets/reply.json');&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;.filterPath() also accepts a function as sole argument. That function should return the filtered path.&lt;/p&gt;
&lt;p&gt;As said, Nock also supports request body filtering much the same way it does with path filtering. Just use .filterRequestBody like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var scope = nock('http://api.app.com')
                .filterRequestBody(/timestamp=[^&amp;amp;]*/g, '')
                .post('/users', {username: 'pgte', email: 'pedro.teixeira@gmail.com'})
                .replyWithFile(201, __dirname + '/assets/reply.json');&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or even with a function as the only argument.&lt;/p&gt;
&lt;h2&gt;Expectations&lt;/h2&gt;
&lt;p&gt;When a scope is defined Nock intercepts every HTTP request being made in that process to that host. If a match is not found - Nock matches verb, path and body - an exception is raised.&lt;/p&gt;
&lt;p&gt;When a mocking match is found, Nock removes that match.&lt;/p&gt;
&lt;p&gt;At the end of the test, if you wish to test that all the expected calls were made, you can use&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&lt;span&gt; &lt;/span&gt;scope.done();&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;and a detailed exception will be thrown if some expectations were not met.&lt;/p&gt;
&lt;h2&gt;Feedback&lt;/h2&gt;
&lt;p&gt;I hope this module makes testing easier for you.&lt;/p&gt;
&lt;p&gt;Feedback with suggestions is welcome!&lt;/p&gt;</description><link>http://metaduck.com/post/10553872399</link><guid>http://metaduck.com/post/10553872399</guid><pubDate>Fri, 23 Sep 2011 12:43:00 +0100</pubDate><category>node.js</category></item><item><title>Configuration files in Node.js made easy with Konphyg</title><description>&lt;p&gt;Configuration is always a chore, a simple thing you have to do, and keep reinventing every time you start a new project.&lt;/p&gt;
&lt;p&gt;I usually have the following setup:&lt;/p&gt;
&lt;p&gt;I have one configuration file per domain and several domains. A domain may be &amp;#8220;www&amp;#8221;, &amp;#8220;couchdb&amp;#8221; or a remote service that requires some parametrization like Postmark.&lt;/p&gt;
&lt;p&gt;These are JSON files that lie in some directory.&lt;/p&gt;
&lt;p&gt;Now, I want to be able to override them for each environment the application works on. I may have a &amp;#8220;development&amp;#8221; environment, a &amp;#8220;test&amp;#8221; environment, a &amp;#8220;staging&amp;#8221; environment and a &amp;#8220;production&amp;#8221; environment. I may even have different development environment configurations depending on the developer.&lt;/p&gt;
&lt;p&gt;I want, for each of these environments, to be able to slightly tweak each configuration for some domains. For instance, I use localhost for Redis in my development environment, but redis.hostname.com in my production one. I want to be able to just specify the differences, not the whole configuration again, because soon that starts to be unmaintainable.&lt;/p&gt;
&lt;p&gt;Looks simple, right? I searched through some existing Node.js modules that manage configuration, and had none that answered these requirements.&lt;/p&gt;
&lt;p&gt;So I came up with &lt;a title="Konphyg" href="https://github.com/pgte/konphyg"&gt;Konphyg&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;&lt;span&gt;Installing&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;$ npm install konphyg&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;Using&lt;/h2&gt;
&lt;p&gt;First you import konphyg and give it a source dir like this:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;var config = require('konphyg')(__dirname + "/config");&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Then you create the &amp;#8220;config&amp;#8221; dir and put a configuration file for each domain. For instance, for the &amp;#8220;postmark&amp;#8221; domain, I can have:&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;{&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;    "host": "api.postmarkapp.com"&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;  , "ssl": false&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;  , "api_key": "myapikey"&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;I place this file inside the &amp;#8220;config&amp;#8221; dir and name it &amp;#8220;postmark.json&amp;#8221;.&lt;/p&gt;
&lt;p&gt;Now, for my development environment I need to specify my API key. So, inside the config dir I place the file &amp;#8220;postmark.development.json&amp;#8221; with just this:&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;{&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;    "api_key": "ABCDEFGHI"&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Then, on my Node code, if I do:&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&lt;span&gt; &lt;/span&gt;console.log(config("postmark"));&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;I get:&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;{&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;    "host": "api.postmarkapp.com"&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;  , "ssl": false&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&lt;span&gt;  , "api_key": "&lt;/span&gt;ABCDEFGHI&lt;span&gt;"&lt;/span&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Simple, right?&lt;br/&gt;Konphyg can also handle deep object nesting in your configuration file, and it will correctly merge the environment-specific configuration with the base one.&lt;br/&gt;Konphyg uses the NODE_ENV environment variable to determine the environment. If not present, it defaults to &amp;#8220;development&amp;#8221;.&lt;/p&gt;</description><link>http://metaduck.com/post/10514524808</link><guid>http://metaduck.com/post/10514524808</guid><pubDate>Thu, 22 Sep 2011 10:32:00 +0100</pubDate><category>node.js</category></item><item><title>Job queue using Node.js, Redis and Kue</title><description>&lt;a href="http://nodetuts.com/tutorials/27-kue-jobs.html#video"&gt;Job queue using Node.js, Redis and Kue&lt;/a&gt;</description><link>http://metaduck.com/post/8132889829</link><guid>http://metaduck.com/post/8132889829</guid><pubDate>Wed, 27 Jul 2011 17:47:01 +0100</pubDate><category>node.js</category></item><item><title>Latest Node Tuts is out: "Starting with everyauth"</title><description>&lt;a href="http://nodetuts.com/tutorials/26-starting-with-everyauth.html#video"&gt;Latest Node Tuts is out: "Starting with everyauth"&lt;/a&gt;</description><link>http://metaduck.com/post/7757842847</link><guid>http://metaduck.com/post/7757842847</guid><pubDate>Mon, 18 Jul 2011 11:00:30 +0100</pubDate><category>javascript,</category><category>programming,</category><category>node.js</category><category>screencast</category></item><item><title>Hands-on Node.js e-book</title><description>&lt;a href="http://nodetuts.com/handson-nodejs-book.html"&gt;Hands-on Node.js e-book&lt;/a&gt;</description><link>http://metaduck.com/post/5214681751</link><guid>http://metaduck.com/post/5214681751</guid><pubDate>Thu, 05 May 2011 10:24:00 +0100</pubDate><category>node.js</category></item><item><title>teamcoco:

The Kills - “Pull U A” (Backstage @ CONAN)
</title><description>&lt;object width="400" height="275" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="ep"&gt;&lt;param name="allowfullscreen" value="true" /&gt;&lt;param name="allowscriptaccess" value="always" /&gt;&lt;param name="movie" value="http://i.cdn.turner.com/tegwebapps/tbs/tbs-www/cvp/teamcoco_dynamic_embed.swf?context=teamcoco_embed_offsite&amp;videoId=248986" /&gt;&lt;param name="bgcolor" value="#000000" /&gt;&lt;embed src="http://i.cdn.turner.com/tegwebapps/tbs/tbs-www/cvp/teamcoco_dynamic_embed.swf?context=teamcoco_embed_offsite&amp;videoId=248986" type="application/x-shockwave-flash" bgcolor="#000000" allowfullscreen="true" allowscriptaccess="always" width="400" height="275"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;&lt;a href="http://teamcoco.tumblr.com/post/4637611739"&gt;teamcoco&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The Kills - “Pull U A” (Backstage @ CONAN)&lt;/p&gt;
&lt;/blockquote&gt;</description><link>http://metaduck.com/post/4778083592</link><guid>http://metaduck.com/post/4778083592</guid><pubDate>Wed, 20 Apr 2011 16:37:44 +0100</pubDate></item><item><title>Freezing and bundling your dependencies with node 0.4 (video screencast)</title><description>&lt;a href="http://nodetuts.com/tutorials/22-freezing-and-bundling-your-dependencies-with-node-04.html"&gt;Freezing and bundling your dependencies with node 0.4 (video screencast)&lt;/a&gt;</description><link>http://metaduck.com/post/4261725322</link><guid>http://metaduck.com/post/4261725322</guid><pubDate>Fri, 01 Apr 2011 18:50:45 +0100</pubDate></item><item><title>The news</title><description>&lt;blockquote&gt;
&lt;p&gt;Today, a young man on acid realized that all matter is merely energy condensed to a slow vibration - that we are all one consciousness experiencing itself subjectively. There&amp;#8217;s no such thing as death, life is only a dream, and we&amp;#8217;re the imagination of ourselves. Here&amp;#8217;s Tom with the weather&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;- Bill Hicks&lt;/p&gt;</description><link>http://metaduck.com/post/3921535117</link><guid>http://metaduck.com/post/3921535117</guid><pubDate>Thu, 17 Mar 2011 15:41:20 +0000</pubDate></item><item><title>Asynchronous iteration patterns in Node.js - part 2</title><description>&lt;p&gt;This is a follow-up to &lt;a href="http://metaduck.com/post/2675027550/asynchronous-iteration-patterns-in-node-js"&gt;my previous article &amp;#8220;Asynchronous iteration patterns&amp;#8221;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The latest feedback has been great, some corrections and remarks were sent my way.&lt;/p&gt;
&lt;p&gt;Also, &lt;a href="http://twitter.com/#!/coda/status/41682974445543425"&gt;some node.js hate&lt;/a&gt; was spread around because of what I think is the added complexity some times needed to handle asynchronous IO. It was not my intention to spread fear about handling asynchronous IO, but to gather and spread my view on how to handle them. In my view, asyhcnronous is good and here to stay, you should learn to embrace it.&lt;/p&gt;
&lt;p&gt;But first, a correction:&lt;/p&gt;
&lt;h3&gt;Doh!&lt;/h3&gt;
&lt;p&gt;I was alerted by some readers that the &lt;a href="https://gist.github.com/raw/772128/821ab7283e942a31de14a8ba0738e2b57287fb3e/serialize_timeout.js"&gt;serialize_timeout.js version&lt;/a&gt; (where we detach from the stack using a setTimeout) would not be necessary since we are already detaching from the stack by calling an asynchronous IO operation.&lt;/p&gt;
&lt;p&gt;Right you are.&lt;/p&gt;
&lt;h3&gt;Apples and Oranges - being fair&lt;/h3&gt;
&lt;p&gt;If we are going to compare node.js IO programming with &amp;#8220;normal&amp;#8221; blocking programming, let&amp;#8217;s be fair, and compare two equivalent objects.&lt;/p&gt;
&lt;p&gt;In my opinion, comparing syntaxes for blocking IO APIs with non-blocking IO APIs is not fair, since non-blocking allows you to do much more. If you want to compare both, you have to compare the node.js solution to the following solution on the blocking world:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Since non-blocking IO allows you to put a lot of IO operations on the background, it&amp;#8217;s only fair that we compare the same capability on the blocking world.&lt;/p&gt;
&lt;p&gt;To have the same behaviour on the blocking world you would have to have, to start with, a thread pool. No, you can&amp;#8217;t get away with creating a fresh new thread for each IO operation, since node.js does away with that overhead.&lt;/p&gt;
&lt;p&gt;Then you would have to assign each IO operation to a new thread from the thread pool.&lt;/p&gt;
&lt;p&gt;Then the main thread would block waiting for a completion signal from one of them.&lt;/p&gt;
&lt;p&gt;Each thread would have to keep a global completion counter in order to know when all operations are done with. And yes, you have to synchronize thread access to that piece of memory.&lt;/p&gt;
&lt;p&gt;When one thread detects that all operations are done, it has to notify the main thread that&amp;#8217;s waiting it in order to unblock.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Not simpler in my opinion.&lt;/p&gt;
&lt;p&gt;You could also run with co-routines, continuations, fibers - however you wish to call cooperative multi-tasking -. It would be a simplification - you wouldn&amp;#8217;t have to synchronize access to the counter - but you still would have to manage multiple contexts. Also, not simpler in my opinion.&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Abstractions&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Also, the article served to expose the underlying patterns and their consequences. Day-to-day programmers should not have to deal with this complexity. That&amp;#8217;s why some abstractions have been devised.&lt;/p&gt;
&lt;p&gt;Here is one of them:&lt;/p&gt;
&lt;h3&gt;Step&lt;/h3&gt;
&lt;p&gt;&lt;a href="https://github.com/creationix/step"&gt;Step&lt;/a&gt; is Tim Caswell&amp;#8217;s flow control library. It allows for chaining callbacks in an easy way.&lt;/p&gt;
&lt;p&gt;For example, let&amp;#8217;s say we have a function called &lt;em&gt;async&lt;/em&gt;, which serves to simulate asynchronous IO, abstracting us away from the database interaction.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/846119.js?file=async.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;Next we need to install step using npm, just type&lt;/p&gt;
&lt;p&gt;&lt;code&gt;$ npm install step&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Then, we need to, say, insert 10 elements into the database in parallel.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/846119.js?file=insert_step.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;You would simply use step with 2 functions.&lt;/p&gt;
&lt;p&gt;On the first you would just insert all the elements in parallel. To the callback you pass this.parallel(), which is the way to create a callback in step that handles parallel requests.&lt;/p&gt;</description><link>http://metaduck.com/post/3564002672</link><guid>http://metaduck.com/post/3564002672</guid><pubDate>Mon, 28 Feb 2011 14:36:00 +0000</pubDate><category>node.js</category></item><item><title>Node Nerd: Durable Sessions</title><description>&lt;a href="http://nodenerd.net/post/3459644479"&gt;Node Nerd: Durable Sessions&lt;/a&gt;: &lt;p&gt;&lt;a href="http://nodenerd.net/post/3459644479"&gt;nodenerd&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;GitHub Commit Monitor currently uses the default, in-memory session provider, which will mostly work for development, but has some downsides:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;When the app restarts or is updated all of the session data is lost&lt;/li&gt;
&lt;li&gt;If the session data is large or there are a large number of sessions, the amount of…&lt;/li&gt;
&lt;/ul&gt;&lt;/blockquote&gt;</description><link>http://metaduck.com/post/3542784620</link><guid>http://metaduck.com/post/3542784620</guid><pubDate>Sun, 27 Feb 2011 10:45:12 +0000</pubDate></item><item><title>Para lá de Teerão
Caetano Veloso - “Qualquer Coisa”...</title><description>&lt;iframe width="400" height="323" src="http://www.youtube.com/embed/OEsO5uNDij8?wmode=transparent&amp;autohide=1&amp;egm=0&amp;hd=1&amp;iv_load_policy=3&amp;modestbranding=1&amp;rel=0&amp;showinfo=0&amp;showsearch=0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;Para lá de Teerão&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.youtube.com/watch?v=OEsO5uNDij8&amp;feature=share"&gt;Caetano Veloso - “Qualquer Coisa” with Los Super Seven&lt;/a&gt; (via &lt;a href="http://youtube.com/user/brontis"&gt;brontis&lt;/a&gt;)&lt;/p&gt;</description><link>http://metaduck.com/post/3464031101</link><guid>http://metaduck.com/post/3464031101</guid><pubDate>Wed, 23 Feb 2011 14:24:53 +0000</pubDate></item><item><title>paideia:

Radiohead - Lotus Flower (via radiohead)
</title><description>&lt;iframe width="400" height="245" src="http://www.youtube.com/embed/cfOa1a8hYP8?wmode=transparent&amp;autohide=1&amp;egm=0&amp;hd=1&amp;iv_load_policy=3&amp;modestbranding=1&amp;rel=0&amp;showinfo=0&amp;showsearch=0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;&lt;a href="http://paideia.tumblr.com/post/3362696874"&gt;paideia&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://www.youtube.com/watch?v=cfOa1a8hYP8&amp;feature=youtu.be"&gt;Radiohead - Lotus Flower&lt;/a&gt; (via &lt;a href="http://youtube.com/user/radiohead"&gt;radiohead&lt;/a&gt;)&lt;/p&gt;
&lt;/blockquote&gt;</description><link>http://metaduck.com/post/3362736574</link><guid>http://metaduck.com/post/3362736574</guid><pubDate>Fri, 18 Feb 2011 14:35:32 +0000</pubDate></item><item><title>Node Tuts #19 is out - Asynchronous iteration patterns in node.js</title><description>&lt;a href="http://nodetuts.com/tutorials/19-asynchronous-iteration-patterns.html"&gt;Node Tuts #19 is out - Asynchronous iteration patterns in node.js&lt;/a&gt;</description><link>http://metaduck.com/post/3087019030</link><guid>http://metaduck.com/post/3087019030</guid><pubDate>Thu, 03 Feb 2011 14:56:30 +0000</pubDate></item><item><title>Asynchronous iteration patterns in Node.js</title><description>&lt;p&gt;Some patterns are hard to grasp, specially when programming asynchronously like you have to when you&amp;#8217;re doing IO on node.js.&lt;/p&gt;
&lt;p&gt;For example, let&amp;#8217;s suppose you had to program the following routine:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Insert a collection of objects on the database and then, when finished, call a callback.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So, if you had to write this in a synchronous fashion you would do something like this:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/772128.js?file=synchronous.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;So, since we are using node.js, db.insert is most probably asynchronous. We have to turn this into an asynchronous function.&lt;/p&gt;
&lt;p&gt;I have seen some obviously wrong implentations like this one:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/772128.js?file=wrong.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;The problem with this one is obvious: callback is called right after launching all the db.inserts on the background, not leaving them a chance to finish. By the time callback gets called, none of the inserts has terminated.&lt;/p&gt;
&lt;p&gt;Another approach would be this one:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/772128.js?file=also_wrong.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;So, there is some temptation to think &amp;#8220;we have to call when the last insert calls back&amp;#8221;, but this is plain wrong. The first insert can still be executing when the last one callsback. You never know.&lt;/p&gt;
&lt;p&gt;I think that the safest approach is to do something like this:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/772128.js?file=right.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;You should only callback when &lt;strong&gt;all&lt;/strong&gt; of the inserts have called back.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Serialization&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Sometimes you want to control the flow and / or the order of the execution.&lt;/p&gt;
&lt;p&gt;You may want the inserts to be perfectly ordered in this case, or you may want to stop inserting if an error occurs so you can recover more easily.&lt;/p&gt;
&lt;p&gt;If that&amp;#8217;s the case, you can do something like this:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/772128.js?file=serialize.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;Here we are using tail recursion to keep inserting the records.&lt;/p&gt;
&lt;p&gt;This example has one problem: it uses the stack, so if collection os too big, you might end blowing up the stack.&lt;/p&gt;
&lt;p&gt;One solution to this problem is to abandon the stack when recursing. And you can do it using a setTimeout with the timeout value of 0. The makes the inner function being called after the stack unwinds:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/772128.js?file=serialize_timeout.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Follow-up&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;See the follow-up article &lt;a href="http://metaduck.com/post/3564002672/asynchronous-iteration-patterns-in-node-js-part-2"&gt;Asynchronous iteration patterns in Node.js - part 2&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Also (as pointed out by Tim Caswell), it&amp;#8217;s important that no exceptions go back up into the event loop instead of ending up on the callback. So, you should wrap your db.insert or any other external function call. Our last example should then be:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/772128.js?file=serialize_timeout_catch.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Read more:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://creationix.com/jsconf.pdf"&gt;Tim Caswell presentation on jsconf about callbacks&lt;/a&gt;;&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Resources:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="https://github.com/creationix/Step"&gt;Step&lt;/a&gt; - a framework for asynchronous flow control by Tim Caswell;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/coolaj86/futures"&gt;Futures&lt;/a&gt; - Futures (promises framework) by AJ O&amp;#8217;Neal;&lt;/li&gt;
&lt;/ul&gt;</description><link>http://metaduck.com/post/2675027550</link><guid>http://metaduck.com/post/2675027550</guid><pubDate>Sun, 09 Jan 2011 23:35:00 +0000</pubDate><category>node.js</category></item></channel></rss>

