<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[blog.nodejitsu.com]]></title><description><![CDATA[scaling node.js applications one callback at a time]]></description><link>blog.nodejitsu.com</link><generator>NodeJS RSS Module</generator><lastBuildDate>Sat, 05 May 2012 02:35:00 GMT</lastBuildDate><atom:link href="/feed.xml" rel="self" type="application/rss+xml"/><item><title><![CDATA[<a href="./getting-started-with-flatiron">Getting Started with Flatiron HTTP</a>]]></title><description><![CDATA[<p>Lately, I've noticed quite a few people asking to see examples of flatiron apps in #nodejitsu. Now, there are actually <a href="https://github.com/nodejitsu/haibu">quite</a> a <a href="https://github.com/nodejitsu/jitsu">few</a> of <a href="http://activate.jit.su/">our</a> <a href="http://bug.jit.su/">projects</a> that use flatiron extensively. Unfortunately, there are a few problems, chief among them that no two flatiron projects do quite the same things or are organized the same ways.

</p>
<p>Now, this isn't necessarily a problem when it comes to building tools. In fact, I think it's a great demonstration of flatiron's flexibility. Each project can use exactly the libraries and organization that make sense for their applications, even for apps as different as <a href="https://github.com/nodejitsu/haibu">haibu</a> and <a href="https://github.com/nodejitsu/jitsu">jitsu</a>. It can be confusing for newcomers, though, that are used to frameworks that enforce stronger conventions, or those that are trying to figure out how to get from "hello world" to something more profound.

</p>
<p>I thought what would be helpful for flatiron newcomers is an in-depth tutorial, which iterates on a "hello world" flatiron server (like those in the project's examples) into a relatively complex webservice that uses some of flatiron's more complex functionality.

</p>
<p>In this tutorial, I'm going to create a webservice for <a href="https://github.com/substack/node-browserify">browserify</a>, a popular client-side code framework for node.js. <a href="https://github.com/jesusabdullah/browserify-cdn">All of the code is on github</a>, and every section of this tutorial corresponds to a code commit. In early parts of this tutorial I will show all the code, but as it gets longer I will typically explain the code with links to the relevant files/commits on github.

</p>
<h2><a href="https://github.com/jesusabdullah/browserify-cdn/tree/5e87b1d90374a28c931388501127c019dc073299">Flatiron HTTP Hello World</a></h2>
<p>To get started, let's write a simple "hello world" app using flatiron, in <a href="https://github.com/jesusabdullah/browserify-cdn/blob/5e87b1d90374a28c931388501127c019dc073299/app.js"><code>./app.js</code></a>:

</p>
<pre><code><span class="comment">// Require flatiron and grab the app object.</span>
<span class="keyword">var</span> flatiron = require(<span class="string">'flatiron'</span>),
    app = flatiron.app;

<span class="comment">// Use the http plugin. This makes flatiron act as an http server with a</span>
<span class="comment">// router on `app.router`.</span>
app.use(flatiron.plugins.http);

<span class="comment">// Route handler for http GET on the root path</span>
app.router.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="comment">// The request and response objects are attached to `this`.</span>
  <span class="keyword">var</span> req = <span class="keyword">this</span>.req,
      res = <span class="keyword">this</span>.res;

  <span class="comment">// Flatiron comes with a logging object already attached!</span>
  app.log.info(<span class="string">'Saying hello!'</span>);

  <span class="comment">// Handle the response as you would normally.</span>
  res.writeHead(<span class="number">200</span>, { <span class="string">'content-type'</span>: <span class="string">'text/plain'</span>});
  res.end(<span class="string">'hello!'</span>);
});

<span class="comment">// Start the server!</span>
app.start(<span class="number">8080</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  <span class="keyword">if</span> (err) {
    <span class="comment">// This would be a server initialization error. If we have one of these,</span>
    <span class="comment">// the server is probably not going to work.</span>
    <span class="keyword">throw</span> err;
  }

  <span class="comment">// Log the listening address/port of the app.</span>
  <span class="keyword">var</span> addr = app.server.address();
  app.log.info(<span class="string">'Listening on http://'</span> + addr.address + <span class="string">':'</span> + addr.port);
});</code></pre>
<p>Writing a basic flatiron server is pretty simple. First, we require flatiron and grab the 'app' object. Then, we assign a route handler to '/' which responds to request with the text, 'hello!'. This server also takes advantage of flatiron's <a href="https://github.com/flatiron/winston">built-in logging</a> to print information to the screen.

</p>
<p>Here's the accompanying <a href="https://github.com/jesusabdullah/browserify-cdn/blob/5e87b1d90374a28c931388501127c019dc073299/package.json"><code>./package.json</code></a>:

</p>
<pre><code>{
  "name": "flatiron-helloworld",
  "version": "0.0.0",
  "dependencies": {
    "flatiron": "0.1.16",
    "union": "0.3.0"
  }
}</code></pre>
<p>The most important thing to notice here is that union is also a dependency. Union is what's called a "peer dependency". This means that flatiron doesn't itself list union as a dependency, but the http plugin expects to be able to require it. This is because flatiron has uses <a href="http://blog.jit.su/writing-cli-apps-with-flatiron">outside of http servers</a> where it doesn't make sense to install union.

</p>
<p>Luckily, if you forget, flatiron will return a reasonable error message:

</p>
<pre><code>$ node app.js 
flatiron.plugins.http requires the `union` module from npm
install using `npm install union`.
Trace: 
    at Object.&lt;anonymous&gt; (<span class="regexp">/home/</span>josh/dev/nodejitsu/flatiron-tutorial/hello/node_modules/flatiron/lib/flatiron/plugins/http.js:<span class="number">25</span>:<span class="number">11</span>)
    at Module._compile (module.js:<span class="number">441</span>:<span class="number">26</span>)
    at Object..js (module.js:<span class="number">459</span>:<span class="number">10</span>)
    at Module.load (module.js:<span class="number">348</span>:<span class="number">31</span>)
    at Function._load (module.js:<span class="number">308</span>:<span class="number">12</span>)
    at Module.require (module.js:<span class="number">354</span>:<span class="number">17</span>)
    at require (module.js:<span class="number">370</span>:<span class="number">17</span>)
    at Object.http (<span class="regexp">/home/</span>josh/dev/nodejitsu/flatiron-tutorial/hello/node_modules/flatiron/node_modules/broadway/node_modules/utile/lib/index.js:<span class="number">261</span>:<span class="number">14</span>)
    at Object.&lt;anonymous&gt; (<span class="regexp">/home/</span>josh/dev/nodejitsu/flatiron-tutorial/hello/app.js:<span class="number">7</span>:<span class="number">25</span>)
    at Module._compile (module.js:<span class="number">441</span>:<span class="number">26</span>)</code></pre>
<p>Once flatiron and union are both installed, of course, our app works as expected:

</p>
<pre><code>$ node app.js 
info: Listening on http:<span class="comment">//0</span>.<span class="number">0.0</span>.<span class="number">0</span>:<span class="number">8080</span></code></pre>
<p>Now we can make a request to our server and receive a kind message:

</p>
<pre><code><span class="variable">$ </span><span class="identifier">curl</span> <span class="identifier">localhost</span><span class="symbol">:</span><span class="number">8080</span>
<span class="identifier">hello!</span></code></pre>
<p>Furthermore, we can see evidence of our request in the server's logs:

</p>
<pre><code>$ node app.js 
info: Listening on http:<span class="comment">//0</span>.<span class="number">0.0</span>.<span class="number">0</span>:<span class="number">8080</span>
info: Saying hello!</code></pre>
<h2><a href="https://github.com/jesusabdullah/browserify-cdn/tree/b9e7f912049731ded0be27594f9971785d823e1e">"Hello World" With A Twist: Configuration and POST</a></h2>
<p>Let's make our "Hello World" app <a href="https://github.com/jesusabdullah/browserify-cdn/blob/b9e7f912049731ded0be27594f9971785d823e1e/app.js">slightly more sophisticated</a>:

</p>
<pre><code><span class="keyword">var</span> path = require(<span class="string">'path'</span>);

<span class="keyword">var</span> flatiron = require(<span class="string">'flatiron'</span>),
    app = flatiron.app;

<span class="comment">// Set up app.config to use ./config.json to get and set configuration settings.</span>
app.config.file({ file: path.join(__dirname, <span class="string">'config.json'</span>) });

app.use(flatiron.plugins.http);

<span class="comment">// This router syntax allows you to define multiple handlers for one path based</span>
<span class="comment">// on http method.</span>
app.router.path(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>

  <span class="comment">// This is the same functionality as previously.</span>
  <span class="keyword">this</span>.get(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    <span class="keyword">this</span>.res.writeHead(<span class="number">200</span>, { <span class="string">'content-type'</span>: <span class="string">'text/plain'</span> });
    <span class="keyword">this</span>.res.end(<span class="string">'hello!'</span>);
  });

  <span class="comment">// Now, when you post a body to the server, it will reply with a JSON</span>
  <span class="comment">// representation of the same body.</span>
  <span class="keyword">this</span>.post(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    <span class="keyword">this</span>.res.json(<span class="number">200</span>, <span class="keyword">this</span>.req.body);
  });
});

<span class="comment">// Now we're using app.config to set the port, with a default of 8080.</span>
app.start(app.config.get(<span class="string">'port'</span>) || <span class="number">8080</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  <span class="keyword">if</span> (err) {
    <span class="keyword">throw</span> err;
  }

  <span class="keyword">var</span> addr = app.server.address();
  app.log.info(<span class="string">'Listening on http://'</span> + addr.address + <span class="string">':'</span> + addr.port);
});</code></pre>
<p>The accompanying <a href="https://github.com/jesusabdullah/browserify-cdn/blob/b9e7f912049731ded0be27594f9971785d823e1e/package.json"><code>package.json</code></a> has a few minor changes as well:

</p>
<pre><code>{
  "name": "browserify-cdn",
  "version": "0.0.0",
  "scripts": {
    "start": "node ./app.js"
  }
  "dependencies": {
    "flatiron": "0.1.16",
    "union": "0.3.0"
  }
}</code></pre>
<p>Besides a name change, our app also now has a "scripts.start" field. This means two things:

</p>
<ul>
<li>'npm start' will start your app.</li>
<li>'jitsu deploy' will successfully start your app.</li>
</ul>
<p>Note that this app also has configuration now, using <a href="https://github.com/flatiron/nconf">app.config</a>! We're using this to load configuration settings from <a href="https://github.com/jesusabdullah/browserify-cdn/blob/b9e7f912049731ded0be27594f9971785d823e1e/config.json"><code>./config.json</code></a>:

</p>
<pre><code>{
  "port": "3600"
}</code></pre>
<p>So, if you run this server and GET /, the response is the same as before:

</p>
<pre><code><span class="variable">$ </span><span class="identifier">curl</span> <span class="identifier">localhost</span><span class="symbol">:</span><span class="number">3600</span>
<span class="identifier">hello!</span></code></pre>
<p>However, if we POST some data:

</p>
<pre><code><span class="variable">$ </span><span class="identifier">curl</span> -<span class="constant">X</span> <span class="constant">POST</span> -<span class="identifier">d</span> <span class="string">'foo=foo&amp;bar=bar'</span> <span class="identifier">localhost</span><span class="symbol">:</span><span class="number">3600</span>
{<span class="string">"foo"</span><span class="symbol">:<span class="string">"foo"</span></span>,<span class="string">"bar"</span><span class="symbol">:<span class="string">"bar"</span></span>}</code></pre>
<p>We can also post JSON if we remember to set the content-type header properly:

</p>
<pre><code><span class="variable">$ </span><span class="identifier">curl</span> -<span class="constant">X</span> <span class="constant">POST</span> -<span class="identifier">d</span> <span class="string">'{ "foo": "foo", "bar": "bar" }'</span> -<span class="constant">H</span> <span class="string">'Content-Type: application/json'</span> <span class="identifier">localhost</span><span class="symbol">:</span><span class="number">3600</span>
{<span class="string">"foo"</span><span class="symbol">:<span class="string">"foo"</span></span>,<span class="string">"bar"</span><span class="symbol">:<span class="string">"bar"</span></span>}</code></pre>
<p>This all Just Works is because flatiron has built-in tools for buffering and parsing request bodies, making the development of JSON APIs dead easy.

</p>
<p>Now we're ready to do something a bit more interesting.

</p>
<h2><a href="https://github.com/jesusabdullah/browserify-cdn/tree/737917f3c14a93b53b6298ecc6b91374d76fc93f">Basic Browserifying Server &amp; Separation of Concerns 101</a></h2>
<p>Now we're going to make our app browserify posted code snippets. Once it's done, the interface should work like so:

</p>
<pre><code><span class="variable">$ </span><span class="identifier">curl</span> -<span class="constant">X</span> <span class="constant">POST</span> -<span class="identifier">d</span> <span class="string">'var traverse = require("traverse");'</span> <span class="identifier">localhost</span><span class="symbol">:</span><span class="number">3600</span>
<span class="identifier">var</span> <span class="identifier"><span class="keyword">require</span></span> = <span class="identifier">function</span> (<span class="identifier">file</span>, <span class="identifier">cwd</span>) {
    <span class="identifier">var</span> <span class="identifier">resolved</span> = <span class="identifier"><span class="keyword">require</span></span>.<span class="identifier">resolve</span>(<span class="identifier">file</span>, <span class="identifier">cwd</span> || <span class="string">'/'</span>);
    <span class="identifier">var</span> <span class="identifier">mod</span> = <span class="identifier"><span class="keyword">require</span></span>.<span class="identifier">modules</span>[<span class="identifier">resolved</span>];
    <span class="identifier"><span class="keyword">if</span></span> (!<span class="identifier">mod</span>) <span class="identifier"><span class="keymethods">throw</span></span> <span class="identifier"><span class="keymethods">new</span></span> <span class="constant">Error</span>(
        <span class="string">'Failed to resolve module '</span> + <span class="identifier">file</span> + <span class="string">', tried '</span> + <span class="identifier">resolved</span>
    );
    <span class="identifier">var</span> <span class="identifier">res</span> = <span class="identifier">mod</span>.<span class="identifier">_cached</span> ? <span class="identifier">mod</span>.<span class="identifier">_cached</span> <span class="symbol">:</span> <span class="identifier">mod</span>();
    <span class="identifier"><span class="keyword">return</span></span> <span class="identifier">res</span>;
}

<span class="identifier"><span class="keyword">require</span></span>.<span class="identifier">paths</span> = [];
<span class="identifier"><span class="keyword">require</span></span>.<span class="identifier">modules</span> = {};
<span class="identifier"><span class="keyword">require</span></span>.<span class="identifier">extensions</span> = [<span class="string">".js"</span>,<span class="string">".coffee"</span>];

<span class="identifier"><span class="keyword">require</span></span>.<span class="identifier">_core</span> = {
    <span class="string">'assert'</span><span class="symbol">:</span> <span class="identifier"><span class="keyword">true</span></span>,
    <span class="string">'events'</span><span class="symbol">:</span> <span class="identifier"><span class="keyword">true</span></span>,
    <span class="string">'fs'</span><span class="symbol">:</span> <span class="identifier"><span class="keyword">true</span></span>,</code></pre>
<p>**snip**

</p>
<p>I didn't include the entire bundle here, but the general idea is this: You post browserify-able javascript code to the service, and it returns the browserified bundle.

</p>
<p>By this point, our app is getting big enough that we want to break functionality up into different pieces. The way I approach this is like so:

</p>
<ol>
<li>Write a library (or a few) that implement the basic pieces of functionality you need.</li>
<li>Call that library from <code>./app.js</code>, only handling http details in the router.</li>
</ol>
<p>The idea here is to <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">separate the concerns</a> so that there isn't routing logic in the bundler or bundling logic in the router. In larger apps, this approach gets broken down further into <a href="http://blog.jit.su/scaling-isomorphic-javascript-code">large-scale design patterns like MVC</a>. In this case our app is pretty small though, so simply separating the bundling into its own library will suffice.

</p>
<p>The bundler, which <a href="https://github.com/jesusabdullah/browserify-cdn/blob/737917f3c14a93b53b6298ecc6b91374d76fc93f/bundler.js">lives in <code>./bundler.js</code></a> for this iteration, is a constructor that inherits from <a href="https://github.com/hij1nx/eventemitter2">EventEmitter2</a>:

</p>
<pre><code><span class="keyword">var</span> EventEmitter2 = require(<span class="string">'eventemitter2'</span>).EventEmitter2,
    browserify = require(<span class="string">'browserify'</span>),
    detective = require(<span class="string">'detective'</span>),
    npm = require(<span class="string">'npm'</span>),
    crypto = require(<span class="string">'crypto'</span>),
    util = require(<span class="string">'utile'</span>);

<span class="comment">// I wrote the Bundler as a constructor with prototype methods.</span>
<span class="comment">// I find that it's a good fit for stateful problems.</span>
<span class="keyword">var</span> Bundler = module.exports = <span class="function"><span class="keyword">function</span> <span class="params">(opts)</span> {</span>

  <span class="comment">// This lets you create a new Bundler without the 'new' keyword.</span>
  <span class="keyword">if</span> (!(<span class="keyword">this</span> <span class="keyword">instanceof</span> Bundler)) {
    <span class="keyword">return</span> <span class="keyword">new</span> Bundler;
  }

  <span class="keyword">var</span> bundler = <span class="keyword">this</span>;

  <span class="comment">// Set the bundler's persistent options here. Also handle defaults.</span>
  bundler.options = opts || {};
  bundler.options.npm = bundler.options.npm || {};

  <span class="comment">// Overrides falsy values such as `undefined`</span>
  <span class="keyword">if</span> (bundler.options.cache !== <span class="literal">false</span>) {
    bundler.options.cache = <span class="literal">true</span>;
  }

  <span class="comment">// Bundler inherits from an EE2 with wildcards and the :: delimiter.</span>
  EventEmitter2.call(<span class="keyword">this</span>, {
    wildcard: <span class="literal">true</span>,
    delimiter: <span class="string">'::'</span>,
    maxListeners: <span class="number">0</span>
  })

  <span class="comment">// Bundler requires a loaded npm in order to work properly.</span>
  <span class="comment">// The rest of the code in the constructor sets this up and emits events</span>
  <span class="comment">// to signal when it's ready.</span>
  bundler.ready = <span class="literal">false</span>;

  npm.load({}, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) {
      <span class="comment">// What would be really cool is if I checked to see if there was an error</span>
      <span class="comment">// event listener or not.</span>
      bundler.emit(<span class="string">'error'</span>, err);
    }

    bundler.ready = <span class="literal">true</span>;
    bundler.emit(<span class="string">'bundler::ready'</span>);
  });
};

util.inherits(Bundler, EventEmitter2);</code></pre>
<p>The bulk of the constructor handles setting default options for our object and configuring the EventEmitter2 aspects of the object. The interesting piece here calls <code><span class="identifier">npm</span>.<span class="identifier"><span class="keymethods">load</span></span></code> on the npm singleton object, emits events when it succeeds or fails, and sets a <code><span class="keyword">this</span>.ready</code> flag. This allows us to create our object and then listen for when we may use it.

</p>
<p>Next, we'll define the prototype method that actually bundles our code:

</p>
<pre><code><span class="comment">// The 'bundle' method is what actually attempts to bundle your project.</span>
Bundler.prototype.bundle = <span class="function"><span class="keyword">function</span> <span class="params">(src, cb)</span> {</span>
  <span class="keyword">var</span> bundler = <span class="keyword">this</span>,
      modules = detective(src);

  <span class="comment">// We used 'detective' to get a list of needed modules, so that we can make</span>
  <span class="comment">// sure they're installed before trying to browserify.</span>
  npm.commands.install(modules, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) {
      cb(err);
    }

    <span class="keyword">var</span> bundle;

    <span class="comment">// Attempt to browserify the passed-in javascript source</span>
    <span class="keyword">try</span> {
      bundle = browserify(<span class="keyword">this</span>.options)
        .addEntry(<span class="string">'index.js'</span>, { body: src || <span class="string">''</span> })
        .bundle();

      <span class="comment">// Hit the callback with our complete bundle object.</span>
      cb(<span class="literal">null</span>, {
        src: src,
        md5: crypto.createHash(<span class="string">'md5'</span>).update(src).digest(<span class="string">'base64'</span>),
        bundle: bundle
      });
    }
    <span class="keyword">catch</span> (err) {
      cb(err);
    }
  });
};</code></pre>
<p>This method handles making sure that required modules are installed, and then attempts to browserify the code. It then calls back with an object representing the code bundle.

</p>
<p>Finally, let's add <code>.attach</code> and <code>.init</code> methods, which will let our new module act as a <a href="https://github.com/flatiron/broadway">broadway plugin</a>:

</p>
<pre><code><span class="comment">// Bundler can be used as a broadway plugin.</span>
Bundler.attach = <span class="function"><span class="keyword">function</span> <span class="params">(opts)</span> {</span>
  <span class="keyword">this</span>.bundler = <span class="keyword">new</span> Bundler(opts);
}

<span class="comment">// The major win we get from making Bundler attachable is that we can integrate</span>
<span class="comment">// its initialization step with our app.</span>
Bundler.init = <span class="function"><span class="keyword">function</span> <span class="params">(done)</span> {</span>
  <span class="keyword">var</span> npm = <span class="string">'npm'</span>.red.inverse;

  <span class="keyword">if</span> (<span class="keyword">this</span>.bundler.ready) {
    console.log(<span class="string">'init: %s is ready.'</span>, npm);
    <span class="keyword">return</span> done();
  } <span class="keyword">else</span> {
    console.log(<span class="string">'init: Waiting for %s.'</span>, npm);
    <span class="keyword">this</span>.bundler.once(<span class="string">'bundler::ready'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
      console.log(<span class="string">'init: %s is ready.'</span>, npm);
      <span class="keyword">return</span> done();
    });
  }
}</code></pre>
<p>Now that the bundler library is done, all we have to do is <a href="https://github.com/jesusabdullah/browserify-cdn/blob/737917f3c14a93b53b6298ecc6b91374d76fc93f/app.js">integrate it with our <code>./app.js</code></a>.


</p>
<p>First, let's talk about how the bundler was integrated into the app. After requiring it, we use <code>bundler</code> like so:

</p>
<pre><code><span class="comment">// </span>This is a new library used <span class="keyword">for</span> running browserify bundle jobs <span class="keyword">for</span> us.
var bundler = require('./bundler');


<span class="comment">// </span>Note that 'bundler' is written to work as a flatiron plugin.
app.use(flatiron.plugins.http);
app.use(bundler);</code></pre>
<p>This creates a property called <code>app.bundler</code>, and adds an initialization step so that when we call <code>app.start</code> npm is also loaded.

</p>
<p>Later, we use <code>app.bundler</code> in our POST handler like so:

</p>
<pre><code><span class="keyword">this</span>.post(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>

  <span class="comment">// If the request body doesn't have the property we expect, it's assumed</span>
  <span class="comment">// to be raw javascript. Note that the raw unparsed body is buffered into</span>
  <span class="comment">// req.chunks (as a Buffer).</span>
  <span class="keyword">var</span> req = <span class="keyword">this</span>.req,
      res = <span class="keyword">this</span>.res,
      js = req.body.js ? req.body.js : req.chunks.toString();

  <span class="comment">// 'app.bundler' was created when we attached 'bundler'.</span>
  app.bundler.bundle(js, <span class="function"><span class="keyword">function</span> <span class="params">(err, data)</span> {</span>
    <span class="keyword">if</span> (err) {
      <span class="keyword">return</span> res.json(<span class="number">500</span>, {
        success: <span class="literal">false</span>,
        reason: err.message || <span class="string">'unknown'</span>
      });
    }
    res.writeHead(<span class="number">200</span>, { <span class="string">'content-type'</span>: <span class="string">'text/javascript'</span> });
    res.end(data.bundle);
  });
});</code></pre>
<p>Note that most of the code here is about figuring out what the user wants to browserify and how to respond in return, and that all the bundling takes place in a single call.

</p>
<p>Finally, here's the <a href="https://github.com/jesusabdullah/browserify-cdn/blob/737917f3c14a93b53b6298ecc6b91374d76fc93f/package.json"><code>./package.json</code></a> for completeness:

</p>
<pre><code>{
  "name": "browserify-cdn",
  "version": "0.0.0",
  "scripts": {
    "start": "node ./app.js"
  },
  "dependencies": {
    "flatiron": "0.1.16",
    "union": "0.3.0",
    "utile": "0.0.10",
    "eventemitter2": "0.4.x",
    "browserify": "1.10.6",
    "detective": "0.1.x",
    "npm": "1.1.x"
  }
}</code></pre>
<p>The only important changes are in the dependencies field, since we now have a few more of them!

</p>
<p>Finally, we can run our service with <code>npm start</code>, and when a user runs the curl command from earlier (<code>curl -X POST -d 'var traverse = require("traverse");' localhost:3600</code>) they will receive a bundle and our logs will look like so:

</p>
<pre><code>$ npm start
npm info it worked <span class="keyword">if</span> it ends <span class="keyword">with</span> ok
npm info using npm@<span class="number">1.1</span>.<span class="number">14</span>
npm info using node@v0.<span class="number">6.14</span>
npm info prestart browserify-cdn@<span class="number">0.0</span>.<span class="number">0</span>
npm info start browserify-cdn@<span class="number">0.0</span>.<span class="number">0</span>

&gt; browserify-cdn@<span class="number">0.0</span>.<span class="number">0</span> start /home/josh/dev/nodejitsu/flatiron-tutorial
&gt; node ./app.js

init: Waiting <span class="keyword">for</span> npm.
init: npm is ready.
info: Browserify-CDN Listening on http:<span class="comment">//0.0.0.0:3600</span>
npm http GET https:<span class="comment">//registry.npmjs.org/traverse</span>
npm http <span class="number">304</span> https:<span class="comment">//registry.npmjs.org/traverse</span>
npm info into /home/josh/dev/nodejitsu/flatiron-tutorial traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info installOne traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info unbuild /home/josh/dev/nodejitsu/flatiron-tutorial/node_modules/traverse
npm info preuninstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info uninstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info postuninstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info preinstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info build /home/josh/dev/nodejitsu/flatiron-tutorial/node_modules/traverse
npm info linkStuff traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info install traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info postinstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
traverse@<span class="number">0.6</span>.<span class="number">1</span> .<span class="regexp">/node_modules/</span>traverse</code></pre>
<p>Congratulations, you now have a working browserify webservice!

</p>
<h2><a href="https://github.com/jesusabdullah/browserify-cdn/tree/960d0a00f9fe4c40469d92ba34f896d1b420fbe6">Add Caching with Resourceful</a></h2>
<p>So, our browserify service works, but there's a problem: Our browserify webservice has to bundle the project every time, even if it's done it before! We can minimize this with caching.

</p>
<p>To facilitate this, I reorganized the project a little bit:

</p>
<pre><code>$ ls
app.js  config.json  lib  node_modules  package.json  post
$ ls -R ./lib
./lib:
bundler  common.js

.<span class="regexp">/lib/</span>bundler:
bundler.js  cache.js  index.js</code></pre>
<p>As you can see, I moved <code>bundler.js</code> into <code>.<span class="regexp">/lib/</span>bundler</code> and added a <code>cache.js</code> and an <code><span class="identifier"><span class="keymethods">index</span></span>.<span class="identifier">js</span></code>.

</p>
<p>You'll also notice that I removed <code>config.json</code> from the git repository. This is because it now includes credentials to a <a href="http://couchdb.apache.org">couchdb</a>. Mine looks like this:

</p>
<pre><code>{
  <span class="string">"port"</span>: <span class="string">"3600"</span>,
  <span class="string">"couch"</span>: {
    <span class="string">"https"</span>: <span class="literal">true</span>,
    <span class="string">"uri"</span>: <span class="string">"**********.iriscouch.com/browserify"</span>,
    <span class="string">"port"</span>: <span class="string">"6984"</span>,
    <span class="string">"auth"</span>: {
      <span class="string">"username"</span>: <span class="string">"**********"</span>,
      <span class="string">"password"</span>: <span class="string">"**********"</span>
    }
  }
}</code></pre>
<p>In order to add caching, the approach I took was to create a new constructor which inherits from <code>Bundler</code>, called <code>CachingBundler</code>, in <a href="https://github.com/jesusabdullah/browserify-cdn/blob/960d0a00f9fe4c40469d92ba34f896d1b420fbe6/lib/bundler/cache.js"><code>.<span class="regexp">/lib/</span>bundler/cache.js</code></a>. This new constructor contains a new prototype method, <code>.get</code>, which checks our cache and only calls <code>.bundle</code> if required. This sort of inheritance pattern is appropriate for cases where your new object is "an x that also does y"---for example, Bundler is an EE2 that also bundles, and CachingBundler is a Bundler that also caches.

</p>
<p>Our new library starts with a long list of requires:

</p>
<pre><code><span class="identifier">var</span> <span class="constant">Bundler</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'./bundler'</span>),
    <span class="identifier">common</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'../common'</span>),
    <span class="identifier">resourceful</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'resourceful'</span>),
    <span class="identifier">errs</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'errs'</span>),
    <span class="identifier">colors</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'colors'</span>),
    <span class="identifier">utile</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'utile'</span>);</code></pre>
<p><code>Bundler</code> and <code>common</code> are internal libraries, while <code>resourceful</code>, <code>errs</code> and <code>utile</code> are all flatiron components. This caching layer uses <a href="https://github.com/flatiron/resourceful">resourceful</a> to interact with a storage backend (in this case, couchdb). Resourceful is an "Object Document Mapper," or ODM, which means that it internally maps javascript objects and prototypes with documents in a document store like couch. This saves developers the step of wrapping their couchdb http calls in a custom abstraction, and is typically used to put the "model" in MVC.

</p>
<p>Here's what creating a resource with resourceful looks like:

</p>
<pre><code><span class="comment">// Cached bundle resources.</span>
<span class="keyword">var</span> CachedBundle = resourceful.define(<span class="string">'cachedBundle'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.string(<span class="string">'md5'</span>);
  <span class="keyword">this</span>.string(<span class="string">'source'</span>);
  <span class="keyword">this</span>.string(<span class="string">'bundle'</span>);
});</code></pre>
<p>This resource is quite simple. It's called a 'cachedBundle', and is expected to at least have three strings (<code>md5</code>, <code>source</code> and <code>bundle</code>).

</p>
<p>Now, we can create our constructor:

</p>
<pre><code><span class="comment">// A version of the bundler that caches. Use `.get(text)`.</span>
<span class="keyword">var</span> CachingBundler = module.exports = <span class="function"><span class="keyword">function</span> <span class="params">(opts)</span> {</span>
  <span class="comment">// This lets you create a new caching Bundler without the 'new' keyword.</span>
  <span class="keyword">if</span> (!(<span class="keyword">this</span> <span class="keyword">instanceof</span> CachingBundler)) {
    <span class="keyword">return</span> <span class="keyword">new</span> CachingBundler;
  }

  opts = opts || {};
  Bundler.call(<span class="keyword">this</span>, opts);
  <span class="comment">// Set up resourceful to use couchdb.</span>
  resourceful.use(<span class="string">'couchdb'</span>, opts);
}

utile.inherits(CachingBundler, Bundler);</code></pre>
<p>Generally, this constructor just repeats the actions of the original <code>Bundler</code> constructor and then inherits from it. However, it also sets up resourceful to use our couchdb, using the options passed into it.

</p>
<p>The meat of our new functionality is in the <code>get</code> prototype method:

</p>
<pre><code>CachingBundler.prototype.get = <span class="function"><span class="keyword">function</span> <span class="params">(src, cb)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>,
      md5 = common.md5(src);

  <span class="comment">// This logging function simply adds some extra text to the message and</span>
  <span class="comment">// then emits it with the event 'log::lvl' (ex: 'log::info').</span>
  <span class="function"><span class="keyword">function</span> <span class="title">log</span> <span class="params">(lvl, msg)</span> {</span>
    <span class="keyword">var</span> restOf = [].slice.call(arguments, <span class="number">2</span>),
        data = utile.format.apply(
          <span class="literal">null</span>,
          [ <span class="string">'(md5 `%s`) '</span>.cyan + msg, md5 ].concat(restOf)
        );

    self.emit(<span class="string">'log::'</span> + lvl, data);
  }

  log(<span class="string">'info'</span>, <span class="string">'Trying to find bundle...'</span>);

  <span class="comment">// Check to see if the file already exists in the cache, based on md5 hash of</span>
  <span class="comment">// the source text. This logic accounts for the possibility of hash collisions</span>
  <span class="comment">// and multiple versions of the same bundle.</span>
  CachedBundle.find({ md5: md5 }, <span class="function"><span class="keyword">function</span> <span class="params">(err, bundles)</span> {</span>
    <span class="keyword">if</span> (err) {
      <span class="keyword">return</span> cb(realError(err));
    }

    <span class="keyword">var</span> matches;

    <span class="keyword">if</span> (!bundles.length) {
      <span class="comment">// No cached bundles found. We should bundle.</span>
      log(<span class="string">'warn'</span>, <span class="string">'Not found.'</span>);
      <span class="keyword">return</span> bundle(src);
    }

    <span class="comment">// Log the document id's for found bundles. If there is more than one</span>
    <span class="comment">// bundle, it means there was either an md5 hash collision or multiple</span>
    <span class="comment">// documents for the same bundle exist.</span>
    log(<span class="string">'info'</span>, <span class="string">'Found bundle(s): %j'</span>, bundles.map(<span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
      <span class="keyword">return</span> doc._id;
    }));

    <span class="comment">// Try to find one that has the same text.</span>
    matches = bundles.filter(<span class="function"><span class="keyword">function</span> <span class="params">(bundle)</span> {</span>
      <span class="keyword">return</span> bundle.source == src;
    });

    <span class="comment">// Any answer other than 1 means an actual md5 hash collison.</span>
    <span class="keyword">switch</span> (matches.length) {
      <span class="keyword">case</span> <span class="number">1</span>:
        log(<span class="string">'info'</span>, <span class="string">'Match found.'</span>);
        finish(<span class="literal">null</span>, matches[<span class="number">0</span>]);
    <span class="keyword">break</span>;
      <span class="keyword">case</span> <span class="number">0</span>:
        log(<span class="string">'info'</span>, <span class="string">'Hash collision with existing document(s) %j'</span>, matches);
        bundle(src);
        <span class="keyword">break</span>;
      <span class="keyword">default</span>:
        log(<span class="string">'Multiple documents describing this document exist.'</span>);
        log(<span class="string">'Showing the first one.'</span>);
        finish(<span class="literal">null</span>, matches[<span class="number">0</span>]);
        <span class="keyword">break</span>;
    }
  });

  <span class="comment">// This function is called when we need to bundle. It addition to logging, it</span>
  <span class="comment">// also attempts to cache the resulting bundle.</span>
  <span class="function"><span class="keyword">function</span> <span class="title">bundle</span> <span class="params">(src)</span> {</span>
    log(<span class="string">'info'</span>, <span class="string">'Bundling.'</span>);
    self.bundle(src, <span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
      <span class="keyword">if</span> (err) {
        <span class="keyword">return</span> cb(err);
      }

      <span class="comment">// Here, we create a new CachedBundle, which maps to our data store.</span>
      <span class="keyword">var</span> bundle = <span class="keyword">new</span> CachedBundle(doc);

      <span class="comment">// This is how you save resources with resourceful.</span>
      log(<span class="string">'info'</span>, <span class="string">'Caching bundle for next time...'</span>)
      CachedBundle.save(bundle, <span class="function"><span class="keyword">function</span> <span class="params">(err, bundle)</span> {</span>
        <span class="keyword">if</span> (err) {
          log(<span class="string">'error'</span>, <span class="string">'Error while caching bundle'</span>);
        }
        <span class="keyword">return</span> finish(realError(err), bundle);
      });

    });
  }

  <span class="comment">// This is pretty much the last step, whether the doc came from the cache</span>
  <span class="comment">// or from a bundling.</span>
  <span class="function"><span class="keyword">function</span> <span class="title">finish</span> <span class="params">(err, bundle)</span> {</span>
    <span class="keyword">if</span> (err) {
      <span class="keyword">return</span> cb(err);
    }

    log(<span class="string">'info'</span>, <span class="string">'Returning bundle.'</span>);
    cb(<span class="literal">null</span>, bundle);
  }

};</code></pre>
<p>Most of the logic you can see involves grabbing the document, and making sure it's the right one, and logging the behavior using the EventEmitter2 api (remember, Bundler inherited from EventEmitter2). Interaction with our datastore is simplified to the creation of a resource type, a call to <code>.<span class="identifier"><span class="keymethods">find</span></span></code> and a call to <code>.save</code>.

</p>
<p>Like <code>Bundler</code>, our caching bundler also has <code>.attach</code> and <code>.init</code> methods for integration with flatiron:

</p>
<pre><code><span class="comment">// Attach the caching bundler, passing in our config options for the couch.</span>
<span class="comment">// Also emits logging events to the app.</span>
CachingBundler.attach = <span class="function"><span class="keyword">function</span> <span class="params">(options)</span> {</span>
  <span class="keyword">var</span> app = <span class="keyword">this</span>;

  <span class="keyword">this</span>.bundler = <span class="keyword">new</span> CachingBundler(utile.mixin(
    options,
    <span class="keyword">this</span>.config.get(<span class="string">'couch'</span>)
  ));

  <span class="comment">// Little known fact about flatiron: The logging plugin will log messages</span>
  <span class="comment">// emitted on the `log` namespace of the core app, which is an instance of</span>
  <span class="comment">// EventEmitter2.</span>
  app.bundler.on(<span class="string">'log::**'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(msg)</span> {</span>
    app.emit(<span class="keyword">this</span>.event, msg);
  });

};

CachingBundler.init = Bundler.init;</code></pre>
<p>The init method is exactly the same. The new behaviors are in our attach method. One of these behaviors is to pass our app's couchdb configuration to the object constructor. The other behavior is to re-emit logging events on the app object, whose log plugin will handle them.

</p>
<p>I also created a <code>.<span class="regexp">/lib/</span>bundler/index.js</code> which looks like so:

</p>
<pre><code><span class="class"><span class="keyword">module</span>.<span class="title">exports</span> = <span class="title">require</span>('./<span class="title">cache</span>');</span></code></pre>
<p>and allows us to simply require our new caching bundler in <a href="https://github.com/jesusabdullah/browserify-cdn/blob/960d0a00f9fe4c40469d92ba34f896d1b420fbe6/app.js"><code>./app.js</code></a> like so:

</p>
<pre><code><span class="keyword">var</span> bundler = require(<span class="string">'./lib/bundler'</span>);</code></pre>
<p>Now, let's run our app and do another <code>curl -X POST -d 'var traverse = require("traverse");' localhost:3600</code>:

</p>
<pre><code>$ npm start
npm info it worked <span class="keyword">if</span> it ends <span class="keyword">with</span> ok
npm info using npm@<span class="number">1.1</span>.<span class="number">14</span>
npm info using node@v0.<span class="number">6.14</span>
npm info prestart browserify-cdn@<span class="number">0.0</span>.<span class="number">0</span>-<span class="number">3</span>
npm info start browserify-cdn@<span class="number">0.0</span>.<span class="number">0</span>-<span class="number">3</span>

&gt; browserify-cdn@<span class="number">0.0</span>.<span class="number">0</span>-<span class="number">3</span> start /home/josh/dev/nodejitsu/flatiron-tutorial
&gt; node ./app.js

init: Waiting <span class="keyword">for</span> npm.
init: npm is ready.
info: Browserify-CDN Listening on http:<span class="comment">//0.0.0.0:3600</span>
info: (md5 `RxLf0LntDlue3quYVoaVtw==`) Trying to find bundle... event=log::info
warn: (md5 `RxLf0LntDlue3quYVoaVtw==`) Not found. event=log::warn
info: (md5 `RxLf0LntDlue3quYVoaVtw==`) Bundling. event=log::info
npm http GET https:<span class="comment">//registry.npmjs.org/traverse</span>
npm http <span class="number">304</span> https:<span class="comment">//registry.npmjs.org/traverse</span>
npm info into /home/josh/dev/nodejitsu/flatiron-tutorial traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info installOne traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info unbuild /home/josh/dev/nodejitsu/flatiron-tutorial/node_modules/traverse
npm info preuninstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info uninstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info postuninstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info preinstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info build /home/josh/dev/nodejitsu/flatiron-tutorial/node_modules/traverse
npm info linkStuff traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info install traverse@<span class="number">0.6</span>.<span class="number">1</span>
npm info postinstall traverse@<span class="number">0.6</span>.<span class="number">1</span>
traverse@<span class="number">0.6</span>.<span class="number">1</span> .<span class="regexp">/node_modules/</span>traverse
info: (md5 `RxLf0LntDlue3quYVoaVtw==`) Caching bundle <span class="keyword">for</span> next time... event=log::info
info: (md5 `RxLf0LntDlue3quYVoaVtw==`) Returning bundle. event=log::info</code></pre>
<p>Naturally, this request wasn't cached so our app had to bundle it. If you check your couch with futon, you'll see that our document has been stored by resourceful. So, if we curl our api <em>again</em>:

</p>
<pre><code><span class="identifier">info</span><span class="symbol">:</span> (<span class="identifier">md5</span> `<span class="constant">RxLf0LntDlue3quYVoaVtw</span>==`) <span class="constant">Caching</span> <span class="identifier">bundle</span> <span class="identifier"><span class="keyword">for</span></span> <span class="identifier"><span class="keyword">next</span></span> <span class="identifier">time</span>... <span class="identifier">event</span>=<span class="identifier">log</span><span class="symbol">:</span><span class="symbol">:<span class="identifier">info</span></span>
<span class="identifier">info</span><span class="symbol">:</span> (<span class="identifier">md5</span> `<span class="constant">RxLf0LntDlue3quYVoaVtw</span>==`) <span class="constant">Returning</span> <span class="identifier">bundle</span>. <span class="identifier">event</span>=<span class="identifier">log</span><span class="symbol">:</span><span class="symbol">:<span class="identifier">info</span></span>
<span class="identifier">info</span><span class="symbol">:</span> (<span class="identifier">md5</span> `<span class="constant">RxLf0LntDlue3quYVoaVtw</span>==`) <span class="constant">Trying</span> <span class="identifier">to</span> <span class="identifier"><span class="keymethods">find</span></span> <span class="identifier">bundle</span>... <span class="identifier">event</span>=<span class="identifier">log</span><span class="symbol">:</span><span class="symbol">:<span class="identifier">info</span></span>
<span class="identifier">info</span><span class="symbol">:</span> (<span class="identifier">md5</span> `<span class="constant">RxLf0LntDlue3quYVoaVtw</span>==`) <span class="constant">Found</span> <span class="identifier">bundle</span>(<span class="identifier">s</span>)<span class="symbol">:</span> [<span class="string">"f4328d0a958746dfa8b45856a900134e"</span>] <span class="identifier">event</span>=<span class="identifier">log</span><span class="symbol">:</span><span class="symbol">:<span class="identifier">info</span></span>
<span class="identifier">info</span><span class="symbol">:</span> (<span class="identifier">md5</span> `<span class="constant">RxLf0LntDlue3quYVoaVtw</span>==`) <span class="constant">Match</span> <span class="identifier">found</span>. <span class="identifier">event</span>=<span class="identifier">log</span><span class="symbol">:</span><span class="symbol">:<span class="identifier">info</span></span>
<span class="identifier">info</span><span class="symbol">:</span> (<span class="identifier">md5</span> `<span class="constant">RxLf0LntDlue3quYVoaVtw</span>==`) <span class="constant">Returning</span> <span class="identifier">bundle</span>. <span class="identifier">event</span>=<span class="identifier">log</span><span class="symbol">:</span><span class="symbol">:<span class="identifier">info</span></span></code></pre>
<p>Since we've already bundled that particular source snippet, we may simply return it! Now we're cooking.

</p>
<h2>What Now?</h2>
<p>In this quick tutorial, I showed you how I built the foundation for the new browserify-cdn project, which is hosted at <a href="http://browserify.nodejitsu.com">http://browserify.nodejitsu.com</a>, by starting with a "hello world" flatiron example and then iterating on it until we had a fully-working api server. Along the way, we learned a little about flatiron core's capabilities and many of its supporting libraries, as well as touching on concepts for organizing medium-sized apps.

</p>
<p>The master branch has a number of tweaks and improvements, the most noticeable of which is serving an html landing page and static content using <a href="https://github.com/jesusabdullah/node-ecstatic">my static server middleware</a> and adding more colors to the text output. Of course, now that you have your <em>own</em> browserify-cdn, you can change it however you want!

</p>
<p>If you do, don't forget to <a href="https://github.com/jesusabdullah/browserify-cdn/pulls">send me a pull request</a>.
</p>
]]></description><link>http://blog.nodejitsu.com/getting-started-with-flatiron</link><guid isPermaLink="true">http://blog.nodejitsu.com/getting-started-with-flatiron</guid><dc:creator><![CDATA[Josh Holbrook]]></dc:creator><pubDate>Mon, 09 Apr 2012 08:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./april-conference-overload">April - Conference Overload</a>]]></title><description><![CDATA[<p>At Nodejitsu, we are always on the lookout to find great javascript conferences that revolve around awesome communities.

</p>
<p>We are also co-hosting two events in April: The <a href="http://node.ph">Node Philly</a> Conference and the <a href="http://www.10gen.com/events/NYC-MongoDB-Hackathon">NYC MongoDB Hackaton</a> and speaking at three more!

</p>
<p>Here's our schedule: be sure to say hi and hangout.

</p>
<h2>JSConf (&amp;NotConf)</h2>
<p><img src="april-conference-overload/jsconf-2012-scottsdale-arizona.png" alt="JSConf">

</p>
<p>It's <a href="http://2012.jsconf.us/">JSConf</a>! Enough said!
Pre conference will be <a href="http://notconf.com/">notconf</a> and it is looking amazing!

</p>
<h2>Web-5 Conference (Béziers, April 4-6)</h2>
<p><img src="april-conference-overload/web5conf.png" alt="Web-5">

</p>
<p>Maciej and Charlie will be attending the <a href="http://www.web-5.org/">Web-5</a> conference in Béziers, France. The conference revolves around Web Technologies and has some great speakers. Great cheese and great weather are also givens. You can register for the conference <a href="http://web-5.eventsbot.com/">here</a>.

</p>
<h2>Dyncon (Stockholm, April 21-22)</h2>
<p><img src="april-conference-overload/dynamic-languages-conference-stockholm-2012.png" alt="Dyncon">

</p>
<p><a href="http://swdc.se/dyncon2012/">Dyncon</a> is an fantastic event. Charlie spoke last year and had a blast. Nuno will be doing the honors for Nodejitsu this year, and we expect great talks from a great selection of speakers.

</p>
<h2>Node Philly (Philadelphia, April 23)</h2>
<p><img src="april-conference-overload/node-philly-2012-philly-tech-week.png" alt="Node.ph">

</p>
<p>Node Philly (<a href="http://node.ph">node.ph</a>) is the first ever node.js conference in Philly. Charlie and Paolo are attending, as well as some great minds from the Node.js community like <a href="http://substack.net/">James Halliday</a> and <a href="http://www.mikealrogers.com/">Mikeal Rogers</a>. The event is part of a larger initiative called <a href="http://phillytechweek.com/">Philly Tech Week</a>. <a href="http://nodephilly.eventbrite.com/">Tickets</a> are available for a nominal fee.

</p>
<h2>MongoDB Hackaton NYC (NYC, April 27)</h2>
<p>We are co-hosting the <a href="http://www.10gen.com/events/NYC-MongoDB-Hackathon">MongoDB hackaton</a> with <a href="http://10gen.com">10gen</a>. Charlie will be on location to help you out with your applications, and get you some free Nodejitsu accounts. This event is free and will be in the 10gen NYC headquarters.

</p>
]]></description><link>http://blog.nodejitsu.com/april-conference-overload</link><guid isPermaLink="true">http://blog.nodejitsu.com/april-conference-overload</guid><dc:creator><![CDATA[Nuno Job]]></dc:creator><pubDate>Fri, 09 Mar 2012 02:14:02 GMT</pubDate></item><item><title><![CDATA[<a href="./hiring-open-source-developers">Hiring open-source developers</a>]]></title><description><![CDATA[<p>At Nodejitsu, we spend a lot of time and resources on <a href="http://en.wikipedia.org/wiki/Open_source_software_development">open-source software development</a>. Before founding Nodejitsu, the three of us were all <a href="https://github.com/marak/">active</a> <a href="https://github.com/hij1nx/">open-source enthusiasts</a> and <a href="https://github.com/indexzero/">developers</a>. Tools like <a href="http://github.com">Github</a> helped bring us together to better understand each others techniques and technical skill-sets. Events like <a href="http://groups.google.com/group/nycjs?pli=1">NYC.JS</a>, <a href="http://musichackday.org/">Music Hack Day NYC</a>, and the first <a href="http://nodeknockout.com/">Node Knockout</a> helped solidify the team. 

</p>
<p>Now, after three years of toiling away on Github, we have now expanded our engineering team to over <a href="http://github.com/nodejitsu/">fourteen strong</a> and every Nodejitsu developer is an active contributor to the open-source community.

</p>
<ul>
<li><p><a href="/hiring-open-source-developers#become-open-source-developer">How to become an open-source developer?</a></p>
</li>
<li><p><a href="/hiring-open-source-developers#get-recruited-as-open-source-developer">How do you get recruited as an open-source developer?</a></p>
</li>
</ul>
<p><br><br>

</p>
<h1>#</h1>
<p><a name="become-open-source-developer"></a>
</p>
<h3>How to become an open-source developer?</h3>
<p>Becoming an "open-source developer" is actually quite simple. You really only need to do one thing: <strong>contribute</strong>. 

</p>
<p>Contributing can be done on several levels of participation. One of the easiest ways to contribute to a project is to use it, find an issue, and report the problem. If you've found an actual problem that can be resolved, hopefully one of the maintainers will respond by fixing the issue or providing guidance on how to resolve the issue. 

</p>
<p>There are also several other useful things you can do such as: unit-tests, benchmark suites, documentation, multi-platform support, third-party integrations, and new functionality.

</p>
<p><a name="get-recruited-as-open-source-developer"></a>
</p>
<h3>How do you get recruited as an open-source developer?</h3>
<p>If you are contributing ( as described in the previous paragraph ), you've already done the hardest part. 

</p>
<p><strong>Good work always speaks for itself.</strong>

</p>
<p>If you have worked on projects which are significant to companies who are hiring developers, they probably already know your name. It's much more likely a company will hire a developer who has already made an improvement to a piece of their codebase versus someone who has little knowledge of any company projects. At Nodejitsu, we primarily <a href="https://github.com/nodejitsu/">hire developers</a> who have already contributed to major company supported projects like: <a href="http://github.com/nodejitsu/jitsu">jitsu</a>, <a href="http://github.com/nodejitsu/haibu">haibu</a>, <a href="http://github.com/flatiron/">flatiron</a>, and <a href="http://github.com/hookio/">hook.io</a>.

</p>
<h2>How to recruit open-source developers?</h2>
<p>Recruiting open-source developers is not difficult, but it can be very difficult for certain companies.

</p>
<p>First off, don't cold email open-source developers. If an open-source developer has posted their email in a public place ( like on Github ), they probably put it up for technical support emails, not recruiter spam. 

</p>
<p><strong>Sponsoring hackathons with open-source incentives is always a great idea.</strong>

</p>
<p><strong>Allow company time for open-source projects</strong>.

</p>
<p>This isn't about setting an arbitrary percentage of time like 10% or 20% of hours. If an employee is working on a project in their free time that could help improve open-source software in a significant way, you should encourage them to work on it. Hopefully, the projects they are working on in their free time align with the goals of your company.

</p>
<p><strong>Use algorithmic recruitment to find developers.</strong>

</p>
<p><a href="http://www.githits.me/">http://www.githits.me/</a> is fun. 

</p>
<p><a href="http://coderwall.com/leaderboard">http://coderwall.com/leaderboard</a> is also good.

</p>
<p><a href="http://develop.github.com/">http://develop.github.com/</a> is great.

</p>
<p>The data is out there. Do some googling and get creative.

</p>
<h2>Upcoming jobs at Nodejitsu</h2>
<p>At <a href="https://github.com/nodejitsu">Nodejitsu</a>, <a href="https://github.com/nodejitsu">our developers</a> are top-class and their open-source contributions stand on their own. Our developers are constantly spammed for job offers and choose to work for us because we try to let them do the work they would be doing anyway.

</p>
<p>Over the next few months, we will be aggressively expanding our development team and hiring new people who can step up in any of the following roles. 

</p>
<ul>
<li>Support Engineering</li>
<li>Development Operations</li>
<li>Front-End Development</li>
<li>User-Experience</li>
<li>Design and Graphic Art</li>
</ul>
<p>We are looking for people who are self-motivated and are always willing to take the extra step needed to get the job done. We are looking for people who can not only provide results, but can also proactively take the initiative to get results.

</p>
<p>Location: On-Site in San Francisco or New York City, Telecommute

</p>
<ul>
<li>Compensation is competitive and based on experience</li>
<li>Health insurance (including dental and vision)</li>
<li>Equity opportunities available for senior roles</li>
</ul>
<p>If you are interested in working for Nodejitsu, send an email to <a href="mailto:hiring@nodejitsu.com">hiring@nodejitsu.com</a> or better yet...

</p>
<p><br>

</p>
<p><strong>Get a pull request merged on Github.</strong>

</p>
<p><br>

</p>
<p><em>Now get coding.</em></p>
]]></description><link>http://blog.nodejitsu.com/hiring-open-source-developers</link><guid isPermaLink="true">http://blog.nodejitsu.com/hiring-open-source-developers</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Sat, 03 Mar 2012 15:30:00 GMT</pubDate></item><item><title><![CDATA[<a href="./pattern-matching-in-javascript">Pattern Matching in Javascript for Asynchronous Iteration</a>]]></title><description><![CDATA[<p><code>pattern</code> (<a href="https://github.com/dscape/p">github</a>, <code>p</code> on npm) is a way to iterate javascript collections with asynchronous functions using a technique called <a href="http://en.wikipedia.org/wiki/Pattern_matching">pattern matching</a>.

</p>
<h2>asynchronous functions</h2>
<p>an asynchronous function is one that usually returns before having finished its job and takes a function it should call when the job is done. that action is the callback, a function to be executed at that point in time.

</p>
<pre><code class="js">// async
var fs = require('fs');
// callback
function logContents(err,contents) { console.log(contents); }
var contents = fs.readFile('a.txt', 'utf8', logContents); 
console.log('1');
// outputs 1, then the contents of the file when the file is read</code></pre>
<p>vs.

</p>
<pre><code class="js">// sync
var fs = require('fs');
var contents = fs.readFileSync('a.txt', 'utf8'); 
console.log(contents);
console.log('1');
// outputs the contents of the file, then 1.</code></pre>
<h1>iterating in javascript with asynchronous functions</h1>
<h2>the problem</h2>
<p>when someone is starting with node i always recommend they watch <a href="http://nodetuts.com/tutorials/19-asynchronous-iteration-patterns.html#video">pedro teixeira's video nodetut on asynchronoys iteration patterns</a>

</p>
<p>in this nodetuts video pedro shows how to iterate asynchronously in node.js. here is the naive approach code he shows which <strong>doesn't work</strong>:

</p>
<pre><code class="js">// simulating an asynchronous call, e.g. getting something from a database
var asyncFn = function(data, callback) {
  var timeout = Math.ceil(Math.random() * 3000);
  // run callback after timeout miliseconds
  setTimeout(function() { callback(null, data); }, timeout);
};

var insertAll = function(coll, callback) {
  coll.forEach(function (nr) {
    asyncFn(nr, function(err,data) {
      console.log('‣', data);
    });
  });
  callback();
};

insertAll([1, 2], function() {
  console.log('done'); });</code></pre>
<p>this will not work as you probably think it does:

</p>
<pre><code class="sh">done
‣ 1
‣ 2</code></pre>
<p>the reason is that the <code>insertAll</code> function returns before the async function calls the callback so <code><span class="keyword">done</span></code> gets logged before the function is complete.

</p>
<h2>solving the problem with a module</h2>
<p>if you think implementing your own asynchronous iteration function is too much hassle there's plenty of modules out there that solve this problem. my favorite is <a href="https://github.com/caolan/async">async</a>. 

</p>
<p>in async the solution for this problem would be something like:

</p>
<pre><code class="js">async.forEach([1, 2], asyncFn, function(err, results){
   console.log('done');
});</code></pre>
<h1>to iterate is human, to recurse is divine</h1>
<p>when looking to the <a href="https://github.com/alessioalex/Nodetuts/blob/master/async_patterns/test.js">solution</a> to this problem without the help of a module it struct me as obvious how much all these algorithms work like pattern matching.

</p>
<ul>
<li>if the queue exists run some generic processing the queue function</li>
<li>if the queue is empty run the callback</li>
</ul>
<table>
  <tr>
    <th>queue</th>
    <th>execute</th>
  </tr>
  <tr>
    <td>empty</td>
    <td>call back</td>
  </tr>
  <tr>
    <td>has Elements</td>
    <td>iterate</td>
  </tr>
</table>

<h2>what is pattern matching?</h2>
<p>pattern matching is a recursive way to develop your programs where you define patterns for the program to identify and match those patterns with actions that should be executed.

</p>
<p>let's consider the very well understood <code><span class="identifier"><span class="keymethods">map</span></span></code> function that takes a collection and transforms each element by applying a function:

</p>
<pre><code class="js">[1,2,3].map(function duplicate(x) { return x*2; });</code></pre>
<p>if you solved this problem using pattern matching the execution of this function would be:

</p>
<pre><code><span class="identifier">transformed_map</span> = [];
<span class="identifier"><span class="keymethods">map</span></span><span class="symbol">:</span>
  <span class="identifier">l</span> = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]
    <span class="identifier">is</span> <span class="identifier">l</span> <span class="identifier">an</span> <span class="identifier">empty</span> <span class="identifier">array?</span>
      <span class="identifier">no</span>.
    <span class="identifier">is</span> <span class="identifier">l</span> <span class="identifier">anything?</span>
      <span class="identifier">yes</span>.
      <span class="identifier">head</span> = <span class="number">1</span>
      <span class="identifier">tail</span> = [<span class="number">2</span>,<span class="number">3</span>]
      <span class="identifier">transformed_map</span>.<span class="identifier"><span class="keymethods">shift</span></span>(<span class="identifier">duplicate</span>(<span class="number">1</span>));
      <span class="identifier"><span class="keymethods">map</span></span>([<span class="number">2</span>,<span class="number">3</span>])
<span class="identifier">transformed_map</span> = [<span class="number">2</span>];
<span class="identifier"><span class="keymethods">map</span></span><span class="symbol">:</span>
  <span class="identifier">l</span> = [<span class="number">2</span>,<span class="number">3</span>]
    <span class="identifier">is</span> <span class="identifier">l</span> <span class="identifier">an</span> <span class="identifier">empty</span> <span class="identifier">array?</span>
      <span class="identifier">no</span>.
    <span class="identifier">is</span> <span class="identifier">l</span> <span class="identifier">anything?</span>
      <span class="identifier">yes</span>.
      <span class="identifier">head</span> = <span class="number">2</span>
      <span class="identifier">tail</span> = [<span class="number">3</span>]
      <span class="identifier">transformed_map</span>.<span class="identifier"><span class="keymethods">shift</span></span>(<span class="identifier">duplicate</span>(<span class="number">2</span>));
      <span class="identifier"><span class="keymethods">map</span></span>([<span class="number">3</span>])
<span class="identifier">transformed_map</span> = [<span class="number">2</span>,<span class="number">4</span>];
<span class="identifier"><span class="keymethods">map</span></span><span class="symbol">:</span>
  <span class="identifier">l</span> = [<span class="number">3</span>]
    <span class="identifier">is</span> <span class="identifier">l</span> <span class="identifier">an</span> <span class="identifier">empty</span> <span class="identifier">array?</span>
      <span class="identifier">no</span>.
    <span class="identifier">is</span> <span class="identifier">l</span> <span class="identifier">anything?</span>
      <span class="identifier">yes</span>.
      <span class="identifier">head</span> = <span class="number">3</span>
      <span class="identifier">tail</span> = []
      <span class="identifier">transformed_map</span>.<span class="identifier"><span class="keymethods">shift</span></span>(<span class="identifier">duplicate</span>(<span class="number">3</span>));
      <span class="identifier"><span class="keymethods">map</span></span>([])
<span class="identifier">transformed_map</span> = [<span class="number">2</span>,<span class="number">4</span>,<span class="number">6</span>];
<span class="identifier"><span class="keymethods">map</span></span><span class="symbol">:</span>
  <span class="identifier">l</span> = []
    <span class="identifier">is</span> <span class="identifier">l</span> <span class="identifier">an</span> <span class="identifier">empty</span> <span class="identifier">array?</span>
      <span class="identifier">yes</span>.
      <span class="identifier"><span class="keyword">return</span></span> <span class="identifier">transformed_map</span>
[<span class="number">2</span>,<span class="number">4</span>,<span class="number">6</span>]</code></pre>
<h2>solving the problem with pattern</h2>
<p>i decided try to implement pattern matching in javascript as my <a href="http://js1k.com/">js1k</a> entry called functional love.

</p>
<p>the rules were simple: implement functions that allow you to do pattern matching in javascript without changing the language itself.

</p>
<p>this is what i came up to for the node tuts episode:

</p>
<pre><code class="js">insert_all([], function done() { console.log('done'); });
insert_all(_, function all(l) {
  insert_element(l.shift(), function (err, elem) {
    console.log('‣ ', elem);
    insert_all(l);
  });
});</code></pre>
<ul>
<li>if the array is empty, log the message done.</li>
<li>if its not empty, insert the element and when the callback is complete recursively call the <code>insert_all</code> function with the rest of the list.</li>
</ul>
<p>you can now call this function like this:

</p>
<pre><code class="js">insert_all([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);</code></pre>
<h2>how it works</h2>
<p>you probably noticed i use the same syntax to declare the insert all function and to call the function itself. what happens is the first time you call <code>pattern</code> it sets the arity of the function. is this case the first pattern has two arguments, meaning i should expect a function with one argument. whenever i call <code>insert_all</code> with one argument i'm calling the function.

</p>
<p>when you registered the first two patterns i created a fact table like:

</p>
<table>
  <tr>
    <th>list</th>
    <th>execute</th>
  </tr>
  <tr>
    <td>empty</td>
    <td>done()</td>
  </tr>
  <tr>
    <td>has elements</td>
    <td>all()</td>
  </tr>
</table>

<p>now when you call the <code>insert_all</code> function we need to iterate this fact table and see which rule applies. then call that function. simple. if the function wants to recurse it simply need to invoke the <code>insert_all</code> function.

</p>
<h1>mad science corner</h1>
<p>ok enough with the easy stuff. let's use pattern to implement a function that reverses an javascript array. asynchronously of course:

</p>
<pre><code class="js">reverse([5,4,3,2,1], function (list) { console.error(list); });</code></pre>
<p>we can do this using the <code>reduce</code> function that takes a list <code>l</code> and an accumulator <code>z</code> and returns something that was constructed by applying a function <code>f</code> to each element of the list <code>x</code> and the accumulator <code>z</code>.

</p>
<pre><code class="js">// pretending asynchronous behavior
// image this is some kind of echo server
function echo(z, x, cb) {
  setTimeout(function() {
    z.unshift(x); cb(z);
  }, Math.ceil(Math.random() * 100)); 
}

function reverse (l, cb) { reduce(echo, [], l, function(z) { cb(z); }); }</code></pre>
<p>now all we need is to implement the <code>reduce</code> function with pattern:

</p>
<pre><code class="js">var _;
reduce(_, _, [], _, function (f, z, l, cb) { cb(z); });
reduce(_, _, _, _, function (f, z, l, cb) {
  f(z, l.shift(), function (new_z) {
    reduce(f, new_z, l, cb);
  });
});</code></pre>
<p>get the full code for this example <a href="https://github.com/dscape/p/blob/master/samples/reverse_list_with_reduce.test.js">here</a>.

</p>
<h1>js1k</h1>
<p><code>pattern</code> is my <a href="http://js1k.com/">js1k</a> submission. it was a lot of fun to write. if you are wondering if you should submit an entry yourself you totally should.

</p>
]]></description><link>http://blog.nodejitsu.com/pattern-matching-in-javascript</link><guid isPermaLink="true">http://blog.nodejitsu.com/pattern-matching-in-javascript</guid><dc:creator><![CDATA[Nuno Job]]></dc:creator><pubDate>Mon, 20 Feb 2012 18:51:02 GMT</pubDate></item><item><title><![CDATA[<a href="./writing-cli-apps-with-flatiron">Writing CLI apps with Flatiron</a>]]></title><description><![CDATA[<p>Command-line interfaces (CLIs) are an often overlooked, but extremely important part of every developers workflow. Think about how different your day-to-day life would be if <code>git</code> functioned differently? Or (<strong>gasp</strong>) incorrectly or inconsistently? At Nodejitsu, we know CLI applications. The CLI for our public platform <a href="https://github.com/nodejitsu/jitsu">jitsu</a> is designed to be quick to get started, highly portable and above all: consistent and robust. With these principals in mind we took extra care designing Flatiron to be adaptable to our production-quality needs. 

</p>
<p>Flatiron is an adaptable decoupled framework for both node.js and the browser. An <strong>adaptable framework</strong> enables users to build multiple types of applications. In Flatiron we are focusing on:

</p>
<ul>
<li>Web applications (http and websockets)</li>
<li>Command line (CLI) applications</li>
<li>Front-end applications</li>
</ul>
<p>This article will focus on the tools at your disposal when using Flatiron to build CLI applications as well as how many existing Flatiron CLI applications are structured.

</p>
<ul>
<li><a href="/writing-cli-apps-with-flatiron/#getting-started">Getting started</a></li>
<li><a href="/writing-cli-apps-with-flatiron/#to-the-code">To the code!</a></li>
<li><a href="/writing-cli-apps-with-flatiron/#configuring-your-cli-app">Configuring your Command-line Application</a></li>
<li><a href="/writing-cli-apps-with-flatiron/#composable-cli-applications">Composable Command-line applications</a></li>
<li><a href="/writing-cli-apps-with-flatiron/#in-the-wild">Flatiron Command-line apps in the wild</a></li>
</ul>
<h2></h2>

<p><a name="getting-started"></a>
</p>
<h1>Getting started</h1>
<p>Writing a Command-line application with Flatiron starts out like writing every other flatiron application:

</p>
<pre>
  $ flatiron create simple-app cli
  info:   Creating application simple-app
  info:   Using cli scaffold.
  info:   Creating directory config
  info:   Creating directory lib
  info:   Creating directory commands
  info:   Creating directory test
  info:   Writing package.json
  info:   Writing app.js
  info:   Writing lib/index.js
  info:   Application simple-app is now ready
</pre>

<p>Lets examine the directory structure created by running <code>flatiron create simple-app cli</code>:

</p>
<pre>
  simple-app/
    app.js
    config/
    lib/
      index.js
      commands/
    package.json
    test/
</pre>

<p>With this simple scaffold the application has already been setup with:

</p>
<ul>
<li>Commands lazy-loaded from the file or directory specified by <code>options.source</code>.</li>
<li><code>app.cmd</code>: Helper function for creating CLI routes.</li>
<li><code>app.argv</code>: Parsed CLI arguments using <a href="https://github.com/substack/node-optimist"><code>optimist</code></a>.</li>
<li><code>app.config</code>: Hierarchical configuration sourced from: environment variables, CLI arguments and a JSON file in that order.</li>
<li><code>app.log</code>: Multi-transport logging using <a href="https://github.com/flatiron/winston"><code>winston</code></a>.</li>
<li><code><span class="identifier">app</span>.<span class="identifier"><span class="keyword">alias</span></span></code>: Helper function to alias shallow commands (e.g. <code>app config list</code> to <code>app conf</code>).</li>
<li><code><span class="identifier">app</span>.<span class="identifier"><span class="keymethods">inspect</span></span></code>: Robust object inspection and formatting using <a href="https://github.com/"><code>cliff</code></a>.</li>
<li><code>app.prompt</code>: CLI prompt using the Flatiron <a href="https://github.com/flatiron/prompt"><code>prompt</code></a> module.</li>
</ul>
<p>There are other options which make writing CLI applications quick and easy. Leave the tough stuff to us. 

</p>
<p><a name="to-the-code"></a>
</p>
<h1>To the code!</h1>
<p>Lets examine each line of the code generated by <code>flatiron create simple-app cli</code>:

</p>
<p><div class="snippet"><pre><code><span class="identifier">var</span> <span class="identifier">flatiron</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'flatiron'</span>),
    <span class="identifier">path</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'path'</span>),
    <span class="identifier">app</span> = <span class="identifier">flatiron</span>.<span class="identifier">app</span>;

<span class="identifier">app</span>.<span class="identifier">config</span>.<span class="identifier">file</span>({ <span class="identifier">file</span><span class="symbol">:</span> <span class="identifier">path</span>.<span class="identifier"><span class="keymethods">join</span></span>(<span class="identifier">__dirname</span>, <span class="string">'config'</span>, <span class="string">'config.json'</span>) });

<span class="identifier">app</span>.<span class="identifier">use</span>(<span class="identifier">flatiron</span>.<span class="identifier">plugins</span>.<span class="identifier">cli</span>, {
  <span class="identifier">source</span><span class="symbol">:</span> <span class="identifier">path</span>.<span class="identifier"><span class="keymethods">join</span></span>(<span class="identifier">__dirname</span>, <span class="string">'lib'</span>, <span class="string">'commands'</span>),
  <span class="identifier">usage</span><span class="symbol">:</span> <span class="string">'Empty Flatiron Application, please fill out commands'</span>
});

<span class="identifier">app</span>.<span class="identifier">start</span>();
</code></pre></div>

</p>
<h3>Setup up Configuration</h3>
<pre>
  app.config.file({ file: path.join(__dirname, 'config', 'config.json') });
</pre>

<p>Add a store to back the configuration for this application. It will automatically load <code>:pwd/config/config.json</code> from disk. 
<br><br>

</p>
<h3>Attach the CLI plugin</h3>
<pre>
  app.use(flatiron.plugins.cli, {
    source: path.join(__dirname, 'lib', 'commands'),
    usage: 'Empty Flatiron Application, please fill out commands'
  });
</pre>

<p>Attach Command-line functionality to the application. See <a href="#configuring-your-cli-app">Configuring your Command-line Application</a> for more detailed documentation.
<br><br>

</p>
<h3>Start the Application</h3>
<pre>
  app.start();
</pre>

<p>Initializes the application and then dispatches to the <a href="https://github.com/flatiron/director"><code>director</code></a> router using <code>app.argv._</code>. For example when running <code>app config get foo</code>, <code>app.argv._</code> will be <code>['app', 'config', 'get', 'foo']</code>.
<br><br>

</p>
<p><a name="configuring-your-cli-app"></a>
</p>
<h1>Configuring your Command-line Application</h1>
<p>There is a simple convention for passing options to both <code>flatiron.plugins.cli</code> and <code>flatiron.plugins.http</code>: <strong>the settings for the named property added to the application has the same name in the options passed to .use()</strong>. For example:

</p>
<p><div class="snippet"><pre><code><span class="comment">//</span>
<span class="comment">// </span>Configuring app.argv
<span class="comment">//</span>

app.use(flatiron.plugins.cli, {
  <span class="comment">//</span>
  <span class="comment">// </span>Settings used by `require('optimist').options()
  <span class="comment">//</span>
  argv: {
    login: {
      alias: 'l',
      description: 'Login to use',
      string: <span class="literal">true</span>
    }
  }
});

<span class="comment">//</span>
<span class="comment">// </span>`app.argv.l` is now available
<span class="comment">//</span>
console.log(app.argv.l);</code></pre></div>

</p>
<p>There are some important settings you need to be aware of:

</p>
<ul>
<li><code>source {string}</code>: File or directory on disk to lazy load commands from. In the case of a directory, the names of the files map to the first parameter in <code>app.argv._</code>.</li>
<li><code>usage {string|Array}</code>: Help text to display when using <code>app help</code></li>
<li><code>argv {Object}</code>: Settings for CLI options parsing.</li>
<li><code>prompt {Object}</code>: Settings for Flatiron <a href="https://github.com/flatiron/prompt"><code>prompt</code></a> module.</li>
<li><code>version: {boolean}</code>: Automatically sets up response for <code>app --version</code> and <code>app -v</code></li>
<li><code>async: {boolean}</code>: If <code><span class="literal">true</span></code> configures the CLI router attached to the application to be asynchronous. See the <a href="https://github.com/flatiron/director#async-routing"><code>director</code></a> documentation for more information.</li>
</ul>
<p><a name="composable-cli-applications"></a>
</p>
<h1>Composable Command-line applications</h1>
<p>Flatiron enables developing adaptable applications through a lightweight dependency injection system called <a href="https://github.com/flatiron/broadway"><code>broadway</code></a>. Writing <code>broadway</code> plugins is easy and can be used to easily compose applications out of reusable components. This was the motivation behind a new CLI-plugin for Flatiron released today: <a href="https://github.com/flatiron/cli-config"><code>flatiron-cli-config</code></a>. This plugin extends the application by adding handlers for <code>app config *</code>. It also adds help for all of these commands available through <code>app help config *</code>:
<br><br>

</p>
<ul>
<li><code>app config list</code>: Lists all key-value pairs known to the application.</li>
<li><code>app config get &lt;key&gt;</code>: Displays the value for <key> to the user.</key></li>
<li><code>app config <span class="keyword">set</span> &lt;key&gt; &lt;value&gt;</code>: Sets the <key> to the specified value. </key></li>
<li><code>app config <span class="keyword">delete</span> &lt;key&gt;</code>: Clears the value for the specified <key>.</key></li>
</ul>
<p>Using this plugin is simple:

</p>
<pre>
  app.use(require('flatiron-cli-config'));
</pre>

<p><strong>That's it.</strong> Your application is now fully setup to use edit configuration files from the command-line.

</p>
<p><a name="in-the-wild"></a>
</p>
<h1>Flatiron Command-line applications in the wild</h1>
<p>Since we released Flatiron there have been a number of interesting applications released and refactored:

</p>
<ul>
<li><a href="https://github.com/vesln/issues">issues</a>: Github Issues from the CLI</li>
<li><a href="https://github.com/vesln/box">box</a>: Powerful key -&gt; value storage for the CLI. </li>
<li><a href="https://github.com/vesln/todo">todo</a>: Todos in the CLI like what.</li>
<li><a href="https://github.com/indexzero/npmcount">npmcount</a>: Silly program that counts number of npm packages from one or more users.</li>
<li><a href="http://github.com/nodejitsu/jitsu/compare/master...flatiron">jitsu</a>: Flawless command line deployment of your Node.js apps to the cloud.</li>
</ul>
<p>Well that about wraps it up. Can't wait to see what crazy things I'll be able to do from the CLI soon!
<br><br><br><br>


</p>
]]></description><link>http://blog.nodejitsu.com/writing-cli-apps-with-flatiron</link><guid isPermaLink="true">http://blog.nodejitsu.com/writing-cli-apps-with-flatiron</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Wed, 08 Feb 2012 08:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./what-is-node-spdy">What the $%@! is SPDY</a>]]></title><description><![CDATA[<p>You may know about SPDY, an experimental protocol for a faster web <a href="http://www.chromium.org/spdy/spdy-whitepaper"><a href="http://www.chromium.org/spdy/spdy-whitepaper">http://www.chromium.org/spdy/spdy-whitepaper</a></a> announced by Google in 2009. SPDY is now supported by two major browsers (Google Chrome and Mozilla Firefox) and it’s running on most of Google’s servers (also soon to be supported by nginx).

</p>
<p>The main goal of SPDY is reducing the latency of web pages by multiplexing multiple http streams into one TCP connection and compressing http headers.

</p>
<p>So instead of creating a TCP connection for each http request (like styles, scripts, images, or even ajax), SPDY-enabled browser will hold only one connection with the server.

</p>
<h2></h2>

<p><br>
<img src="what-is-node-spdy/cwnd.png"><br>
source: <a href="http://www.igvita.com/2011/10/20/faster-web-vs-tcp-slow-start"><a href="http://www.igvita.com/2011/10/20/faster-web-vs-tcp-slow-start">http://www.igvita.com/2011/10/20/faster-web-vs-tcp-slow-start</a></a>

</p>
<p>Your server can tell the browser that it supports SPDY in two ways: setting the ‘Alternate-Protocol’ header, or by using a TLS handshake extension NPN (Next Protocol Negotiation). In the second case the server will send the supported protocols (i.e., SPDY/2 HTTP/1.1 HTTP/1.0) to browser before any data transfer will be performed, and the browser will choose the protocol that is preferable for the client.

</p>
<p>You can learn more about SPDY by examing the protocol specification: <a href="http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft2"><a href="http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft2">http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft2</a></a>
<br><br>

</p>
<h1>Node.js and SPDY</h1>
<p>The growing interest in both the SPDY protocol and Node.js created the need for a stable Node.js SPDY module when the first version was released last year. There were a number of issues with this first implementation: it was buggy, it did not support the default node.js builds, and it was incompatible with popular frameworks (only partial express support, and no socket.io support at all). Despite all of these issues it still attracted considerable some attention from the Node.js community.

</p>
<p>Before continuing development on node-spdy it was clear that node.js core needed to be improved: the tls module was lacking NPN support, and there was no zlib functionality. While adding NPN callbacks to node was quite simple, I found that almost every OS has old SSL libraries without support for it. That’s why latest node version bundles openssl in it’s deps/ folder. Thanks to Isaac Z. Schlueter, zlib module was added in 0.6.0 version of node.js, and required only a little patching: it was missing stream dictionary support.

</p>
<p>With all that working out of the box (only in 0.7.0-pre version of node now) I decided to start developing a completely new stable node-spdy version. You can take a look at what I’ve done so far at <a href="https://github.com/indutny/node-spdy">https://github.com/indutny/node-spdy</a> . Note that to test it you’ll need to build v0.7.0-pre of node.js (currently at github’s master branch):

</p>
<pre>
  git clone <a href="git://github.com/joyent/node.git">git://github.com/joyent/node.git</a>
  cd node
  [sudo] ./configure
  [sudo] make
  [sudo] make install
</pre>

<p>I have one running SPDY server running at <a href="https://spdy-twitlog.indutny.com/"><a href="https://spdy-twitlog.indutny.com/">https://spdy-twitlog.indutny.com/</a></a>. It’s demonstrating socket.io + express support of node-spdy module.

</p>
<p><br><br>
</p>
<h1>Features &amp; Roadmap</h1>
<h2>Implemented:</h2>
<ul>
<li>Node.js compatible interface (same as for require(‘http’).Server )</li>
<li>Opening/closing streams</li>
<li>Fallback to https</li>
<li>Basic flow management (no WINDOW management so far, that means .pause() and .resume() will just buffer data internally instead of sending WINDOW_UPDATE to client)</li>
<li>Protocol errors handling</li>
<li>Stream scheduler (for priority management)</li>
<li>Push streams</li>
</ul>
<h2>Roadmap:</h2>
<ul>
<li>WINDOW_UPDATE and INITIAL_WINDOW_SIZE</li>
<li>Fixing bugs</li>
</ul>
<p><br><br>
</p>
]]></description><link>http://blog.nodejitsu.com/what-is-node-spdy</link><guid isPermaLink="true">http://blog.nodejitsu.com/what-is-node-spdy</guid><dc:creator><![CDATA[Fedor Indutny]]></dc:creator><pubDate>Wed, 25 Jan 2012 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./introducing-blacksmith">Introducing Blacksmith</a>]]></title><description><![CDATA[<p><strong>Github</strong>: <a href="https://github.com/flatiron/blacksmith">https://github.com/flatiron/blacksmith</a><br><strong>Documentation/Example</strong>: <a href="http://blacksmith.jit.su">http://blacksmith.jit.su</a>

</p>
<p>Blacksmith is a static site generator. It uses <a href="https://github.com/hij1nx/weld">weld</a>, <a href="https://github.com/tmpvar/jsdom">jsdom</a> and <a href="https://github.com/chjj/marked">marked</a> to turn json, markdown  and 100% genuine HTML and CSS, on the filesystem, into awesome sites like the one you're looking at right now. Moreover, it includes a command line interface for quickly building, editing and testing blacksmith-built websites. Here's a short list of features:

</p>
<ul>
<li>Easy to use</li>
<li>Can be hosted anywhere, since it generates static HTML/CSS</li>
<li>Write and Edit articles on the file system using github-flavored markdown</li>
<li>Based on JSDOM and Weld</li>
<li>Easily create custom themes using plain HTML and CSS ( <strong>no micro-templating</strong> ! )</li>
<li>Default theme is a port of scribbish by Jeffrey Allan Hardy</li>
<li>Ships with a robust node.js static server suitable for production</li>
</ul>
<p>Blacksmith may remind you a bit of <a href="https://github.com/mojombo/jekyll">jekyll</a> and <a href="http://octopress.org/">octopress</a>, and in fact it is influenced by these projects. However, whereas jekyll is "blog-aware" and uses liquid for templating, blacksmith uses the DOM for its templating needs and can easily generate not just blogs, but documentation sites and <em>more</em>. Plus, you don't need ruby or rake since it's all written in node.

</p>
<h2>Why Static?</h2>
<p>We knew from the start that we wanted our blog platform to generate a static site. Why? Static sites are fast, foolproof, and get the job done. Why dynamically generate a page each time if you only have to do it once?

</p>
<p>This might seem counterintuitive, considering all of the real-time, client-side code in Nodejitsu. However, while websockets and hash-based routing fit really well for many problems, others, like our blog, simply don't need it.

</p>
<h2>Why Weld?</h2>
<p>We also knew from the start that we wanted to <a href="/micro-templates-are-dead">avoid microtemplates</a>. Hij1nx puts it pretty well, but to reiterate: Templates are 100% HTML and css, and <em>that</em> is <em>awesome</em>.

</p>
<p>Given this question, you may ask "why not <a href="https://github.com/flatiron/plates">plates</a>?" Truth be told, we began this project before plates was ready for prime time. There is, however, a good reason not to switch: Having access to a full dom allows for doing such things as using jquery server-side, for the utmost in flexibility.

</p>
<h2>Try it out!</h2>
<p>Just visit blacksmith's <a href="https://github.com/flatiron/blacksmith">github repository</a>, install it and have fun!
</p>
]]></description><link>http://blog.nodejitsu.com/introducing-blacksmith</link><guid isPermaLink="true">http://blog.nodejitsu.com/introducing-blacksmith</guid><dc:creator><![CDATA[Josh Holbrook]]></dc:creator><pubDate>Sat, 14 Jan 2012 09:18:49 GMT</pubDate></item><item><title><![CDATA[<a href="./building-an-anonymous-cloud-database">Building an anonymous cloud database</a>]]></title><description><![CDATA[<p>As part of my <a href="http://blog.nodejitsu.com/fault-tolerant-applications-in-nodejs">ongoing quest</a> to develop <a href="http://en.wikipedia.org/wiki/Skynet_(Terminator)">Skynet</a>, I've been thinking a lot about the decentralized storage and distribution of small amounts of state in a peer-to-peer environment. With new privacy laws, the internet is fundamentally changing in a way we have not seen before. It's up to us, the developers to make sure the internet remains a fair and open place.

</p>
<p>In software application development we usually store application state in <a href="http://en.wikipedia.org/wiki/Volatile_memory">volatile</a> and <a href="http://en.wikipedia.org/wiki/Non-volatile_memory">non-volatile</a> <a href="http://en.wikipedia.org/wiki/Random-access_memory">random access memory</a>. We also use <a href="http://en.wikipedia.org/wiki/Computer_networking_device">network devices</a> to communicate state between our application and a central provider or server. We store state in things like databases, the file-system and cloud hosting providers. This approach is recommended for most applications, but when we start to think about the implications of building large, distributed, and decentralized applications, we begin to rethink about how these applications are going to store and maintain state.

</p>
<p><br>

</p>
<p><strong>In some way or another, almost anything can store state. Any device that can be written to, then read from later can be used to store state.</strong>

</p>
<p>Think of it like this:

</p>
<p><strong>There are hundreds of thousands of endpoints on the web right now that you can post some sort of data to, and read it back later. Why not make a database out of that?</strong>

</p>
<h1>#</h1>
<h1>Basic strategies in building a decentralized and anonymous database</h1>
<ol>
<li>No central servers. A central server is a central point of failure.</li>
<li>No central authorities. A central authority over control of the database indicates another ( and much worse ) central point of failure.</li>
<li>Ability to encrypt and obscure data.</li>
<li>Ability to run in any combination of local / cloud / hosted. The database should be able to run locally, on hosted servers, and in the cloud.</li>
<li>Ability to easily share and replicate data. The data should be able to easily transfer and replicate between multiple systems and users.</li>
</ol>
<p>The goals of building a decentralized and anonymous database are fairly straight forward. The data needs to have no central point of failure ( technological or political ). The data needs to be able to be secured. The data needs to be accessible and sharable.

</p>
<h1>Introducing hnet</h1>
<p><a href="http://github.com/hookio/hnet/">hnet</a> is a decentralized and anonymous database built in <a href="http://nodejs.org">node.js</a>. It works by spreading small amounts of information across several nodes using a variety of non-traditional storage engines. 

</p>
<p><a href="http://github.com/hookio/hnet/"><a href="http://github.com/hookio/hnet/">http://github.com/hookio/hnet/</a></a>

</p>
<h1>What is an hnet node?</h1>
<p>An hnet node is <strong>anything</strong> that we can store a <em>small</em> amount of data which we can eventually read back later. The <a href="http://github.com/hookio/hnet">hnet client</a> communicates with many hnet nodes in order to establish a dataset. 

</p>
<h1>What is an hnet storage engine?</h1>
<p>A storage engine can be considering a wrapper for any service on the web that can store data, and read it back later. Storage engines are small and pluggable, so it should be very easy to author new engines. Some examples of engines are: gist, pastebin, imgur, google groups, reddit, twitter, irc, etc... The only real requirement for a storage engine is that it can store state, the rest is up to your imagination.

</p>
<h1>Why hnet?</h1>
<p><a href="http://github.com/hookio/hnet/">hnet</a> was originally built as an easy way to provide distributed and semi-anonymous tables of server ips and ports for <a href="hook.io">hook.io</a> hooks. hnet helps provide hook.io a way of auto-discovery other hooks over a <a href="http://en.wikipedia.org/wiki/Wide_area_network">Wide Area Network</a>. <strong>Note:</strong> hook.io already supports auto-discovery over the <a href="http://en.wikipedia.org/wiki/Local_area_network">Local Area Network</a> via <a href="http://en.wikipedia.org/wiki/Multicast_DNS">mdns</a>.

</p>
<h1>How does hnet work?</h1>
<h2>Many dumb hnet nodes, <a href="http://github.com/hookio/hnet/">one smart client</a>.</h2>
<p><img src="building-an-anonymous-cloud-database/hnet-client.png">

</p>
<p><strong>In order to query <a href="http://github.com/hookio/hnet">hnet</a>, first we connect to a few "top-level" nodes</strong> 

</p>
<p><img src="building-an-anonymous-cloud-database/top-level-nodes.png">

</p>
<p>If you are not maintaining your own <a href="http://github.com/hookio/hnet">hnet</a>, the <a href="http://github.com/hookio/hnet">hnet client</a> will fall-back to a few semi-moderated top level nodes. If you don't feel comfortable having someone else moderate your data, it's trivial to setup your own piece of <a href="http://github.com/hookio/hnet">hnet</a>.

</p>
<p>You will notice that <a href="http://github.com/hookio/hnet">hnet</a> uses <a href="http://iriscouch.com">Iriscouch</a> for many of it's top-level nodes and that most nodes eventually link back to <a href="http://hnet.iriscouch.com/public"><a href="http://hnet.iriscouch.com/public">http://hnet.iriscouch.com/public</a></a>. <a href="http://iriscouch.com">Iriscouch</a> provides free hosted <a href="http://en.wikipedia.org/wiki/CouchDB">CouchDB</a> as a service. It allows you to signup for a free CouchDB instance instantly and with minimal registration. IrisCouch was chosen for both it's high quality of service, and the fact the lead developer of the service <a href="https://github.com/jhs">Jason Smith</a> is an active open-source and open-data advocate.

</p>
<p><strong>Note:</strong> Our <a href="http://github.com/nodejitsu/jitsu">node.js deployment tool</a> <code>jitsu</code> also ships with a nifty command <code>jitsu databases create couch</code>, which will instantly give you a CouchDB instance through IrisCouch. 

</p>
<h1>The hnet protocol is JSON</h1>
<p><strong>the hnet protocol supports arbitrary JSON data, and optional <a href="http://en.wikipedia.org/wiki/JSON-RPC">JSON-RPC</a> commands</strong>

</p>
<p>Here is an example of what a JSON fragment returned from an hnet node might look like:

</p>
<p><img src="building-an-anonymous-cloud-database/client-query-node.png">

</p>
<p><strong>example JSON returned from hnet node:</strong>

</p>
<pre><code>[
  { "foo": "bar", "tar": "val" },
  { "foo": "boo", "something": ["a","b","c"] },
  { "foo": "bar", "tar": "val" },
]</code></pre>
<p><strong>optional JSON-RPC commands can be embedded</strong>

</p>
<p><a href="http://github.com/hookio/hnet">hnet</a> <strong>optionally</strong> parses these <a href="http://en.wikipedia.org/wiki/JSON-RPC">JSON-RPC</a> commands.

</p>
<p><img src="building-an-anonymous-cloud-database/JSON-RPC-Commands.png">

</p>
<pre><code>[
  { "foo": "boo", "something": ["a","b","c"] },
  { "method": "link", params: [ 
      { "type": "couch", "uri": "http://hnet.iriscouch.com/public/0" }
    ] 
  },
  { "foo": "bar", "tar": "val" }
]</code></pre>
<p>If we look at the array item from the previous JSON fragment, we can see:

</p>
<pre><code>{ "method": "link", params: [ { "type": "couch", "uri": "http://hnet.iriscouch.com/public/0"} ] },</code></pre>
<h1>The <em>link</em> method is particularly important.</h1>
<h1>It indicates that we should lazily link this document from a remote dataset into the current position in the item array.</h1>
<h1>This allows us to create large datasets from many small hnet nodes.</h1>
<p><strong>hnet client receives data from many nodes</strong>


</p>
<p>After hnet is able to query a few top-level nodes, it begins to crawl several other linked hnet nodes and merges the data locally.


</p>
<p><img src="building-an-anonymous-cloud-database/client-many-nodes.png">

</p>
<p><strong>Saving data to hnet</strong>

</p>
<p><a href="http://github.com/hookio/hnet">hnet</a> could be considered an append-only database. <a href="http://github.com/hookio/hnet">hnet</a> is designed to create new nodes instead of attempting to edit existing nodes. Every time a new hnet node is created, it links back to at least two existing nodes.

</p>
<p><img src="building-an-anonymous-cloud-database/saving-data.png">

</p>
<p>Since every new node created links back to at least two other known hnet nodes, all newly created hnet nodes will eventually link back to the first nodes we started querying.


</p>
<h1>Establishing a TTL ( Time To Live ) for circular link resolution</h1>
<p>By default, the <a href="http://github.com/hookio/hnet">hnet</a> client will not attempt to resolve circular JSON-RPC links. You can enable circular linking by specifying the <code>ttl</code> parameter in the <a href="http://github.com/hookio/hnet">hnet</a> constructor.

</p>
<p><strong>Ex:</strong>

</p>
<pre><code><span class="keyword">var</span> Hnet = require(<span class="string">'../lib/hnet'</span>).Hnet;

<span class="keyword">var</span> hnet = <span class="keyword">new</span> Hnet({
  ttl: <span class="number">5000</span>
});

hnet.load();</code></pre>
<p>The <code>ttl</code> parameter indicates that the <a href="http://github.com/hookio/hnet">hnet client</a> will resolve any circular links it encounters, after a delay of 5,000 milliseconds. If a <code>ttl</code> is specified, the <a href="http://github.com/hookio/hnet">hnet</a> client will continue to crawl <a href="http://github.com/hookio/hnet">hnet</a> forever, or until the circular link becomes broken due to specific <a href="http://github.com/hookio/hnet">hnet</a> nodes becoming unavailable. 

</p>
<p><img src="building-an-anonymous-cloud-database/circular-propigation.png">

</p>
<h1>A quick note on Steganography and Cryptography</h1>
<p><a href="http://github.com/hookio/hnet">hnet</a> exposes simple <code>Hnet.get</code> and <code>Hnet.save</code> methods. It's fairly trivial to perform whichever cryptography you want on the data before you save it, and when you retrieve it. <a href="http://github.com/hookio/hnet">hnet</a> also provides an <em>optional</em> interface for specifying un-encrypted metadata with encrypted data. This approach allows you to use <a href="http://github.com/hookio/hnet">hnet</a> with most existing cryptography standards.

</p>
<p><a href="http://en.wikipedia.org/wiki/Steganography">Steganography</a> is the art and science of writing hidden messages in such a way that only the sender and intended recipient are aware of the existence of the message. It can be considered a form of <a href="http://en.wikipedia.org/wiki/Security_through_obscurity">security through obscurity</a>. Many <a href="http://github.com/hookio/hnet">hnet</a> storage engines use some form of steganography. The advantage of using steganography in conjunctions with cryptography, is that messages do not attract attention to themselves. Cryptography can protect the contents of a message, but steganography can obscure the fact that a message even exists.


</p>
<p><br>
<br>
<br>

</p>
]]></description><link>http://blog.nodejitsu.com/building-an-anonymous-cloud-database</link><guid isPermaLink="true">http://blog.nodejitsu.com/building-an-anonymous-cloud-database</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Mon, 09 Jan 2012 07:00:20 GMT</pubDate></item><item><title><![CDATA[<a href="./fault-tolerant-applications-in-nodejs">Fault tolerant applications in nodejs</a>]]></title><description><![CDATA[<p>As part of my ongoing quest to develop <a href="http://en.wikipedia.org/wiki/Skynet_(Terminator)">Skynet</a>, I've been deep diving into distributed computing.

</p>
<p>At <a href="http://nodejitsu.com">Nodejitsu</a>, our node.js hosting platform deals with 1000s of live servers spanned across multiple data-centers. As scale increases, minute statistical probabilities become very real problems. The network is unreliable, disks become unwritable, streams break, unexpected input is unexpected, and entire data-centers can go down.

</p>
<p>Think of it like this: 

</p>
<p><strong>If you have 1,000 servers each individually rated at 99.9% uptime, on average, one of those machines is always failing.</strong>

</p>
<h1>#</h1>
<p><strong>So we research...</strong>

</p>
<p><a href="http://en.wikipedia.org/wiki/Fault-tolerant_system">Fault tolerant system</a> <br>
<a href="http://en.wikipedia.org/wiki/Fallacies_of_Distributed_Computing">Fallacies of Distributed Computing</a><br>
<a href="http://en.wikipedia.org/wiki/Distributed_computing#Properties_of_distributed_systems">Properties of distributed systems</a><br>
<a href="http://en.wikipedia.org/wiki/High_availability#Percentage_calculation">High availability Percentage calculation</a><br>

</p>
<p><strong>and we research more...</strong>

</p>
<p><a href="http://en.wikipedia.org/wiki/Shared_nothing_architecture">Shared nothing architecture</a><br>
<a href="http://en.wikipedia.org/wiki/Byzantine_fault_tolerance">Byzantine fault tolerance</a><br>
<a href="http://en.wikipedia.org/wiki/Paxos_(computer_science)">Paxos</a><br>

</p>
<p><strong>Eventually, we hit the</strong> <a href="http://en.wikipedia.org/wiki/Halting_problem">The Halting Problem</a>: 

</p>
<p><em>Given a description of a computer program, decide whether the program finishes running or continues to run forever. In 1936, <a href="http://en.wikipedia.org/wiki/Alan_Turing">Alan Turing</a> proved that a general algorithm to solve the halting problem for all possible program-input pairs <strong>cannot</strong> exist.</em>

</p>
<p>to summarize all of these links in the context of this blog post...

</p>
<p><br>

</p>
<h1>It's mathematically impossible your distributed application is not going to fuck up. Deal with it.</h1>
<hr>

<p><br>

</p>
<h1>Basic strategies in building fault tolerant applications in node</h1>
<ol>
<li>The operating system's RAM, processes, and file descriptors are relatively cheap. Use them as needed.</li>
<li>Use JSON to pass data between nodes. ( see: <a href="https://github.com/nodejitsu/nssocket">nssocket</a> or <a href="http://github.com/substack/dnode">dnode</a> ).</li>
<li>Embrace <a href="http://en.wikipedia.org/wiki/Crash-only_software">crash-only design</a>. Nodes should be able to disconnect, restart and reconnect as fast as possible with minimal impact.</li>
<li>Never assume any one node process will never go down. Assume that any process can go down for any reason at any time.</li>
</ol>
<p>The last point is particularly important. If your application is unable to recover from a "central" node going down, it should not be considered fault tolerant.

</p>
<p><br>

</p>
<h1>hook.io</h1>
<p><a href="http://hook.io">hook.io</a> is a distributed input/output framework for node.js. It allows you to seamlessly link together several processes and start sending messages between them. hook.io also provides <a href="http://hook.io">a rich network</a> of stand-alone hook libraries for adding additional i/o sources. In a sense, hook.io can be described as a next generation <a href="http://en.wikipedia.org/wiki/Enterprise_service_bus">enterprise service bus</a>.

</p>
<ul>
<li>Email List: <a href="http://groups.google.com/group/hookio"><a href="http://groups.google.com/group/hookio">http://groups.google.com/group/hookio</a></a></li>
<li>Video Lessons: <a href="http://youtube.com/maraksquires"><a href="http://youtube.com/maraksquires">http://youtube.com/maraksquires</a></a> ( <a href="https://github.com/hookio/tutorials">mirror</a> )</li>
<li>Wiki Pages <a href="https://github.com/hookio/hook.io/wiki/_pages"><a href="https://github.com/hookio/hook.io/wiki/_pages">https://github.com/hookio/hook.io/wiki/_pages</a></a> </li>
<li><a href="http://ejeklint.github.com/2011/09/23/hook.io-for-dummies-part-1-overview/">hook.io for dummies</a></li>
<li><a href="http://blog.nodejitsu.com/distribute-nodejs-apps-with-hookio">Distribute Node.js Apps with hook.io: </a></li>
<li>#nodejitsu on irc.freenode.net</li>
</ul>
<p><br>

</p>
<h1>Basic Paxos</h1>
<p><a href="http://en.wikipedia.org/wiki/Paxos_(computer_science)#Basic_Paxos
">Paxos</a> is a family of protocols for solving consensus in a network of unreliable processors. <a href="http://en.wikipedia.org/wiki/Consensus_(computer_science">Consensus</a> is the process of agreeing on one result among a group of participants. This problem becomes difficult when the participants or their communication medium may experience failures.

</p>
<p>As of v0.8.6, <a href="http://hook.io">hook.io</a> now has the ability to do a very basic consensus among all hooks to ensure recovery if <strong>any</strong> hooks die. 

</p>
<p>In previous versions of hook.io, if the "master" or "central" server hook went down, all other hooks would stop communicating. 

</p>
<p>Now, hook.io is able able to recover from the "central" server hook going down.

</p>
<p><img src="fault-tolerant-applications-in-nodejs/spokes-hub.png">

</p>
<p><br>

</p>
<p>Previously, when the hub went missing, none of the spokes knew where to connect anymore.

</p>
<p><img src="fault-tolerant-applications-in-nodejs/spokes-missing-hub.png">

</p>
<p><br>

</p>
<h1>Building fault-tolerant node.js application with hook.io</h1>
<p>hook.io can be used programatically or as stand-alone binary. For simplicity, we will assume in this example that you are using <code>hookio</code> as a binary application, and with all it's default settings. 

</p>
<p>For more examples of using hook.io programtically check out the <a href="https://github.com/hookio/hook.io/tree/master/examples">examples</a> or <a href="https://github.com/hookio/hook.io/tree/master/test">test</a> folders.

</p>
<p><strong>To install hook.io with npm</strong>

</p>
<pre><code> npm install hook.io -g</code></pre>
<p><em>Now, we are going to start up three instances of <code>hookio</code> in our terminal.</em>

</p>
<p><strong>Terminal 1</strong>

</p>
<pre><code> hookio</code></pre>
<p><strong>Terminal 2</strong>

</p>
<pre><code> hookio</code></pre>
<p><strong>Terminal 3</strong>

</p>
<pre><code> hookio</code></pre>
<p>Using hook.io's default auto-discovery functionality the first terminal will take the role of server, and the second and third terminals will connect as clients to the first terminal.

</p>
<p><img src="fault-tolerant-applications-in-nodejs/consensus.png">

</p>
<p><br>

</p>
<p>Now, kill the first hook terminal with <code>CTRL-C</code>. The second hook will take over the role of the server. The third hook will now know to connect  to the second hook instead of the first.

</p>
<p><img src="fault-tolerant-applications-in-nodejs/recovery.png">

</p>
<p>It might not seem very impressive, but it demonstrates a basic example of how to build fault-tolerant multi-process distributed applications in node.js

</p>
<h1>Applications built with hook.io now have no central point of failure.</h1>
<h1>But wait, there's more!!!</h1>
<h1>mdns</h1>
<p><a href="http://en.wikipedia.org/wiki/Multicast_DNS">Multicast DNS (mdns)</a> is a way of using <a href="http://en.wikipedia.org/wiki/Domain_Name_System">DNS</a> programming interfaces, packet formats and operating semantics on a small network where no DNS server is running. The mDNS protocol is used by Apple's <a href="http://en.wikipedia.org/wiki/Bonjour_(software)">Bonjour<a></a> and Linux <a href="http://en.wikipedia.org/wiki/Avahi_(software)">Avahi<a></a> service discovery systems. mdns is an easy way to help networked devices find each other without any prior configuration.

</a></a></p>
<p>As of v0.8.6, <a href="http://hook.io">hook.io</a> now has <strong>alpha</strong> support for <a href="http://en.wikipedia.org/wiki/Zeroconf">zero configuration networking</a> via mdns. This means that if you <code>hookio -m</code> on two machines on the same <a href="http://en.wikipedia.org/wiki/Local_area_network">Local Area Network</a>...they will find each other and instantly start communicating without any configuration!

</p>
<p><strong>Computer A</strong>

</p>
<pre><code> hookio -m</code></pre>
<p><strong>Computer B</strong>

</p>
<pre><code> hookio -m</code></pre>
<p>Now these two computers ( connected over a LAN, with no central DNS server ) will automatically discovery each other and begin to transmit messages.

</p>
<p>Think of the possibilities! 

</p>
<h1>Conclusion</h1>
<p>With the new mdns and paxos features, hook.io is getting better everyday. The current goal is to stabilize this new functionality in the 0.8.x branch across all platforms.

</p>
<p>The next steps will be p2p hook trackers and hosted hook services...
</p>
]]></description><link>http://blog.nodejitsu.com/fault-tolerant-applications-in-nodejs</link><guid isPermaLink="true">http://blog.nodejitsu.com/fault-tolerant-applications-in-nodejs</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Tue, 27 Dec 2011 04:50:20 GMT</pubDate></item><item><title><![CDATA[<a href="./package-json-cheat-sheet">package.json cheat sheet</a>]]></title><description><![CDATA[<p><a href="http://npmjs.org">npm</a> is the node package manager. 

</p>
<p>It helps you manage your <a href="http://nodejs.org">node.js</a> modules and dependencies.

</p>
<p>Previously, we created <a href="http://blog.nodejitsu.com/npm-cheatsheet">a npm cheat sheet</a> describing various NPM commands.

</p>
<p>Now, here is <a href="http://package.json.nodejitsu.com">a package.json cheat sheet</a> for exploring various properties of npm's package.json format.

</p>
<p>Enjoy the package.json cheatsheet!

</p>
<h2> </h2>
<p><a href="http://package.json.nodejitsu.com"><img src="/package-json-cheat-sheet/screenshot.png"></a>
</p>
]]></description><link>http://blog.nodejitsu.com/package-json-cheat-sheet</link><guid isPermaLink="true">http://blog.nodejitsu.com/package-json-cheat-sheet</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Sun, 25 Dec 2011 17:55:28 GMT</pubDate></item><item><title><![CDATA[<a href="./travis-ci-at-nodejitsu">Travis CI At Nodejitsu</a>]]></title><description><![CDATA[<p>If you watch <a href="https://github.com/nodejitsu">flatiron repositories on GitHub</a>, you may have started noticing these:

</p>
<p><img src="travis-ci-at-nodejitsu/director-travis.png">

</p>
<p>These are <a href="http://travis-ci.org">Travis CI</a> <a href="http://about.travis-ci.org/docs/user/status-images/">build status images</a>. We started testing our code at Travis CI and we want to tell the whole world about it!

</p>
<p><br>

</p>
<h2> </h2>
<p><br>

</p>
<h1>What is Travis CI?</h1>
<p>Travis CI is a <a href="http://en.wikipedia.org/wiki/Continuous_integration">continuous integration system</a>. Long story short: continuous integrations systems run your tests. How is it different from running them yourself?

</p>
<ul>
<li>clean environment - your local development environment can be pretty weird and you know it! People who use your code don't necessarily have the same settings as you have</li>
<li>easy creation of test environments</li>
<li>it actually <em>runs</em> the tests - continuous integration system won't say 'this change is so small that it can't mess anything up'</li>
<li>build logs are publicly visible - transparency is important, especially when it's about something other people rely on</li>
<li>it's nearly realtime - we often push code and almost instantly get notified about test results</li>
</ul>
<p><strong>tl;dr</strong>:<br>
<img src="travis-ci-at-nodejitsu/run-the-tests.png" alt="Run the fucking tests">

</p>
<p><br>


</p>
<h1>Why is it important for a CI to be realtime?</h1>
<p>People make mistakes. Developers forget to <code><span class="identifier">npm</span> <span class="identifier"><span class="keymethods">update</span></span></code> before <code><span class="identifier">npm</span> <span class="identifier"><span class="keymethods">test</span></span></code>, keep their temporatory files and so on. You can probably write down a long list of silly mistakes you sometimes make. This can lead to pushing failing code.

</p>
<p><br>


</p>
<p><img src="travis-ci-at-nodejitsu/failing-code.png" alt="Checked in failing code?">

</p>
<p><br>

</p>
<p>Of course, Marak doesn't do that. At least nobody can confirm it.

</p>
<p>Few days ago, thanks to Travis, we were able to find a <a href="http://travis-ci.org/#!/flatiron/union/builds/348518">regression</a> in <a href="https://github.com/flatiron/union.git">union</a>. It turned out to be a dependency failure, which we were able to fix in approximately 5 minutes.

</p>
<p>So, we <em>delivered</em> a product in 5 minutes. Sounds like a heaven for project managers.

</p>
<p>OK, so how does this "realtime" thing look like? Many of us spend our time on #nodejitsu IRC channel at Freenode. Thus, a natural thing was to enable IRC notifications for builds.


</p>
<p><img src="travis-ci-at-nodejitsu/irc-notifications.png" alt="IRC notifications">

</p>
<p><br>

</p>
<p>I can definitely agree with Marak here. Point of this notifications is not only to tell you that you failed. We want people to know that their changes were good!

</p>
<p><br>

</p>
<h1>Versions!</h1>
<p>We care about innovating. We care about our code being compatible with newer versions of software (<code>node</code>, <code>npm</code> and so on), but we have to care about people using older versions.

</p>
<p>How can Travis help? Travis lets you to set up multiple test environments which target different runtime version. It's really easy to run your tests in <code>node v0.6</code> and <code>node v0.4</code> at the same time with just 3 lines in your <a href="http://about.travis-ci.org/docs/user/build-configuration/"><code>.travis.yml</code> file</a> (detailed instructions for node.js are available <a href="http://about.travis-ci.org/docs/user/languages/javascript-with-nodejs/">here</a>).

</p>
<p><div class="snippet"><pre><code>language: node_js
node_js:
  - 0.4
  - 0.6

</code></pre></div>

</p>
<p>Build you get looks like <a href="http://travis-ci.org/#!/flatiron/broadway/builds/351271">that</a>.

</p>
<p><br>

</p>
<h1>Travis is easy!</h1>
<p>Travis is a hosted service - you don't need a sysadmin to setup a Jenkins server for you. All you need is <code>.travis.yml</code> file and enabled GitHub post-receive hook (which Travis can do for you!).

</p>
<p>Besides Node.js, travis-ci.org offers first class support for several other technologies:

</p>
<ul>
<li>Clojure</li>
<li>Erlang</li>
<li>PHP</li>
<li>Ruby</li>
</ul>
<p>with more languages coming in the future. It only takes a couple of minutes to <a href="http://about.travis-ci.org/docs/user/getting-started/">add your project to travis-ci.org</a>, give it a try and if you find it useful, consider <a href="https://love.travis-ci.org">supporting the project</a>.

</p>
<p><br>

</p>
<h1>Summary</h1>
<p>We're having a great time with Travis. It helped us find a few regressions, bugs and compatibility issues. If you're starting or if you have an open source project, you should add it to Travis. Show people that you care about your test results!
</p>
]]></description><link>http://blog.nodejitsu.com/travis-ci-at-nodejitsu</link><guid isPermaLink="true">http://blog.nodejitsu.com/travis-ci-at-nodejitsu</guid><dc:creator><![CDATA[Maciej Malecki]]></dc:creator><pubDate>Sat, 03 Dec 2011 11:20:56 GMT</pubDate></item><item><title><![CDATA[<a href="./npm-cheatsheet">npm cheatsheet</a>]]></title><description><![CDATA[<p><a href="http://npmjs.org">npm</a> is the node package manager. 

</p>
<p>It helps you manage your <a href="http://nodejs.org">node.js</a> modules and dependencies.

</p>
<p>Here is a quick cheatsheet of all my favorite <code>npm</code> commands:

</p>
<p><br>

</p>
<ul>
<li><a href="./npm-cheatsheet#Installing_npm">Installing npm</a></li>
<li><a href="./npm-cheatsheet#Update_npm">Update npm</a></li>
<li><a href="./npm-cheatsheet#Search_for_npm_packages">Search for npm packages</a></li>
<li><a href="./npm-cheatsheet#View_details_of_a_npm_package">View details of a npm package</a></li>
<li><a href="./npm-cheatsheet#Installing_a_npm_package_locally">Installing a npm package locally</a></li>
<li><a href="./npm-cheatsheet#Installing_a_npm_package_into_an_application">Installing a npm package into an application</a></li>
<li><a href="./npm-cheatsheet#Understanding_Global_versus_Local_installs_in_npm">Understanding Global versus Local installs in npm</a></li>
<li><a href="./npm-cheatsheet#Global_Package_Installation">Global Package Installation</a></li>
<li><a href="./npm-cheatsheet#Uninstalling_a_package_locally">Uninstalling a package locally</a></li>
<li><a href="./npm-cheatsheet#Uninstalling_a_package_globally">Uninstalling a package globally</a></li>
<li><a href="./npm-cheatsheet#Installing_a_specific_version_of_a_package">Installing a specific version of a package</a></li>
<li><a href="./npm-cheatsheet#Cloning_a_module_from_Github">Cloning a module from Github</a></li>
<li><a href="./npm-cheatsheet#Linking_any_npm_package_locally">Linking any npm package locally</a></li>
<li><a href="./npm-cheatsheet#Linking_local_npm_packages_to_multiple_applications">Linking local npm packages to multiple applications</a></li>
<li><a href="./npm-cheatsheet#Unlinking_a_npm_package_from_an_application">Unlinking a npm package from an application</a></li>
<li><a href="./npm-cheatsheet#Unlinking_a_npm_package_from_your_system">Unlinking a npm package from your system</a></li>
<li><a href="./npm-cheatsheet#Create_a_new_npm_package">Create a new npm package</a></li>
<li><a href="./npm-cheatsheet#Creating_a_new_user_account_on_npm">Creating a new user account on npm</a></li>
<li><a href="./npm-cheatsheet#Publishing_a_npm_package">Publishing a npm package</a></li>
<li><a href="./npm-cheatsheet#Unpublishing_a_npm_package">Unpublishing a npm package</a></li>
<li><a href="./npm-cheatsheet#Managing_owners_of_packages">Managing owners of packages</a></li>
</ul>
<p><br> 

</p>
<h2> </h2>
<p><a name="Installing_npm"></a>
</p>
<h1>Installing npm</h1>
<pre><code> curl http:<span class="comment">//n</span>pmjs.org/install.sh | sh</code></pre>
<p><a name="Update_npm"></a>
</p>
<h1>Update npm</h1>
<p>There are several ways you can update <code>npm</code>. I prefer either:

</p>
<pre><code> curl http:<span class="comment">//n</span>pmjs.org/install.sh | sh</code></pre>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>or</strong>

</p>
<pre><code> npm install npm -g</code></pre>
<p><br>

</p>
<p><a name="Search_for_npm_packages"></a>
</p>
<h1>Search for npm packages</h1>
<pre><code> npm search hook.io</code></pre>
<p><strong>Protip:</strong> <em>Try using <a href="http://search.npmjs.org"><a href="http://search.npmjs.org">http://search.npmjs.org</a></a></em>

</p>
<p><strong>Double Protip:</strong> <em>Know the name of the package you want before you start</em>

</p>
<p><br>

</p>
<p><a name="View_details_of_a_npm_package"></a>
</p>
<h1>View details of a npm package</h1>
<pre><code> npm view hook.io</code></pre>
<p><a name="Installing_a_npm_package_locally"></a>
</p>
<h1>Installing a npm package locally</h1>
<p>For the purpose of this demo, we will use <code>http-server</code>. 

</p>
<p><code>http-server</code> is a package we've written which provides an easy to use wrapper around node's core http.Server class. This module makes for a good example, since it's API provides both a CLI binary and a requirable node.js module.


</p>
<pre><code> npm install http-server</code></pre>
<p>This performs a <strong>local</strong> install of <code>http-server</code> in our <strong>current working directory</strong> 

</p>
<p>You may also notice a new <strong><code>node_modules/</code></strong> folder. You can ignore this for now.

</p>
<p><br>

</p>
<p><a name="Installing_a_npm_package_into_an_application"></a>
</p>
<h1>Installing a npm package into an application</h1>
<pre><code>  <span class="identifier">mkdir</span> <span class="identifier">mynewapp</span>/
  <span class="identifier">cd</span> <span class="identifier">mynewapp</span>
  <span class="identifier">npm</span> <span class="identifier">install</span> <span class="identifier">http</span>-<span class="identifier">server</span>
  <span class="identifier">touch</span> <span class="identifier"><span class="keymethods">test</span></span>.<span class="identifier">js</span></code></pre>
<npm-cheatsheet>

<p><strong>run script</strong>

</p>
<pre><code> <span class="identifier">node</span> <span class="identifier"><span class="keymethods">test</span></span>.<span class="identifier">js</span></code></pre>
<p><strong>Notice how we: <code><span class="identifier"><span class="keyword">require</span></span>(<span class="string">'http-server'</span>)</code>? What kind of wizardry is this?</strong>

</p>
<p><code>http-server</code> is not the name of a native node.js module. It's the name of the package we just installed from <code>npm</code>. <code>node</code> and <code>npm</code> are smart enough to automatically load modules from our local <code>node_modules/</code> folder.

</p>
<p><br>

</p>
<p><a name="Understanding_Global_versus_Local_installs_in_npm"></a>
</p>
<h1>Understanding Global versus Local installs in npm</h1>
<p>By default, <code>npm</code> will install all packages into the <strong>local</strong> directory you are working in. This is a <strong>good</strong> thing. It can however, be slightly confusing if you have worked with inferior package management systems in the past.

</p>
<p><strong>For example, if we:</strong>

</p>
<pre><code> <span class="identifier">mkdir</span> <span class="identifier">anotherapp</span>/
 <span class="identifier">cd</span> <span class="identifier">anotherapp</span>/
 <span class="identifier">touch</span> <span class="identifier"><span class="keymethods">test</span></span>.<span class="identifier">js</span></code></pre>
<p><strong>test.js</strong>

</p>
<pre><code> <span class="keyword">var</span> HTTPServer = require(<span class="string">'http-server'</span>);</code></pre>
<p><strong>and then run the script...</strong>

</p>
<pre><code> <span class="identifier">node</span> <span class="identifier"><span class="keymethods">test</span></span>.<span class="identifier">js</span></code></pre>
<p><strong>we'll get this error:</strong>


</p>
<pre><code><span class="identifier">node</span>.<span class="identifier">js</span><span class="symbol">:</span><span class="number">134</span>
        <span class="identifier"><span class="keymethods">throw</span></span> <span class="identifier">e</span>; <span class="regexp">//</span> <span class="identifier">process</span>.<span class="constant">nextTick</span> <span class="identifier">error</span>, <span class="identifier"><span class="keyword">or</span></span> <span class="string">'error'</span> <span class="identifier">event</span> <span class="identifier">on</span> <span class="identifier"><span class="keymethods">first</span></span> <span class="identifier">tick</span>
        ^
<span class="constant">Error</span><span class="symbol">:</span> <span class="constant">Cannot</span> <span class="identifier"><span class="keymethods">find</span></span> <span class="class"><span class="keyword">module</span> '<span class="title">http</span>-<span class="title">server</span>'</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Function</span>.<span class="constant">_resolveFilename</span> (<span class="class"><span class="keyword">module</span>.<span class="title">js</span>:326:11)</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Function</span>.<span class="identifier">_load</span> (<span class="class"><span class="keyword">module</span>.<span class="title">js</span>:271:25)</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="identifier"><span class="keyword">require</span></span> (<span class="class"><span class="keyword">module</span>.<span class="title">js</span>:355:19)</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Object</span>.&amp;<span class="identifier">lt</span>;<span class="identifier">anonymous</span>&gt; (<span class="regexp">/Users/maraksquires</span><span class="regexp">/dev/nodeapps</span><span class="regexp">/anotherapp/test</span>.<span class="identifier">js</span><span class="symbol">:</span><span class="number">1</span><span class="symbol">:</span><span class="number">80</span>)
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Module</span>.<span class="identifier">_compile</span> (<span class="class"><span class="keyword">module</span>.<span class="title">js</span>:411:26)</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Object</span>..<span class="identifier">js</span> (<span class="class"><span class="keyword">module</span>.<span class="title">js</span>:417:10)</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Module</span>.<span class="identifier"><span class="keymethods">load</span></span> (<span class="class"><span class="keyword">module</span>.<span class="title">js</span>:343:31)</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Function</span>.<span class="identifier">_load</span> (<span class="class"><span class="keyword">module</span>.<span class="title">js</span>:302:12)</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Array</span>.&amp;<span class="identifier">lt</span>;<span class="identifier">anonymous</span>&gt; (<span class="class"><span class="keyword">module</span>.<span class="title">js</span>:430:10)</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">EventEmitter</span>.<span class="constant">_tickCallback</span> (<span class="identifier">node</span>.<span class="identifier">js</span><span class="symbol">:</span><span class="number">126</span><span class="symbol">:</span><span class="number">26</span>)</code></pre>
<p>This is logical, we installed <code>http-server</code> <strong>locally</strong> into <code>"/mynewapp/"</code>, <strong>not</strong> in <code>"/anotherapp/"</code>. 

</p>
<p><strong>There are two direct solutions to fix this:</strong>

</p>
<p> a) Install the package again, but locally into our new application

</p>
<pre><code> cd anotherapp/
 npm install http-server</code></pre>
<p> b) Install the package globally

</p>
<pre><code> npm install http-server -g</code></pre>
<p><br>

</p>
<p><a name="Global_Package_Installation"></a>
</p>
<h1>Global Package Installation</h1>
<p>If you want to have a package available globally use:

</p>
<pre><code> npm install http-server -g</code></pre>
<p>The <code>-g</code> flag will indicate that <code>http-server</code> should be installed <strong>globally</strong>, and be available for all node scripts to require.

</p>
<p>Now, we can <strong><code><span class="identifier"><span class="keyword">require</span></span>(<span class="string">'http-server'</span>)</code></strong> in any node script on our system.

</p>
<p>In addition, since the <code>http-server</code> package has specified a <code>bin</code> property, it will also install a binary script called <code>http-server</code> globally. 

</p>
<p><em>Now you can simply run the command:</em>

</p>
<pre><code> http-server</code></pre>
<p><br>

</p>
<p><a name="Uninstalling_a_package_locally"></a>
</p>
<h1>Uninstalling a package locally</h1>
<pre><code>cd mynewapp/
npm uninstall http-server</code></pre>
<p><a name="Uninstalling_a_package_globally"></a>
</p>
<h1>Uninstalling a package globally</h1>
<pre><code>npm uninstall http-server -g</code></pre>
<p><a name="Installing_a_specific_version_of_a_package"></a>
</p>
<h1>Installing a specific version of a package</h1>
<pre><code>cd mynewapp/
npm install http-server@0.3.0</code></pre>
<p><a name="Cloning_a_module_from_Github"></a>
</p>
<h1>Cloning a module from Github</h1>
<p>This is important. In some cases, there will be patches, forks, or branches that we will want to use for our module, but have not yet been published to <code>npm</code>. Thankfully, the source code for most <code>npm</code> modules is also available on <a href="http://github.com">Github.com</a>

</p>
<pre><code>git clone git:<span class="comment">//g</span>ithub.com/nodeapps/http-server.git
cd http-server/
npm link</code></pre>
<p><em>Our cloned version of <code>http-server</code> is now linked locally</em>

</p>
<p><br> 

</p>
<p><a name="Linking_any_npm_package_locally"></a>
</p>
<h1>Linking any npm package locally</h1>
<p>If you have a local directory containing an <code>npm</code> package, you can link this package locally. This is good for development purposes and for situations when we do not want to publish our package to the public <code>npm</code> repository.

</p>
<pre><code>cd http-server/
npm link</code></pre>
<p><em>Our local version of <code>http-server</code> is "linked" on our local machine</em>

</p>
<p><br>

</p>
<p><a name="Linking_local_npm_packages_to_multiple_applications"></a>
</p>
<h1>Linking local npm packages to multiple applications</h1>
<p>As we've seen before, <code>npm</code> will install packages into the local directory by default. <code>npm link</code> works pretty much the same way.

</p>
<pre><code>mkdir newapp/
cd newapp/
npm link http-server</code></pre>
<p><em>This indicates that we've now linked <code>http-server</code> into our new application <code>newapp</code>. If we had not run <code>npm link http-server</code> we would have gotten a missing module error</em>

</p>
<p><br>

</p>
<p><a name="Unlinking_a_npm_package_from_an_application"></a>
</p>
<h1>Unlinking a npm package from an application</h1>
<pre><code>cd newapp/
npm unlink http-server</code></pre>
<p><a name="Unlinking_a_npm_package_from_your_system"></a>
</p>
<h1>Unlinking a npm package from your system</h1>
<pre><code>cd http-server/
npm unlink</code></pre>
<p><a name="Create_a_new_npm_package"></a>
</p>
<h1>Create a new npm package</h1>
<pre><code>mkdir mypackage/
cd mypackage/
npm init</code></pre>
<p><a name="Creating_a_new_user_account_on_npm"></a>
</p>
<h1>Creating a new user account on npm</h1>
<pre><code>npm adduser</code></pre>
<p><a name="Publishing_a_npm_package"></a>
</p>
<h1>Publishing a npm package</h1>
<pre><code>cd mypackage/
npm publish</code></pre>
<p><a name="Unpublishing_a_npm_package"></a>
</p>
<h1>Unpublishing a npm package</h1>
<pre><code>npm unpublish http-server</code></pre>
<p><a name="Managing_owners_of_packages"></a>
</p>
<h1>Managing owners of packages</h1>
<p>If you want multiple users to be able to publish to the same package:

</p>
<pre><code>npm owner add marak http-server
npm owner rm marak http-server
npm owner ls http-server</code></pre>
<p>For additional information on the <code>package.json</code> format and <code>npm</code> best practices, check out Charlie Robbin's article: <a href="http://blog.nodejitsu.com/package-dependencies-done-right"><a href="http://blog.nodejitsu.com/package-dependencies-done-right">http://blog.nodejitsu.com/package-dependencies-done-right</a></a>
</p>
</npm-cheatsheet>]]></description><link>http://blog.nodejitsu.com/npm-cheatsheet</link><guid isPermaLink="true">http://blog.nodejitsu.com/npm-cheatsheet</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Thu, 24 Nov 2011 08:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./how-to-write-a-readme">How To Write A Readme</a>]]></title><description><![CDATA[<p><em>This post was originally written for my personal blog, <a href="http://jesusabdullah.github.com">http://jesusabdullah.github.com</a>, while writing documentation for the <a href="https://github.com/flatiron">Flatiron</a> framework. Flatiron's documentation is not 100% up-to-snuff yet, but we're <a href="https://gist.github.com/1363524">following standards and guidelines</a> very similar to these as we fill in the gaps.</em>

</p>
<hr>

<p>So you're writing a module. Cool! Are you ready to document it? I'm here to help.

</p>
<p>I'm no expert on readmes. I have, however, read a <em>lot</em> of readmes (both good and bad), written my fair share of readmes and documentation, and---most importantly---have formed strong opinions on what I should see in a readme.

</p>
<p>This post focuses on the "first pass" for your readme. These PROTIPS are applicable, however, to readmes of <em>all</em> ages.

</p>
<p><br>

</p>
<h2> </h2>
<h1>1. Write an Example, Right Now</h1>
<p>The very first thing that should be written in a readme is a short example code snippet. This snippet should show what your library does, and as little else as possible. In the ideal case, people should <em>be able to infer from your example how your library works</em>.

</p>
<p>For example, here's a stubbed-out readme for a small utility by <a href="https://github.com/substack/node-mkdirp">SubStack</a>:

</p>
<blockquote>
<h1>mkdirp</h1>
<p>Like <code>mkdir -p</code>, but in node.js!

</p>
<h1>Example</h1>
<h2>pow.js</h2>
<pre><code><span class="keyword">var</span> mkdirp = require(<span class="string">'mkdirp'</span>);

mkdirp(<span class="string">'/tmp/foo/bar/baz'</span>, <span class="number">0755</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) console.error(err)
    <span class="keyword">else</span> console.log(<span class="string">'pow!'</span>)
});</code></pre>
<p>Output
    pow!

</p>
<p>And now /tmp/foo/bar/baz exists, huzzah!

</p>
</blockquote>
<p>This probably isn't the greatest readme of all time. However, the example is a perfect case study. In <strong>four lines</strong>, a programmer more or less fluent in javascript can tell that <code>mkdirp</code>:

</p>
<ul>
<li>Is a function.</li>
<li>Takes 3 arguments: A <em>file path</em>, some <em>octal permissions</em> and <em>an errorback</em>.</li>
<li>Probably makes directories.</li>
</ul>
<p>Add in the mention of "like mkdir -p" and, without any other documentation, we can tell how it works.

</p>
<p>Of course, mkdir -p is small enough that you can actually cover 100% of the API in one example. Not all projects are so lucky, but they can still strive to get a common use case across.

</p>
<p>Here's another good example of an example, from <a href="https://github.com/isaacs/node-tap">node-tap</a>. The example in this code saves what would otherwise be a terrible readme, to the point where node-tap has a solid contingent of loyal users <em>despite</em> its readme.

</p>
<h2>Why?</h2>
<p>You want to get people to use your project, right? Supposing this is your goal, you have to understand that <strong>your readme is your library's best chance of "selling" your library</strong>, and you <strong>don't have that much time</strong>.

</p>
<p>When a developer starts looking at libraries that might solve his or her problem, they're thinking two things:

</p>
<ol>
<li>Does this project solve my problem?</li>
<li>If so, how?</li>
</ol>
<p>Chances are they're looking at your project's competition as well, and they're not very patient. You need to get the gist of this information across early enough that your audience pauses to read the rest of your readme.

</p>
<p>A <em>good</em> example will tell a developer right away if the module does what they need, and <em>any</em> example will give the developer a taste of your API.

</p>
<p>You also get the added benefit of having to write a simple case of your API, giving you the opportunity to "sanity check" your API. Does anything look bulky in your example? Could the API be made more obvious? Now you know.

</p>
<p><br>

</p>
<h1>2. Describe the install procedure.</h1>
<p>A project that I think does a really good job of this is <a href="https://github.com/hookio/hook.io">hook.io</a>:

</p>
<blockquote>
<h1>Getting Start / Demo</h1>
<pre><code> npm install hook.io-helloworld -g</code></pre>
<p>Now run:

</p>
<pre><code> hookio-helloworld</code></pre>
<p>Spawn up as many as you want. The first one becomes a server, the rest will become clients. Each helloworld hook emits a hello on an interval. Now watch the i/o party go!

</p>
</blockquote>
<p><strong>Two. Lines.</strong> You now know how to get up and going with hook.io!

</p>
<p>Node.js projects like hook.io are lucky in this regard, as npm makes most installations for node projects a one-liner. This is ideal, as ease of installation is another selling point for your project.

</p>
<p>If you're not lucky enough to have an easy installation procedure, then this section becomes even more important. In the case of hook.io, I may have been able to put 2 and 2 together and went looking for it on npm. For a more complicated yet poorly-documented install procedure, developers <em>will</em> screw it up, at which point they will either complain to you or give up and move on.

</p>
<h2>Why?</h2>
<p>Assuming your example made a sale, the second question a developer is going to ask is, "How do I install this thing?" Make it easy for them.

</p>
<p><br>

</p>
<h1>3. Stub out the API docs.</h1>
<p>Now that you have a basic example and installation instructions, you can move on to documenting the basic API.

</p>
<p>When I write API docs (and this is admittedly a weak point for me), I like to start with obvious entry points (your module only has one obvious entry point, right?) and work from there.

</p>
<p>For example, here's a snippet from some API docs I wrote for <a href="https://github.com/flatiron/union">union</a>:

</p>
<blockquote>
<h3>union.createServer(options)</h3>
<p>The <code>options</code> object is required. Options include:

</p>
<h4>options.before</h4>
<p><code>options.before</code> is an array of middlewares, which are used to route and serve incoming requests. For instance, in the example, <code>favicon</code> is a middleware which handles requests for <code>/favicon.ico</code>.

</p>
<p>Union's request handling is <a href="https://github.com/senchalabs/connect">connect</a>-compatible, meaning that all existing connect middlewares should work out-of-the-box with union.

</p>
<p>In addition, the response object passed to middlewares listens for a "next" event, which is equivalent to calling <code><span class="identifier"><span class="keyword">next</span></span>()</code>. Flatiron middlewares are written in this manner, meaning they are not reverse-compatible with connect.

</p>
<h4>options.after</h4>
<p><code>options.after</code> is an array of stream filters, which are applied after the request handlers in <code>options.before</code>. Stream filters inherit from <code>union.ResponseStream</code>, which implements the Node.js core streams api with a bunch of other goodies.

</p>
<p>The advantage to streaming middlewares is that they do not require buffering the entire stream in order to execute their function.

</p>
<h4>options.limit (<em>optional</em>)</h4>
<p>This argument is passed to internal instantiations of <code>union.BufferedStream</code>.


</p>
</blockquote>
<p>In union, the obvious entry point is <code>union.createServer</code>. In this example, I tried to explain what you do with it, and what all the pieces mean.

</p>
<h2>Why?</h2>
<p>Hopefully the idea of <em>documenting your code</em> isn't completely foreign. That said, you may be tempted to think that an example is "enough". I would suggest that this is true only in very rare cases. Even <code>mkdirp</code> could use a short paragraph explaining the arguments and behavior of the module. Inferrence is great, but shouldn't be completely relied upon. Be straightforward.

</p>
<p><br>

</p>
<h1>4. Tests</h1>
<p>Your module may or may not have tests. If it <em>does</em> have tests (and tests are a wonderful idea!), you should describe how to run them. For example, here's a snippet that's very familiar to us at Nodejitsu:

</p>
<blockquote>
<h2>Run Tests</h2>
<p>Tests are written in vows and give complete coverage of all APIs and storage engines.

</p>
<pre><code class="bash">  $ npm test</code></pre>
</blockquote>
<p>This is pretty much ideal.

</p>
<h2>Why?</h2>
<p>Like installation instructions, testing directions should be as straightforward as possible. If you're using node and npm, npm test is great because it distills testing into a one-liner.

</p>
<p>(Choosing the <em>right</em> testing framework is another discussion entirely. I personally like node-tap).

</p>
<p><br>

</p>
<h1>5. Licensing and Contributors</h1>
<p>Finally, tag on your license and contributors.

</p>
<p>The content of this <em>isn't actually too important</em> in the context of a readme. For example, I usually just write the following:

</p>
<blockquote>
<h2>License:</h2>
<p>MIT/X11.

</p>
</blockquote>
<h2>Why?</h2>
<p>It's a good idea to tell other people how they can/may work on your code of course, but it's a secondary consideration. First, your commit logs will show who worked on the project, and arguably way better than your readme can. Second, the license is only important for people that want to hack on your code, and even then most people are willing to accept "It's MIT" when it comes to sending a pull request.

</p>
<p>Licensing may become more important in the future, but in the short term you can afford to wait and scale it later.

</p>
<p><br>

</p>
<h1>6. But I had other stuff to say!</h1>
<p>Write a blog post about it.

</p>
<p>No, seriously.

</p>
<h2>Why?</h2>
<p>A readme isn't always the best place to talk about your project. A readme's scope should really be pretty limited to:

</p>
<ul>
<li>What is it?</li>
<li>How do I use it?</li>
</ul>
<p>Anything else---like, "Why I Wrote This Module" or "Addressing Criticisms Of My Module"---don't really fit. But, blog posts are a <strong>great</strong> way of getting this information out.

</p>
<p>A good example of how a blog post can enhance a readme can be found on Nodejitsu's blog:

</p>
<blockquote>
<p><a href="http://blog.nodejitsu.com/scaling-isomorphic-javascript-code">Scaling Isomorphic Javascript Code</a>

</p>
</blockquote>
<p>In this blog post, Charlie Robbins discusses the motivations behind writing <a href="https://github.com/flatiron/flatiron">Flatiron</a>, Nodejitsu's collective idea of what a web framework should look like.

</p>
<p>For those interested in design patterns, it's a very good read. In this post, Charlie distills the meaning of MVC, how different existing frameworks implement it, and why (in his opinion) existing tools aren't enough. If that lights your fire, then I highly recommend this article.

</p>
<p>That said, for the user that just wants to write a webapp and doesn't really care about which kind of MVC-ish paradigm they're using, such explanations in a readme will <strong>only get in the way.</strong>

</p>
<p><br>

</p>
<h1>TL;DR</h1>
<p>If nothing else, <strong>write an example.</strong>
</p>
]]></description><link>http://blog.nodejitsu.com/how-to-write-a-readme</link><guid isPermaLink="true">http://blog.nodejitsu.com/how-to-write-a-readme</guid><dc:creator><![CDATA[Josh Holbrook]]></dc:creator><pubDate>Fri, 18 Nov 2011 01:24:09 GMT</pubDate></item><item><title><![CDATA[<a href="./understanding-open-source-branding">Understanding Open Source Branding</a>]]></title><description><![CDATA[<p>What is product? At Nodejitsu our definition is simple: <strong>product is what our users are consuming every day.</strong> It doesn't matter if it is our Platform-as-a-Service, <a href="http://www.nodejitsu.com">nodejitsu.com</a>, or if it is <a href="https://github.com/flatiron">one of</a> <a href="https://github.com/nodejitsu">our many</a> <a href="https://github.com/nodeapps">open source</a> <a href="https://github.com/hookio">libraries.</a> This definition is why from very early on at Nodejitsu we decided <strong>to treat our open source libraries with the same level of attention and care that we do our public Platform-as-a-Service.</strong>

</p>
<p>Successful open source libraries and initiatives require the same kind of attention to branding that many think is reserved for profit focused products. In other words, <strong><a href="http://zachholman.com/posts/open-source-marketing/">Open Source Doesn't Just Market Itself</a>.</strong> Lets explore how discoverability, time to start (i.e. how long it takes to use what you've built), community, and <a href="http://jsconf.nodejitsu.com">some good old fashioned hustling</a> can help build Open Source brands.
<br><br>

</p>
<h2> </h2>
<h1>Overview</h1>
<p>tl;dr? This is the place for you:

</p>
<ul>
<li><a href="#dont-make-me-think">"Don't Make Me Think"</a>: Understand your users' motivations.</li>
<li><a href="#divorce-your-ego">Divorce your Ego</a>: Understand your motivations.</li>
<li><a href="#build-a-community">Build a Community</a>: Setting and managing user expectations.</li>
<li><a href="#open-source-at-nodejitsu">Open Source at Nodejitsu</a>: A quick overview of Nodejitsu's Open Source projects and initiatives. </li>
<li><a href="#conclusion">Conclusion</a>: Wrap it up.</li>
</ul>
<p><br><br>
<a name="dont-make-me-think"></a>
</p>
<h1>"Don't Make Me Think"</h1>
<p>A clear concise explanation of your Open Source offering is the best way to get users interested in what you're developing. Zach Holman from Github put it eloquently in his article <a href="http://zachholman.com/posts/open-source-marketing/"><em>Open Source Doesn't Just Market Itsef</em></a>:

</p>
<blockquote>
My favorite marketing of all time is documentation. We all loathe sleazy marketing, and by definition I like to think documentation can't be sleazy because it solves a real purpose: teaching everyone about the project.
</blockquote>

<p>Take a step back and think about discoverability and time to start from a user's point of view: they somehow stumbled upon your project. They probably don't know you or how awesome you are. <strong><em>They are looking for a solution to a problem that your project may or may not solve. The quicker you help them make this decision the better.</em></strong> 

</p>
<p>Documentation comes in all flavors, each of which serves a different purpose. Every type of documentation increases the momentum and reduces the perceived risk of your project so the more the better. Just like a startup, building momentum is a key metric to success: <a href="http://www.hulu.com/watch/12939/field-of-dreams-if-you-build-it-he-will-come"><em>"Build enough momentum and they will come."</em></a>
<br><br>

</p>
<ul>
<li><strong>README:</strong> This is Open Source MVP. Without a README (preferrably Markdown on Github), at least half the users that discover your project will simply move on. If you have a lot of Open Source projects <strong>be consistent.</strong> <a href="https://gist.github.com/1363524">Use an outline; we do at Nodejitsu.</a></li>
<li><strong>Examples:</strong> If your library has several use cases, then it is absolutely critical to <a href="https://github.com/nodejitsu/node-http-proxy/tree/master/examples"><em>include example code and briefly discuss it in your README.</em></a></li>
<li><strong>Project Website:</strong> <em>Even better.</em> A custom project website allows you to create a true brand for your project; a logo, a catchy tag-line, whatever. <a href="https://github.com/blog/273-github-ribbons"><em>Be sure to link back to Github or elsewhere.</em></a></li>
<li><strong>Blog Posts and Tutorials:</strong> This is the long tail of Open Source branding. Each blog post or descriptive tutorial you write will gather more momentum and lower the perceived risk of your Open Source offering.</li>
</ul>
<p><br>
Beyond documentation remember that <em>this is Open Source: people will read your code.</em> If you haven't finished part of your API or there is work left to be done be clear about it and expect feedback. Or, if you've decided on a particular way to write your code (such as promises or a particular coding style), realize many users will be immediately dismissive. This is <a href="http://blog.izs.me/post/12604303054/experts-idiots-and-taste">particularly important in Javascript</a>:

</p>
<blockquote>If your code uses a compiled fibers library, or something that transforms the code, then it's much harder for me to figure out what the heck is going on. The introspection is gone.</blockquote>

<p><br><br>
<a name="divorce-your-ego"></a>
</p>
<h1>Divorce Your Ego</h1>
<p>To me, the emotional investment in creating Open Source is best summed up by <a href="http://groups.google.com/group/nodejs/msg/fbccef7121fa5322">Isaac Schlueter</a>:

</p>
<blockquote>It's like having children. Seems like a lot of pointless busy-work, and then you do it, probably without meaning or wanting to, and then suddenly fall so in love, you can't understand why everyone doesn't go as nuts over this little food-to-poop converter as you do. If you're not careful, you'll end up writing 3 or 4 more.</blockquote>

<p>Divorcing yourself from your ego and these emotions is hard. You have probably put in countless hours of your own time just because you thought it was cool. <strong>But it is crucial to Open Source success:</strong> your users probably don't want your life story about why you created your library, or how it is going to solve a problem they don't have. 

</p>
<p>They also don't want to get an attitude when they open up an issue or reach out to you over Twitter, Email, or your Mailing list. A user may not completely understand the problem you're solving or is just plain misusing your API. An open-minded and understanding attitude is your greatest ally. This doesn't mean you have to divorce yourself from your opinions, just stay objective and never make it personal. 

</p>
<p><br><br>
<a name="build-a-community"></a>
</p>
<h1>Build a Community</h1>
<p>Beyond having a simple and concise explanation of what your Open Source offering is it is important to create a place where questions and FAQs can be easily found and responded to. Think of this as <em>"beyond documentation."</em> 

</p>
<p>When working with these community building resources it is crucial to realize <strong>your first interaction with a user may be your last. And, if you provide a great experience for your Open Source users they will become your community's greatest asset:</strong> responding to Github issues, helping new users, writing Open Source which expands on your own, authoring a critical mass of blog posts, and more. At <a href="http://www.nodejitsu.com">Nodejitsu</a> most of our new hires come out of this group of users who respond to common GitHub issues and mailing list threads.

</p>
<p>So bury your ego and be as friendly as you can. That's not to say you have to do your users' work for them; just set and manage user expectations. We try to respond to every issue within 24 hours; <em>ideally within 5 minutes.</em>
<br><br>

</p>
<ul>
<li><strong>GitHub issues:</strong> You probably already use GitHub issues for your project. Are you checking them every day? Do you have a FAQ tag for commonly opened issues? </li>
<li><strong>Mailing list:</strong> Usually a Google group. This is a great place for feature discussions and commonly asked questions. Just look at the <a href="http://groups.google.com/group/nodejs">nodejs</a>, <a href="http://groups.google.com/group/express-js">expressjs</a>, or <a href="http://groups.google.com/group/hookio">hookio</a> mailing lists. </li>
<li><strong>Twitter:</strong> Like it or not, Twitter is a very common place for developers to ask questions. Be prepared for some extra noise in your @ mentions. If you prefer not to use Twitter, be understanding and explain that to users. Also: <em>retweets are one of your best marketing sources.</em></li>
<li><strong>Email:</strong> Personally I prefer not to answer questions about Open Source projects over email; I ask that a Github issue be opened. If you're feeling generous, however, it is a great way to build a rapport with one user.</li>
</ul>
<p>When working with these community resources there are some basic expectations which my co-founder, Marak Squires, outlined in his JSConf.eu talk: <a href="http://jsconf.eu/2011/how_to_be_an_open-source_gangs.html">How to be an Open Source Gangster</a>. The tagline may sound silly, but as the Chief Evangelist at Nodejitsu Marak speaks from experience:
<br><br>

</p>
<ul>
<li><strong>Be available:</strong> If it takes a user a week to get a response to a pull-request, issue, or email, they probably aren't even a user anymore.</li>
<li><strong>Persistence, Tenacity, Follow-through:</strong> Stay focused. Every day is a new challenge. Like most developers Open Source is probably your side-project. Be explicit with yourself about how much time you are going to commit. If you go over that limit then find a way to share the workload with a contributor. <em>Just giving up will undo any hard work you've put in.</em>  </li>
<li><strong>Ignoring Distractions:</strong> Don't get distracted by things that don't contribute to your core Open Source offering. <em>"Let the things that don't matter truly slide."</em></li>
<li><strong>Recruitment:</strong> Realize that you are not a one man army and engage your contributors vigorously. In the long run, they are the greatest asset to your community.</li>
</ul>
<p><br><br>
<a name="open-source-at-nodejitsu"></a>
</p>
<h1>Open Source at Nodejitsu</h1>
<p>Last week at Nodejitsu <a href="http://blog.nodejitsu.com/introducing-flatiron">we announced Flatiron</a>. In addition to the libraries that we announced we took this opportunity to reorganize our personal Github repositories into organizations. We realized that <strong>as our Open Source offering grew organizing repositories across multiple Github organizations was the simplest path to high discoverability.</strong> This decision is not for everyone, and probably not the correct decision for most individual developers. Just like starting a company, these qualities help your Github organization <strong><em>tell a cohesive story.</em></strong> A good Open Source Github organization does a few things:
<br><br>

</p>
<ul>
<li><strong>Cohesive motivation:</strong> What problem is your Github organization solving? You don't get a README on your organization page so this should be inferred from the repositories or the homepage URL. </li>
<li><strong>Critical mass of repositories:</strong> Enough repositories to convince a passive user that the organization is legitimate. This can be extremely difficult if your company is new to Open Source; you may be better off contributing to an existing organization. Releasing several projects at once is a good way to avoid having less than a critical mass.  </li>
<li><strong>Critical mass of members:</strong> Enough users to convince a passive user that the organization is legitimate. <a href="http://githits.me">Githits.me</a> is a great way to determine this; it ranks organizations by the sum of the Github followers of all users. This is not a perfect metric by any means, but it can help you determine this. </li>
</ul>
<p>At <a href="http://www.nodejitsu.com">Nodejitsu</a> we have decided to delineate our core Open Source offering into several organizations each of which we feel tells a different story:
<br><br>

</p>
<ul>
<li><strong><a href="https://github.com/nodejitsu">Nodejitsu</a>:</strong> Core Open Source libraries from our public Platform-as-a-Service, <a href="http://www.nodejitsu.com">Nodejitsu.com</a> including <a href="https://github.com/jitsu">jitsu</a>, <a href="https://github.com/haibu">haibu</a>, and <a href="https://github.com/forever">forever</a>.</li>
<li><strong><a href="https://github.com/flatiron">Flatiron</a>:</strong> Collection of decoupled Open Source libraries for building tools and web applications in Node.js.</li>
<li><strong><a href="https://github.com/hookio">Hook.io</a>:</strong> A full featured I/O framework for Node.js.</li>
<li><strong><a href="https://github.com/nodeapps">Node Apps</a>:</strong> A collection of sample applications designed to expedite time-to-start with Node.js on <a href="http://www.nodejitsu.com">Nodejitsu.com</a>.</li>
<li><strong><a href="https://github.com/nodetraining">Node Training</a>:</strong> Our training materials (when they're finished) along with tutorial-style projects which we use in our <a href="http://www.eventbrite.com/org/995072085">training sessions</a>.</li>
</ul>
<p><br><br>
</p>
<h1>Moving and Renaming Personal Repositories</h1>
<p>You've probably heard this saying about Computer Science before:

</p>
<blockquote>There are only two hard problems in Computer Science: cache invalidation and naming things.  -- Phil Karlton</blockquote>

<p>As the quantity of your Open Source libraries increases and they potentially move around to different organizations the first name you picked may no longer be appropriate. Such is the case for the routing component of <a href="http://flatironjs.org">Flatiron</a>, which today <strong>we are renaming from sugarskull to <a href="https://github.com/flatiron/director">director</a>.</strong> We felt that the name <a href="https://github.com/flatiron/director">director</a> was more in-line with the <a href="http://flatironjs.org">Flatiron</a> brand.

</p>
<p>If you do decide to move personal Open Source repositories to an organization Github will not perform an 301 redirects so the best process is below. It is not ideal by any means, but it is the best Github can do today. If you are concerned about SEO think about this this way: <em>you shouldn't be concerned with the 100 followers you have today; be concerned with the 1,000 followers you want in a year.</em>
<br><br>

</p>
<ol>
<li>Move the repository to your organization from your personal Github
<img src="understanding-open-source-branding/danger-zone.png"></li>
<li>Immediately fork the moved repository back to your personal Github and add a redirection notice.
<img src="understanding-open-source-branding/move-notice.png"></li>
</ol>
<p><br><br>
<a name="conclusion"></a>
</p>
<h1>Conclusion</h1>
<p>Hopefully not all of this is new to you; most of it is a distillation of the common wisdom that most developers follow today. A lot of this can be thought of as <a href="http://zachholman.com/posts/open-source-marketing/">Open Source in the age of Github.</a>

</p>
<blockquote>Prior to GitHub, word about open source projects travelled primarily through word-of-mouth and messenger bicyclists. The largest open source project had three users and two developers. I think it involved a lot of twine and glitter.</blockquote>

<ul>
<li><strong>Make your users first time as easy as possible:</strong> Minimize perceived risk to maximize momentum.</li>
<li><strong>Be an <a href="http://jsconf.eu/2011/how_to_be_an_open-source_gangs.html">Open Source Gangster</a>:</strong> Every day I'm Open Sourcin'. </li>
<li><strong>Engage your community and recruit actively:</strong> Github, Twitter, Mailing list(s); whatever works.</li>
<li><strong>Create a Github organization for large projects:</strong> Remember to tell a cohesive story.</li>
</ul>
<p><br><br><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/understanding-open-source-branding</link><guid isPermaLink="true">http://blog.nodejitsu.com/understanding-open-source-branding</guid><dc:creator><![CDATA[Paolo Fragomeni]]></dc:creator><pubDate>Mon, 14 Nov 2011 05:12:00 GMT</pubDate></item><item><title><![CDATA[<a href="./introducing-flatiron">Introducing Flatiron</a>]]></title><description><![CDATA[<p>Web development is all about choices. What language do you want to use? What database? What libraries? No matter how you develop web applications these choices have to be made. When using large frameworks in other languages such as Ruby or PHP most of these choices are made for you. In Node.js we have <a href="http://npmjs.org">npm</a>, which has allowed a diverse ecosystem of modules to develop. This has fostered a philosophy of <a href="http://blog.nodejitsu.com/the-nodejs-philosophy">creative experimentation</a>, but not made it any easier to make these choices.

</p>
<p>This is the motivation behind <a href="http://flatironjs.org">flatiron</a>. At it's core <a href="http://flatironjs.org">flatiron</a> is two things:
<br><br>

</p>
<p><strong>An initiative to build a collection of decoupled tools with the same standard of quality and performance that you would expect from anything built by <a href="http://nodejitsu.com">Nodejitsu</a>.</strong>
<br><br>

</p>
<p><strong>A full-stack web application development framework which packages these tools together to make <a href="http://blog.nodejitsu.com/scaling-isomorphic-javascript-code">isomorphic</a> and <a href="http://nodejs.org/docs/v0.6.0/api/streams.html">stream-based</a>  application development easier.</strong>
<br><br>

</p>
<p>This article will introduce you to the components that make-up flatiron as well as how <a href="https://github.com/flatiron/flatiron">the core flatiron project</a>.
<br><br>

</p>
<h2> </h2>
<h1>A Sum of its Parts</h1>
<p>At Nodejitsu, we have and continue to believe in a simple mantra: <strong>build the best tools and the best systems will follow.</strong> Tools and their distribution among members of an organization evolve organically overtime. To put it another way: <strong>if you use Node.js you are probably already using a component of flatiron.</strong> We have simply moved these tools to the <a href="https://github.com/flatiron/flatiron">Flatiron Github Organization</a>

</p>
<ul>
<li><a href="https://github.com/flatiron/api-easy">api-easy</a>: Fluent (i.e. chainable) syntax for generating vows tests against RESTful APIs.</li>
<li><a href="https://github.com/flatiron/complete">complete</a>: Custom command line tab completion for nodejs CLI apps.</li>
<li><a href="https://github.com/flatiron/nconf">nconf</a>: Hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.</li>
<li><a href="https://github.com/flatiron/neuron">neuron</a>: The simplest possible event driven job manager, FIFO queue, and 'task based cache' in node.js.</li>
<li><a href="https://github.com/flatiron/node-prompt">node-prompt</a>: A beautiful command-line prompt for node.js.</li>
<li><a href="https://github.com/flatiron/sugarskull">sugarskull</a>: A depth-first search based routing library for the browser and node.js.</li>
<li><a href="https://github.com/flatiron/winston">winston</a>: A multi-transport async logging library for Node.js.</li>
</ul>
<p>In addition to migrating existing libraries we have been working on a number of new libraries to round out these tools.

</p>
<ul>
<li><a href="https://github.com/flatiron/broadway">broadway</a>: Lightweight feature reflection and application composition for node.js and the browser.</li>
<li><a href="https://github.com/flatiron/flatiron">flatiron</a>: An unobtrusive full-stack web framework for node.js and the browser.</li>
<li><a href="https://github.com/flatiron/plates">plates</a>: Unobtrusive, thin and fast anti-templating</li>
<li><a href="https://github.com/flatiron/revalidator">revalidator</a>: A cross-browser / node.js validator used by resourceful and flatiron.</li>
<li><a href="https://github.com/flatiron/resourceful">resourceful</a>: A resource-oriented ODM with a high-level API for routing and validation.</li>
<li><a href="https://github.com/flatiron/union">union</a>: A hybrid buffered / streaming middleware kernel backwards compatible with connect.</li>
<li><a href="https://github.com/flatiron/utile">utile</a>: A drop-in replacement for <code>util</code> with some additional advantageous functions.</li>
</ul>
<p>A lot of effort has been made to ensure that each component stands on it's own and that each Github repository clearly explains the purpose, use case, and stability of the library. There are a few particularly interesting highlights among these libraries that we'll explore below.
<br><br>

</p>
<h1>A quick tour of Flatiron</h1>
<p><strong>Application composition</strong> 

</p>
<p>Thanks to Javascript you never have to worry about types again (mostly), but that doesn't mean that we can't learn something from design patterns more prevalent is statically typed languages. Namely: <a href="http://martinfowler.com/articles/injection.html">inversion of control and dependency injection</a>. Don't be scared! Promise you won't have to register anything, ever.

</p>
<p><a href="https://github.com/flatiron/broadway">Broadway</a> exposes a simple "plugin" API which allows the application developer to extend the top-level application object easily. This model translates well between the browser and the server because developers can write different plugins to suite the needs of the different environments. <a href="https://github.com/flatiron/broadway">Broadway</a> includes several plugins by default which can be overridden if you don't agree with the particular module or library choice we've made:

</p>
<p><img style="margin-left: 75px;" src="/introducing-flatiron/app-use.png">
<br><span style="margin-left: 170px;"><strong>Figure 1: app.use() in Broadway</strong></span>
<br><br>

</p>
<p>Doesn't remind you of dependency injection? It shouldn't! Because of the loosely typed nature of Javascript it isn't necessary to bring along all of the heavyweight type registration APIs that are so common in most dependency injection frameworks. Instead, plugins must be responsible and properly implement three methods

</p>
<ul>
<li>.attach(options): This synchronous method is called immediately on <code>app.use(somePlugin)</code>.</li>
<li>.init(done): This asynchronous method is called once when the application initializes and before it starts.</li>
<li>.detach(): This synchronous method is called on <code>app.unuse(somePlugin)</code>.</li>
</ul>
<p><img style="margin-left: 10px;" src="/introducing-flatiron/plugin-lifecycle.png">
<br><span style="margin-left: 170px;"><strong>Figure 2: Plugin Lifecycle in Broadway</strong></span>
<br><br>

</p>
<p>All of these functions are evaluated in the scope of the app (i.e. <code><span class="keyword">this</span></code> inside of a plugin is the app itself). Lets take a look at a quick sample from broadway itself:

</p>
<p><div class="snippet"><pre><code>exports.attach = <span class="function"><span class="keyword">function</span> <span class="params">(options)</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// Here setting `this.config` will expose the `.config` </span>
  <span class="comment">// property on the application itself</span>
  <span class="comment">//</span>
  options = options  || {};
  <span class="keyword">this</span>.config = <span class="keyword">new</span> nconf.Provider(options);
};

exports.init = <span class="function"><span class="keyword">function</span> <span class="params">(done)</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// Later on we can initialize the configuration </span>
  <span class="comment">// we attached earlier.</span>
  <span class="comment">//</span>
  <span class="keyword">this</span>.config.load(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">return</span> err ? done(err) : done();
  });
};</code></pre></div>

</p>
<p><em>Ok. So what?</em> Application extensibility allows us to reuse more components across different kinds of applications while writing less code. In almost every <a href="http://expressjs.org">express</a> application, you will see a server.js file which is essentially wiring up the same libraries to the same methods. If you write a couple of small applications it might not seem like a problem, but when building a product like Nodejitsu it simply isn't DRY enough.

</p>
<p><strong>Streaming or not streaming? No problem!</strong> 

</p>
<p>One of the current problems in node.js core is that there is no good way to buffer a stream when not closing the underlying file descriptor. Don't worry though; the geniuses behind node.js are on it and already have a solution on the drawing board. In the meantime though, something needs to fill the gap and that is <a href="https://github.com/flatiron/union">union</a> and <a href="https://github.com/flatiron/sugarskull">sugarskull</a>. 

</p>
<p>The problem is that 90% of the time you actually want to buffer a small amount of request data (&lt; 10k) into memory then parse it and attach it to the <a href="http://nodejs.org/docs/v0.6.0/api/http.html#http.ServerRequest">http.ServerRequest</a> object. Think: <em>a POST with some JSON attached to it.</em> Occasionally though, you may want to take advantage of a <a href="http://nodejs.org/docs/v0.6.0/api/streams.html">stream</a>. Think: <em>a large file upload to Amazon S3.</em> In this case, buffering is cancer and <code>.<span class="identifier"><span class="keymethods">pipe</span></span>()</code> is king.

</p>
<p>The solution is two-fold:

</p>
<ul>
<li>Pipe the concrete <a href="http://nodejs.org/docs/v0.6.0/api/http.html#http.ServerRequest">http.ServerRequest</a> to a <a href="https://github.com/flatiron/union/blob/master/lib/buffered-stream.js">BufferedStream</a> implementation by default.</li>
<li>Attach metadata to routes indicating if the route requires a stream or not. If a stream is not required, attempt to parse the entire body before continuing to the Router.</li>
</ul>
<introducing-flatiron>

<p>As the above sample illustrates, not much changes from the API you may already know with a couple of key differences:

</p>
<ul>
<li>The request, <code>req</code>, and response, <code>res</code>, are set on the <code><span class="keyword">this</span></code> argument of the route function.</li>
<li>Optional metadata can be passed to Router methods like <code>.get</code>. To enable the stream API just set <code>{ stream: <span class="literal">true</span> }</code>.</li>
</ul>
<p>You may be yelling <em>"what happened to function (req, res, next)!?!"</em> but that's too much to go into here. Rest assured there are good reasons. If you're thinking about 
<br><br>

</p>
<p><strong>Routing, templating and validation: anywhere, anytime</strong> 

</p>
<p>Flatiron comes with a highly performant router, a robust validation library, and a fast unobtrusive templating library <strong><em>which all work on the client and the server.</em></strong> Currently there is no packaged browser-build of all of these components together, but that will be coming soon through a collaboration with the <a href="http://jqueryui.com/">jQuery UI team</a>. 

</p>
<p>There are other components which are on the Roadmap for isomorphic (i.e. browser-server) compatibility: <a href="https://github.com/flatiron/broadway">broadway</a> and <a href="https://github.com/flatiron/resourceful">resourceful</a>. Here's a quick compatibility matrix of all the modules we've listed above:

</p>
<p><img style="margin-left: 75px;" src="/introducing-flatiron/flatiron-compatibility.png">
<br><span style="margin-left: 170px;"><strong>Figure 3: Flatiron Compatibility Matrix</strong></span>
<br><br>

</p>
<h1>A community effort</h1>
<p>We have not been operating in a vacuum at <a href="http://nodejitsu.com">Nodejitsu</a> on <a href="http://flatironjs.org">Flatiron</a>. We have taken feedback from the Node.js community for all of our existing libraries. Thanks to you <em>hundreds of issues have been found and closed.</em> For the components we are releasing today, many of them are a result of your feedback. Fast unobtrusive templating? Done. Streaming + non-streaming. Done. 

</p>
<p>In the coming weeks we will be announcing new libraries to fulfill <a href="#roadmap">our roadmap</a> with help from other companies who are as exciting about Node.js and isomorphic Javascript applications as we are.
<br><br>

</p>
<p><a name="roadmap"></a>
</p>
<h1>What's next?</h1>
<p>There are still pieces missing, but the Flatiron team will be working hard over the coming weeks and months to finish up our roadmap:

</p>
<ul>
<li>A browser-isomorphic (i.e. client-server) Presenter layer.</li>
<li>Make <a href="https://github.com/flatiron/union">resourceful</a> and <a href="https://github.com/flatiron/broadway">broadway</a> browser-isomorphic.</li>
<li>A pluggable View layer.</li>
<li>A full-stack browser solution.</li>
</ul>
<p><br>

</p>
<h1>Want more? Check back tomorrow.</h1>
<p><strong>This is just the beginning.</strong> 

</p>
<p><br><br><br><br>



</p>
</introducing-flatiron>]]></description><link>http://blog.nodejitsu.com/introducing-flatiron</link><guid isPermaLink="true">http://blog.nodejitsu.com/introducing-flatiron</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Wed, 09 Nov 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./node-for-normals">Node for Normals</a>]]></title><description><![CDATA[<p>You're smart. You know your way around your laptop and your iPhone. Maybe you spend more time in excel and powerpoint than on the command line. You're not an engineer but you've played with some HTML and CSS. Maybe not. Point is, you've been hearing about this Node.js thing and you want to know if it's for you. Maybe I can help.

</p>
<p>First, just a little about me... in July I joined Nodejitsu as COO. What's that mean? For the purposes of this discussion, not a whole lot. What's more important is that I'm an application developer and I'm new to Node. In this post, I'll discuss a lot of the things that attracted me to Node.

</p>
<h2> </h2>
<p><img src="/node-for-normals/confused_guy.jpg" style="float: right; margin: 15px; border: 1px solid #333;" alt="Confused Man: http://www.flickr.com/photos/safari_vacation/6257284524/"><br>
</p>
<h1>What is Node?</h1>
<p>Node (aka Node.js, NodeJS) is Javascript. It's the same thing that's been running in your browser for years. Now it's better, faster, and stronger. Oh, and now it's everywhere. Node is what allows you to bring Javascript, a language traditionally run in the browser, to the server. And why does Node matter? I'm glad you asked that.

</p>
<p><br>

</p>
<h1>Javascript isn't going anywhere</h1>
<p>There's no getting around having Javascript in your app. Javascript is <em>THE</em> language for making dynamic web interfaces bar none. If you're thinking, "Hey, but isn't that JQuery?" You're right. But JQuery is Javascript. Promise. And if you're thinking, "Come on, but what about Flash?" Well... what about it?

</p>
<p>Javascript is going to be in your application somewhere. Node allows you to standardize on that from the top to the bottom. Some applications have Javascript on the front-end on top of a Python web application that speaks to APIs served by something more performant like Scala or Erlang. That's a lot of different competencies to hire for and to maintain and when something breaks, not everyone is going to be conversant with everything. Deferring specialization is a huge benefit of Node.

</p>
<p><br>

</p>
<h1>Wow, is it fast!</h1>
<p><a href="http://www.ostinelli.net/a-comparison-between-misultin-mochiweb-cowboy-nodejs-and-tornadoweb/">Node is an order of magnitude faster than Ruby and Python.</a> This translates roughly to say that it's very easily the most responsive under load of any of the most popular high level languages (Javascript, Ruby, Python). Node and Javascript benefit from all the work that Google, Apple and Microsoft have poured into making their browsers more performant as well as more efficient to run on less resources (such as a netbook or iPad). Lucky us.

</p>
<p><br>

</p>
<h1>Realtime</h1>
<p>Node uses an asynchronous event-driven model. This means that it can make more efficient use of resources to do more things at one time and is an excellent fit for the architectures of many Internet applications. This model also makes these applications easier, and more intuitive for engineers to create.

</p>
<p><br>

</p>
<h1>Facilitation of engineer AND code versatility</h1>
<p>Javascript everywhere means that while there are still going to be developers that are more familiar with particular front or back end APIs or environments, it's a lot easier for the team to pitch in where help is needed. In a similar fashion, Javascript everywhere facilitates the reuse of code all through your stack which is a good thing as it cuts down on redundancy and helps maintainability of your application.

</p>
<p><br>

</p>
<h1>Yeah, we think it's pretty cool too</h1>
<p>This is of course, just a taste. Here are some other excellent resources to get you started.

</p>
<ul>
<li><a href="http://nodeguide.com/convincing_the_boss.html">Convincing the Boss</a></li>
<li><a href="http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef7-0f7ecbdd56cb">Understanding Node.js</a></li>
<li><a href="http://video.nextconf.eu/video/1914374/nodejs-digs-dirt-about">"Data-Intensive Real-Time" Applications</a></li>
</ul>
<p>Also, check us out on the <a href="http://twitter.com/nodejitsu">Twitter</a> (<a href="http://twitter.com/nodejitsu">@Nodejitsu</a>), read some of the other articles on our <a href="http://blog.nodejitsu.com">blog</a>, or maybe attend some of our future training sessions. We also write a tremendous amount of <a href="http://github.com/nodejitsu">open-source code</a> that you can utilize in your applications.



</p>
<p><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/node-for-normals</link><guid isPermaLink="true">http://blog.nodejitsu.com/node-for-normals</guid><dc:creator><![CDATA[Saadiq Rodgers-King]]></dc:creator><pubDate>Wed, 02 Nov 2011 08:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./scaling-isomorphic-javascript-code">Scaling Isomorphic Javascript Code</a>]]></title><description><![CDATA[<p>Take a minute and think about how often you've heard the phrase "Model-View-Controller" (or MVC). Do you really know what it means? At a high-level it is about a separation of concerns between the major areas of functionality in presentation-centric applications built on retained graphics systems (i.e not-raster graphics, such as games). Dig a little deeper and it becomes obvious that it is just a bucket term for a lot of different things. In the past, most development communities built-out an MVC solution that worked well for their most popular use-case and moved on. Great examples of this are the Ruby and Python communities with the MVC-based architecture Rails and Django both embody. 

</p>
<p>This approach has been acceptable for other languages such as Java, Ruby, and Python it is simply not good enough for Node.js for one reason: <strong>Javascript is now an isomorphic language.</strong> By <strong>isomorphic</strong> we mean that any given line of code (with notable exceptions) can execute both on the client and the server. On the surface this seemingly innocuous property creates a number of challenges that are not solved by current MVC-based patterns. This article will explore some of these existing patterns, how both their implementation and concerns vary across languages and environments, and how they are not good enough for a truly isomorphic Javascript codebase. In conclusion, we will explore a new pattern: <a href="/scaling-isomorphic-javascript-code#rvp">Resource-View-Presenter</a>.
<br><br>

</p>
<h2> </h2>
<h1>At a glance</h1>
<p>Design patterns are the bread and butter of application development. They encapsulate and outline the concerns of the application and the environment of the in which it exists. Between the browser and the server these concerns can vary widely:

</p>
<ul>
<li>Is the view ephemeral (e.g. on the server) or long-lived (e.g. in the browser)?</li>
<li>Is the view reusable across different use-cases or scenarios?</li>
<li>Should the view be annotated with application-specific tags or markup?</li>
<li>Where should the bulk of the business logic reside? (in the model? in the controller?)</li>
<li>How is the application state persisted or accessed?</li>
</ul>
<p>Lets explore some of the existing patterns and how they answer these questions:

</p>
<ul>
<li><a href="#mvc">Model-View-Controller</a></li>
<li><a href="#model2">Model2</a></li>
<li><a href="#mvp-mvvm">Model-View Presenter and Model-View-ViewModel</a></li>
<li><a href="#modern-javascript-implementations">Modern Javascript Implementations</a></li>
<li><a href="#real-time-implications">Real-time Implications</a></li>
<li><strong>tl;dr?</strong> <a href="#rvp">Introducing Resource-View-Presenter</a></li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
<p><br><br>

</p>
<p><a name="mvc"></a>
</p>
<h1>MVC</h1>
<p><img src="scaling-isomorphic-javascript-code/mvc.png" style="margin-left: 70px;">
<br><span style="margin-left: 180px;"><strong>Figure 1: Model-View-Controller</strong></span>

</p>
<p>The traditional Model-View-Controller pattern assumes a long-lived view and a swappable Controller. For example, in a given view you may have different Controller logic depending on who is logged in. At a high-level no decision is made about how the view is rendered (i.e. what templating engine is used). 

</p>
<p>Given the assumption of a long-lived view and that user interaction is by definition coming into the view, traditional MVC is a very useful pattern for front-end development. As we will explore later, a slightly modified version of this pattern is in fact what <a href="http://documentcloud.github.com/backbone">Backbone.js</a> uses. 
<br><br>

</p>
<p><a name="model2"></a>
</p>
<h1>Model2</h1>
<p><img src="scaling-isomorphic-javascript-code/model2-mvc.png" style="margin-left: 70px;">
<br><span style="margin-left: 170px;"><strong>Figure 2: Model2 Model-View-Controller</strong></span>

</p>
<p>Don't be scared if you've never heard of <a href="http://en.wikipedia.org/wiki/Model_2">Model2</a> before; it is a design pattern that dates back to 1999 when it was coined in an article by <em>Govind Seshadri: <a href="http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc.html">Understanding JavaServer Pages Model 2 architecture</a></em>. It can be argued that Model2 does not necessitate a fully-realized MVC pattern, but most modern implementations (such as <a href="http://andrzejonsoftware.blogspot.com/2011/09/rails-is-not-mvc.html">Ruby on Rails</a>) do formalize it in that way.

</p>
<p><img src="scaling-isomorphic-javascript-code/rails-model2-mvc.png" style="margin-left: 60px;">
<br><span style="margin-left: 140px;"><strong>Figure 3: Rails Model2 Model-View-Controller</strong></span>


</p>
<p>The common wisdom is that in Model2-like frameworks such as Ruby on Rails one should have "fat models and thin controllers". This is not the case for every application, but in practice it is generally what this author has seen. In the traditional MVC Controllers tend to be heavier (i.e. more business logic) due to their need to listen and react to input from the view so this decision seems to add up.

</p>
<p>Given the stateless nature of HTTP the Model2 View is truly ephemeral: <strong>no state maintained in the view itself between requests.</strong> In most server-side frameworks any application state is stored via <a href="http://en.wikipedia.org/wiki/HTTP_cookie">Session Cookies</a>. This makes the decision of a one-way communication between the Controller and View very logical, but also unsuitable for any front-end development.
<br><br>

</p>
<p><a name="mvp-mvvm"></a>
</p>
<h1>MVP and MVVM</h1>
<p>Both the Model-View-Presenter and Model-View-ViewModel patterns are similar to the traditional MVC pattern with a few key differences:

</p>
<ul>
<li>View does not have a direct reference to the Model</li>
<li>Presenter (or ViewModel) has a reference to the view and updates it based on changes to the model</li>
</ul>
<p>The MVP pattern is discussed at length by Martin Fowler (<a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html">here</a>, <a href="http://martinfowler.com/eaaDev/uiArchs.html">and here</a>) and is generally discussed in the context of two implementations: 
<br><br>

</p>
<ul>
<li><strong>Passive View:</strong> Design the view to be as naive as possible with the all but the absolute necessary presentation and business logic contained in the Presenter.</li>
<li><strong>Supervising Controller:</strong> Used in systems in which the declarative view can be expanded to encompass simple logic. In this incantation the Presenter should only take over when the declarative logic in the view cannot meet the system requirements. </li>
</ul>
<p><img src="scaling-isomorphic-javascript-code/mvp.png" style="margin-left: 70px;">
<br><span style="margin-left: 180px;"><strong>Figure 4: Model-View-Presenter</strong></span>

</p>
<p><br>
<img src="scaling-isomorphic-javascript-code/mvvm.png" style="margin-left: 70px;">
<br><span style="margin-left: 180px;"><strong>Figure 5: Model-View-ViewModel</strong></span>

</p>
<p>MVP and MVVM are almost indistinguishable with one key exception: <strong>MVVM assumes that changes in the ViewModel will be reflected in the view by a robust data-binding engine</strong>. Niraj Bhatt outlined the difference eloquently in his <a href="http://nirajrules.wordpress.com/2009/07/18/mvc-vs-mvp-vs-mvvm/">MVC vs. MVP vs. MVVM article</a>: <em>"For instance if View had a property IsChecked and Presenter was setting it in classic MVP, in MVVM ViewModel will have that IsChecked Property which View will sync up with."</em>

</p>
<p>The positive end of the MVP and MVVM is that the Presenter (or ViewModel) is easier to unit-test because the state of the View is by definition contained in methods invoked by (MVP) or properties set on (MVVM) by the Presenter or ViewModel respectively.

</p>
<p><a name="mvp-mvvm-almost-works"></a>
For front-end development either of these patterns are perfectly acceptable choices. A routing layer can pass control to the appropriate Presenter (or ViewModel) which in-turn can update and respond to a persistent view in the browser. With some massaging either could also be re-worked for use on the server for one reason: <strong>there is no connection between the model and the view.</strong> This allows for an ephemeral view which is rendered by a given Presenter (or ViewModel). <a href="#rvp">As we will see later on</a>, this modified pattern can be truly isomorphic. 

</p>
<p><br>
<a name="modern-javascript-implementations"></a>
</p>
<h1>Modern Javascript Implementations</h1>
<p>The design patterns presented above have many modern implementations today:

</p>
<ul>
<li><a href="http://documentcloud.github.com/backbone">Backbone.js</a></li>
<li><a href="http://batmanjs.org">Batman.js</a></li>
<li><a href="http://angularjs.org">Angularjs</a></li>
<li><a href="http://javascriptmvc.com">JavascriptMVC</a></li>
<li><a href="http://sammyjs.org/">Sammy</a></li>
</ul>
<p>These frameworks are generally used for creating <a href="http://blog.nodejitsu.com/single-page-apps-with-nodejs">Single-Page Applications</a> (although more traditional AJAX is also possible). User Interaction within a single-page application comes in two distinct flavors: 
<br><br>

</p>
<ul>
<li><strong>OnHashChanged or pushState events:</strong> Occur when the URL in the browser changes. For example: navigating to <a href="http://myapp.local/#/some-page">http://myapp.local/#/some-page</a></li>
<li><strong>DOM events:</strong> Occur when a user makes a specific interaction with the current DOM. For example: clicking on an anchor tag. </li>
</ul>
<p><br>
Lets consider some of the patterns and architectures used. If you're interested in further reading check out <a href="http://michaux.ca/articles/mvc-architecture-for-javascript-applications">Peter Michaux's article on MVC Architecture for Javascript Applications</a>. 
<br><br>

</p>
<p><a name="backbone-mvc"></a>
</p>
<h1>Backbone</h1>
<p><a href="http://documentcloud.github.com/backbone">Backbone.js</a> is one of the most popular client-side development frameworks available today. At it's core it is an implementation of the traditional Model-View-Controller pattern. When we examine it in more detail, however, we can see that there are some deviations from the traditional MVC pattern explored earlier. 

</p>
<p><img src="scaling-isomorphic-javascript-code/backbone-mvc.png" style="margin-left: 70px;">
<br><span style="margin-left: 180px;"><strong>Figure 6: Backbone Model-View-Controller</strong></span>

</p>
<p>In the diagram above we have separated the control-flow represented by <em>OnHashChanged</em> and <em>DOM</em> events to illustrate the separate entry points offered by Backbone. By illustrating this nuance it is clear that Backbone has one important difference from traditional MVC: <strong>the View manipulates the Model</strong>. When we examine the <a href="http://documentcloud.github.com/backbone/docs/todos.html">Backbone Todo Sample</a>, we can see this is clearly the accepted common wisdom:

</p>
<p><div class="snippet"><pre><code>window.AppView = Backbone.View.extend({
  <span class="comment">// ....</span>

  <span class="comment">//</span>
  <span class="comment">// When a TodoView is instantiated it is passed an</span>
  <span class="comment">// instance of the Todo model.</span>
  <span class="comment">//</span>
  addOne: <span class="function"><span class="keyword">function</span><span class="params">(todo)</span> {</span>
    <span class="keyword">var</span> view = <span class="keyword">new</span> TodoView({model: todo});
    <span class="keyword">this</span>.$(<span class="string">"#todo-list"</span>).append(view.render().el);
  }
  
  <span class="comment">// ....</span>
});

window.TodoView = Backbone.View.extend({
  <span class="comment">// ....</span>
  
  <span class="comment">//</span>
  <span class="comment">// Here the TodoView updates the state of the Todo model.</span>
  <span class="comment">// This breaks from the traditional MVC in which the view</span>
  <span class="comment">// only listens for changes on the Model.</span>
  <span class="comment">//</span>
  toggleDone: <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
    <span class="keyword">this</span>.model.toggle();
  }
  
  <span class="comment">// ....</span>
});</code></pre></div>

</p>
<p>The decision to break from the traditional MVC pattern gives large Backbone applications all similar feel: <em>thin controllers and models combined with heavy views.</em> These business logic-heavy views are essentially Presenters when looked at objectively. In a large Backbone codebase you should expect <em>a large number of views composited together via a DOM framework like jQuery or zepto.</em>

</p>
<p>There is nothing wrong with breaking from the traditional MVC pattern; in the context of front-end development having a reference to the Model from the View removes a lot of bookkeeping logic from the application. It does, however, make it a pattern that is not isomorphic. 
<br><br>

</p>
<p><a name="batman-mvvm"></a>
</p>
<h1>Batman</h1>
<p><a href="http://batmanjs.org">Batman.js</a> is a new Javascript framework that was discussed at <a href="http://2011.jsconf.us/#/proposal/6f23fd600302403a9f53e11390186b11">JSConf 2011</a>. Although the entities within Batman are Model, View, and Controller. The presence of a strong <a href="http://batmanjs.org/documentation.html#introduction">data binding engine and pure HTML views</a> suggests that it is actually an implementation of the <a href="#mvp-mvvm">Model-View-ViewModel</a>. 

</p>
<p><img src="scaling-isomorphic-javascript-code/batman-mvvm.png" style="margin-left: 70px;">
<br><span style="margin-left: 170px;"><strong>Figure 7: Batman Model-View-ViewModel</strong></span>

</p>
<p>Having not worked with Batman much it is difficult to say with confidence what a large Batman codebase looks like. That said: <em>the emphasis on the binding engine and thin views suggest that business logic will end up spread between the Controllers and Models within a given application.</em> 

</p>
<p>As with <a href="#backbone-mvc">Backbone</a>, Batman breaks from the traditional <a href="#mvp-mvvm">Model-View-ViewModel</a> pattern in that <strong>the Model communicates directly with the View and the ViewModel (i.e. Controller) does not manipulate the View directly</strong>. In addition, because of the references between the Model and the View it is not easily reusable as a server-side pattern. It is, however, more easily massaged into a server-side pattern if a Composite or Adapter pattern is implemented in the Model layer to render a static view and respond to real-time requests.
<br><br>

</p>
<p><a name="real-time-implications"></a>
</p>
<h1>Real-time implications</h1>
<p>Among all of the developer buzz one topic continues to be at the forefront: <strong>realtime web applications.</strong> <a href="http://nodejitsu.com">Nodejitsu</a> is an official sponsor of the upcoming <a href="http://krtconf.com/">Keeping it Realtime conference in Portland</a>; check it out! So how do some of the patterns we've examined stack up for realtime support (such as <a href="http://en.wikipedia.org/wiki/WebSocket">WebSockets</a>)? 
<br><br>

</p>
<ul>
<li><strong>Model-View-Controller <em>(Yes)</em>:</strong> Model(s) can listen for real-time events and update the view appropriately.</li>
<li><strong>Model2 <em>(No)</em>:</strong> The Ephemeral View concept is baked into the Model2 pattern. That is: <em>Controller(s) do not listen for events from the Model.</em> </li>
<li><strong>Model-View-Presenter <em>(Yes)</em>:</strong> Model(s) can listen for real-time events, which will propagate to the Presenter(s) who will update the view appropriately.</li>
<li><strong>Model-View-ViewModel <em>(Yes)</em>:</strong> Model(s) can listen for real-time events, which will propagate to the ViewModel(s) who will update the view appropriately.</li>
</ul>
<p><br>
The acceptability of MVC, MVP, and MVVM patterns make <a href="http://documentcloud.github.com/backbone">Backbone.js</a> or <a href="http://batmanjs.org">Batman.js</a> workable realtime frameworks for front-end developments. On the server-side this fact no longer holds true because as we have shown: <strong>traditional MVC, MVP, and MVVM patterns will not work for static views due to the tight coupling between the View and the Model.</strong>

</p>
<p><strong><em>Enter the <a href="#rvp">Resource-View-Presenter pattern</a>.</em></strong>
<br><br>

</p>
<p><a name="rvp"></a>
</p>
<h1>Introducing Resource-View-Presenter</h1>
<p>As we have shown: <strong>the <a href="#mvc">MVC</a>, <a href="#mvp-mvvm">MVP</a>, and <a href="#mvp-mvvc">MVVM</a> patterns will not work on both the client and the server.</strong> At the crux of Resource-View-Presenter is the realization that no pattern will work flawlessly both on the client and the server without some modification. As was suggested when <a href="#mvp-mvvm-almost-works">examining the MVP and MVVM patterns</a>, it is possible to make these patterns truly isomorphic due to their <strong>decoupled Model and View layers.</strong>

</p>
<p>The main decisions which Resource-View-Presenter are:
<br><br>

</p>
<ul>
<li>Decouple the Model and View</li>
<li>Recognize and plan for the differences between the Client and Server.</li>
<li>Expect a thin View, and a heavy Presenter and Resource.</li>
<li>Prefer business logic in the Resource over the Presenter.</li>
<li>Allow for both ephemeral (i.e. static server-side views) and persistent Views (i.e. the DOM).</li>
<li>Prefer a Presenter over a ViewModel to preserve the purity of the Markup (i.e. HTML).</li>
<li>Assume a persistent Presenter and Model.</li>
</ul>
<p>Although these decision may seem as though they are random, each has a specific purpose:
<br><br>

</p>
<ul>
<li>By decoupling the Model and the View we allow for both ephemeral and persistent Views</li>
<li>A thin View is consistent with modern, logic-less templating engines such as <a href="https://github.com/hij1nx/weld">weld</a> and <a href="http://mustache.github.com/">mustache</a>.</li>
<li>Having a Presenter instead of a ViewModel is consistent with designer-friendly templating such as <a href="https://github.com/hij1nx/weld">weld</a>.</li>
<li>Assuming a persistent Presenter and Model both on the Client and Server enables encapsulation of real-time functionality in Presenters on both sides.</li>
</ul>
<p>Lets dig deeper. On the Client-side Resource-View-Presenter resembles a traditional MVP pattern. The choice to rename  the Model to Resource is heavily influenced by our assumption to <em>prefer business logic in the Resource over the Presenter.</em> This makes the Resource in RVP more similar to the heavy Models found in Model2, not traditional MVP the nomenclature denotes that. When implementing RVP the litmus test for what logic belongs in the Presenter is two fold: <strong>any Presentation-specific logic which is too heavy for a "thin" View or any business logic which utilizes global application state</strong>.

</p>
<p>As with <a href="http://documentcloud.github.com/backbone">Backbone</a> and <a href="http://batmanjs.org">Batman</a>, Client-side RVP implementations should support both OnHashChange / pushState routing and DOM events.

</p>
<p><img src="scaling-isomorphic-javascript-code/client-rvp.png" style="margin-left: 30px;">
<br><span style="margin-left: 170px;"><strong>Figure 8: Client-side Resource-View-Presenter</strong></span>

</p>
<p><br><br>
On the Server-side Resource-View-Presenter is almost identical with one notable exception: <strong>the View is ephemeral and does not pass calls or have a reference to the Presenter.</strong> In fact, when using RVP for JSON-based web-services the view is practically non-existent; it is just a call to <code>JSON.stringify()</code>.
<br><br>

</p>
<p><img src="scaling-isomorphic-javascript-code/server-rvp.png" style="margin-left: 40px;">
<br><span style="margin-left: 170px;"><strong>Figure 9: Server-side Resource-View-Presenter</strong></span>

</p>
<p><br><br>
At first glance, Server-side RVP may seem similar to <a href="#model2">Model2 MVC</a>, but the persistent-nature of both the Presenter and Model to support real-time events makes this similarity is only skin deep. RVP does this by listening for events and changes on the model which may be backed by a real-time data source such as <a href="http://redis.io/topics/pubsub">Redis PubSub</a> or <a href="http://guide.couchdb.org/draft/notifications.html">CouchDB changes</a>. 

</p>
<p>The real-time support is of particular note because it enables the application developer to <strong>focus on the business logic, not the underlying network transport.</strong> This may seem trivial, but examine the pattern (or lack there-of) offered by <a href="http://expressjs.org">Express</a> and <a href="http://socket.io">Socket.io</a> (the most popular node.js Framework and Realtime IO libraries respectively) and it becomes clear that it is not. 

</p>
<p><img src="scaling-isomorphic-javascript-code/express.png" style="margin-left: 30px;">
<br><span style="margin-left: 170px;"><strong>Figure 10: Express and Socket.io</strong></span>

</p>
<p><br><br>
This is not meant to be an attack on <a href="http://expressjs.org">Express</a> or <a href="http://socket.io">Socket.io</a>; they both are explicit in what they offer and they both do it exceptionally well. A higher-level design pattern is simply not a concern. 
<br><br>

</p>
<p><a name="conclusion"></a>
</p>
<h1>Conclusion</h1>
<p>Writing large applications is hard. Encapsulating and reusing components of those applications across the Client and the Server is even harder. After considering this analysis it is hopefully clear how utilizing the Resource-View-Presenter pattern within your own applications will help to make this easier. 

</p>
<p><strong>Don't have the time to implement it yourself? No problem!</strong> This article is the result of a lot of careful thought and hard work born from the <a href="http://npmtop.nodejitsu.com/">massive open-source undertaking</a> Nodejitsu has been apart of from the beginning. Our philosophy remains the same: <strong>build the best tools and the best systems will follow.</strong> 

</p>
<p>And follow they will. If you haven't guessed already, we have an epic open-source release coming up that will implement the Resource-View-Presenter pattern. So if you have any feedback, <a href="http://nodejitsu.assistly.com/customer/portal/questions/new">let us know!</a>. And stay close, I will be announcing the release at <a href="http://swdc.se/2011/">SWDC 2011 in Stockholm, Sweden on November 9th.</a>. 

</p>
<p><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/scaling-isomorphic-javascript-code</link><guid isPermaLink="true">http://blog.nodejitsu.com/scaling-isomorphic-javascript-code</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Tue, 18 Oct 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./practical-nodejs-docs">Practical Node.js Docs</a>]]></title><description><![CDATA[<ul>
<li><strong>Site:</strong> <a href="http://docs.nodejitsu.com">http://docs.nodejitsu.com</a></li>
<li><strong>Github:</strong> <a href="https://github.com/nodejitsu/docs">https://github.com/nodejitsu/docs</a></li>
</ul>
<p>A few weeks ago we released <a href="http://docs.nodejitsu.com">http://docs.nodejitsu.com</a>, just in time for <a href="http://www.nodeknockout.com">Node Knockout</a>! docs.nodejitsu.com is a collection of community written tutorials and how-to articles for <a href="http://nodejs.org">node.js</a>. There are <em>over fifty articles</em> so far, from the <a href="http://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks">basics</a> all the way up to <a href="http://docs.nodejitsu.com/articles/cryptography/how-to-use-crypto-module">more difficult topics</a>. We like to think of it as our unofficial, non-competing entry into NKO. We also, of course, hoped that the actual competitors would find it useful.


</p>
<p><br>


</p>
<h2> </h2>
<p>Like our software, all of the articles are <a href="https://github.com/nodejitsu/docs">hosted on github</a>. Contributors can fork the project on github, edit the files in markdown (or add new ones), and submit a pull request. We are actively working on adding more features to the site, such as a tighter integration to <a href="http://search.npmjs.org"><a href="http://search.npmjs.org">http://search.npmjs.org</a></a>


</p>
<p>Aside from Nodejitsu's West Coast Team, we've already had a number of other contributors including: <a href="http://marcorogers.com/blog/">Marco Rogers</a>., <a href="https://github.com/deanlandolt">Dean Landolt</a>, <a href="https://github.com/adammw">Adam Malcontenti-Wilson</a>, and <a href="https://github.com/pkumar">Pavan Sunkara</a>. Thank you all! We still need <strong>more</strong> articles, so if you are interested in becoming a community contributor (and possibly getting compensated for your work), please contact us at <a href="mailto:docs@nodejitsu.com">docs@nodejitsu.com</a>.

</p>
<p>We hope that the Node.js community finds <a href="http://docs.nodejitsu.com">http://docs.nodejitsu.com</a> a handy resource and, through community contributions, it becomes the de facto source for practical Node.js documentation.
</p>
]]></description><link>http://blog.nodejitsu.com/practical-nodejs-docs</link><guid isPermaLink="true">http://blog.nodejitsu.com/practical-nodejs-docs</guid><dc:creator><![CDATA[Josh Holbrook]]></dc:creator><pubDate>Tue, 20 Sep 2011 17:17:12 GMT</pubDate></item><item><title><![CDATA[<a href="./http-proxy-middlewares">Node-HTTP-Proxy, Middlewares, and You</a>]]></title><description><![CDATA[<p>When the <code>Node HTTP Proxy</code> was built, its purpose was performance.  The concept of a <code>stream</code> in Node lends itself beautifully to working with HTTP requests - HTTP requests are, after all, TCP streams in the first place.  One of Node's strengths is its facility for streaming data, and a great deal of performance can be achieved simply by piping the request and response streams to other destinations, and back again.  This, therefore, was how the HTTP Proxy was designed - and it does its job well.  


</p>
<p>The problem here is that the extremely popular <code>middleware</code> style of web application development is often incompatible.  If you use a body decoder middleware, for example, every request will need to be buffered in full before the body can be properly decoded.  This increases memory usage and reduces performance, compared to simply relaying un-altered requests and responses to other destinations - it all has to be waited for, read into memory, possibly altered, then sent again, adding to both the time and resource cost of each request.

</p>
<p><br>


</p>
<h2> </h2>
<p>More importantly, though, if any subsequent middleware in your middleware chain tries to listen for 'data' or 'end' events, or otherwise treat the current HTTP connection as a stream, it just won't work, as a buffered request is no longer a stream - it is now just a data object.  

</p>
<p>Despite these concerns, 'middlewares' are an easy concept to grasp, easy to use, and are likely to remain popular.  There are some gains to be had, as well - middlewares are a simple way to add new features to your application stack.  If you find yourself wishing for a certain feature, the ability to use or write a middleware to add that feature can save everyone a lot of time, compared to the amount of time a pull request can take to be reviewed and merged.  It also allows for conflicting features to exist more easily - finding out that two middlewares won't work well together is a much smaller problem than dealing with successive breaking API changes in a library.  

</p>
<p>Due to these facts, and the number of requests we've received from users who want to proxy to that style of application, we have added middleware support to Node HTTP Proxy.

</p>
<p>Here's a basic example of how to use a middleware - specifically, the <code>connect-gzip</code> middleware.  This would <code>gzip</code>-compress every file you serve.  It can be a useful trick, at times, when applied to specific file types - replace the <code>/.*/</code> with <code>/png/</code>, for example.

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> http = require(<span class="string">'http'</span>),
    httpProxy = require(<span class="string">'http-proxy'</span>),
    gzip = require(<span class="string">'connect-gzip'</span>);

httpProxy.createServer(
  gzip.gzip({ matchType: <span class="regexp">/.*/</span> }),
  <span class="number">9000</span>, <span class="string">'localhost'</span>
).listen(<span class="number">8000</span>);

http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res)</span> {</span>
  res.writeHead(<span class="number">200</span>, { <span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span> });
  res.write(<span class="string">'request successfully proxied to: '</span> + req.url + <span class="string">'\n'</span> + JSON.stringify(req.headers, <span class="literal">true</span>, <span class="number">2</span>));
  res.end();
}).listen(<span class="number">9000</span>);</code></pre></div>

</p>
<p>The basic idea is that when you call <code>httpProxy.createServer</code>, you can now pass in any middlewares as arguments, in the order in which you'd like them to be used.  If one of your middlewares doesn't set your proxy destination for you, pass in the <code>port</code> and <code>host</code> you want to proxy to at the end of the list, as shown above.

</p>
<p>Here is another simple middleware usage example, this one using an example middleware by Nodejitsu's Mad-Scientist-in-Residence, Dominic Tarr, called <code>proxy-by-url</code>.  Available on <code>npm</code>, this middleware provides a sugar syntax for defining both forward and reverse proxy destinations in the same block, and routing to them based on URL matching. 

</p>
<p><div class="snippet"><pre><code><span class="constant">httpProxy</span>.<span class="constant">createServer</span>(
  <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'proxy-by-url'</span>)({
  <span class="string">'/github'</span><span class="symbol">:</span> { <span class="identifier">port</span><span class="symbol">:</span> <span class="number">80</span>, <span class="identifier">host</span><span class="symbol">:</span> <span class="string">'github.com'</span> },
  <span class="string">'/nodejitsu'</span><span class="symbol">:</span> { <span class="identifier">port</span><span class="symbol">:</span> <span class="number">80</span>, <span class="identifier">host</span><span class="symbol">:</span> <span class="string">'nodejitsu.com'</span> },
  <span class="string">'/localstuff'</span><span class="symbol">:</span> { <span class="identifier">port</span><span class="symbol">:</span> <span class="number">8080</span>, <span class="identifier">host</span><span class="symbol">:</span> <span class="string">'localhost'</span> } 
  })
).<span class="identifier">listen</span>(<span class="number">8000</span>);</code></pre></div>

</p>
<p>Now let's take a look at how to make a middleware - even if you don't plan to make one of your own, the structure is very straightforward, and understanding it will help you better understand how middlewares work.  This middleware is for very simple logging - it will write the headers of each request to a logfile.

</p>
<p><div class="snippet"><pre><code>

<span class="keyword">var</span> fs = require(<span class="string">'fs'</span>),
    http = require(<span class="string">'http'</span>),
    httpProxy = require(<span class="string">'../lib/node-http-proxy'</span>);


module.exports = <span class="function"><span class="keyword">function</span> <span class="params">(logging)</span> {</span>
  <span class="comment">// Code here is run when the middleware is initially loaded.</span>
  <span class="keyword">var</span> logFile = fs.createWriteStream(<span class="string">'./requests.log'</span>);

  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">(request, response, next)</span> {</span>
    <span class="comment">// Code here is run on each request.</span>
    <span class="keyword">if</span> (logging) {
      logFile.write(JSON.stringify(request.headers, <span class="literal">true</span>, <span class="number">2</span>));
    }
    next();
  }
}
</code></pre></div>

</p>
<p>This middleware can now be used like the others:

</p>
<p><div class="snippet"><pre><code><span class="constant">httpProxy</span>.<span class="constant">createServer</span>(
  <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'./example-middleware'</span>)(<span class="identifier"><span class="keyword">true</span></span>),
  <span class="number">8000</span>, <span class="string">'localhost'</span>
).<span class="identifier">listen</span>(<span class="number">9000</span>)</code></pre></div>

</p>
<p>In other Node HTTP Proxy news, we at Nodejitsu have also been fortunate enough, in the last several weeks, to receive a number of high-quality patches and bug fixes from <a href="http://github.com/isaacs">isaacs</a>. As a result, the resilience and stability of Node HTTP Proxy have been significantly enhanced.  

</p>
<p>So the next time you run into isaacs, say thanks!  (With beer.)
</p>
]]></description><link>http://blog.nodejitsu.com/http-proxy-middlewares</link><guid isPermaLink="true">http://blog.nodejitsu.com/http-proxy-middlewares</guid><dc:creator><![CDATA[Charlie McConnell]]></dc:creator><pubDate>Thu, 15 Sep 2011 20:46:35 GMT</pubDate></item><item><title><![CDATA[<a href="./spawning-hookio-hooks">Spawning hook.io Hooks</a>]]></title><description><![CDATA[<p>In a follow-up to my <a href="http://blog.nodejitsu.com/hookio-video-tutorials">previous blog</a> about getting started with hook.io, I created five additional video tutorials on how to spawn hook.io hooks and child processes in your hook.io cloud. I've also created a <a href="http://youtube.com/maraksquires">youtube account you can subscribe to for more videos</a>.

</p>
<p>You can also find a mirror of these videos @ <a href="https://github.com/hookio/tutorials"><a href="https://github.com/hookio/tutorials">https://github.com/hookio/tutorials</a></a>

</p>
<p>Enjoy!

</p>
<p><br>


</p>
<p>Exploring the Core API

</p>
<ol>
<li>#12 <a href="http://youtu.be/am4U-hfRpIQ">A quick lesson in fault tolerance Part 1</a></li>
<li>#13 <a href="http://youtu.be/y_3CnUh_hI0">A quick lesson in fault tolerance Part 2</a></li>
<li>#14 <a href="http://youtu.be/r-u80MsYjac">Spawning child hooks Part 1</a></li>
<li>#15 <a href="http://www.youtube.com/watch?v=3-vDtA74a1c">Spawning child hooks Part 2</a></li>
<li>#16 <a href="http://www.youtube.com/watch?v=NZu7QHOLOSQ&amp;feature=channel_video_title">Full-featured child hook spawning with Haibu and Haibu-Carapace</a></li>
<li>#17 <a href="http://www.youtube.com/watch?v=8NvigYnLkA8&amp;feature=channel_video_title">Using Hook.io to Install NPM Packages Anywhere</a></li>
</ol>
<p><br>


</p>
<h2> </h2>
<p><strong>Note: I apologize for small text size, I will try to improve this on the next batch of screencasts</strong>


</p>
<iframe width="480" height="390" src="http://www.youtube.com/embed/am4U-hfRpIQ" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

<p><hr>
</p>
<p><iframe width="480" height="390" src="http://www.youtube.com/embed/y_3CnUh_hI0" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
</p>
<hr>

<p><iframe width="480" height="390" src="http://www.youtube.com/embed/r-u80MsYjac" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
</p>
<hr>

<p><iframe width="480" height="390" src="http://www.youtube.com/embed/3-vDtA74a1c" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
</p>
<hr>

<p><iframe width="480" height="390" src="http://www.youtube.com/embed/NZu7QHOLOSQ" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
</p>
<hr>

<p><iframe width="480" height="390" src="http://www.youtube.com/embed/8NvigYnLkA8" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
</p>
<hr>

]]></description><link>http://blog.nodejitsu.com/spawning-hookio-hooks</link><guid isPermaLink="true">http://blog.nodejitsu.com/spawning-hookio-hooks</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Thu, 15 Sep 2011 02:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./hookio-video-tutorials">hook.io video tutorials</a>]]></title><description><![CDATA[<p><a href="http://github.com/hookio/">hook.io</a> is a full featured i/o framework for node.js. hook.io allows you to create clouds of node.js processes which seamlessly communicate with each other to form fault-tolerant distributed systems.</p>

<p>hook.io is a radical departure from how web applications are currently being built. hook.io itself is very easy to use, but the concepts behind it can be hard to understand from only reading the documentation and unit tests.

</p>
<p>For this reason, I have created <em>eleven</em> short video tutorials for explaining the basic usage and functionality of hook.io

</p>
<p>You can also find a mirror of these videos @ <a href="https://github.com/hookio/tutorials"><a href="https://github.com/hookio/tutorials">https://github.com/hookio/tutorials</a></a>

</p>
<p><strong>UPDATE: <a href="http://blog.nodejitsu.com/spawning-hookio-hooks">6 more videos on Spawning hook.io Hooks</a></strong>

</p>
<p><strong>DOUBLE UPDATE: Due to popular demand, I have converted and uploaded all videos to youtube. You can subscribe here: <a href="http://www.youtube.com/maraksquires">http://www.youtube.com/maraksquires</a></strong>

</p>
<p>Enjoy!

</p>
<p><br>


</p>
<ol>
<li><a href="http://www.youtube.com/watch?v=7lP0sBwv46c">The Basics Part 1</a></li>
<li><a href="http://www.youtube.com/watch?v=8OnJl2vUeKQ">The Basics Part 2</a></li>
<li><a href="http://www.youtube.com/watch?v=kxt9OmAOsNo">The Basics Part 3</a></li>
<li><a href="http://www.youtube.com/watch?v=cutuegVrYV0">IRC Hook Configuration Part 1</a></li>
<li><a href="http://www.youtube.com/watch?v=OupAl4S1vL0">IRC Hook Configuration Part 2</a></li>
<li><a href="http://www.youtube.com/watch?v=7rWvhYB8lUE">3 Minute IRC Bot</a></li>
<li><a href="http://www.youtube.com/watch?v=koielkLkTXs">Hook.io Libraries</a></li>
<li><a href="http://www.youtube.com/watch?v=De09kro6yC0">HTTP Webhook Server</a></li>
<li><a href="http://www.youtube.com/watch?v=kop0LEUKNwk">Socket.io Bridge to Browser</a></li>
<li><a href="http://www.youtube.com/watch?v=a2-gHIMSnUo">Emit events from CouchDB _changes feed</a></li>
<li><a href="http://www.youtube.com/watch?v=HsVXjTvmV0M">Extending an existing application</a></li>
</ol>
<p><br>


</p>
<h2> </h2>
<p><strong>Note: I apologize for the low quality audio and strange video overlays. I've fixed this problem in the newer batches of videos</strong>

</p>
<p><br>

</p>
<iframe width="640" height="390" src="http://www.youtube.com/embed/7lP0sBwv46c" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="640" height="390" src="http://www.youtube.com/embed/8OnJl2vUeKQ" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="640" height="390" src="http://www.youtube.com/embed/kxt9OmAOsNo" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="480" height="390" src="http://www.youtube.com/embed/cutuegVrYV0" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="640" height="390" src="http://www.youtube.com/embed/OupAl4S1vL0" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="640" height="390" src="http://www.youtube.com/embed/7rWvhYB8lUE" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="640" height="390" src="http://www.youtube.com/embed/koielkLkTXs" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="480" height="390" src="http://www.youtube.com/embed/De09kro6yC0" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="640" height="390" src="http://www.youtube.com/embed/kop0LEUKNwk" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="480" height="390" src="http://www.youtube.com/embed/a2-gHIMSnUo" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<hr>
<iframe width="480" height="390" src="http://www.youtube.com/embed/HsVXjTvmV0M" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
]]></description><link>http://blog.nodejitsu.com/hookio-video-tutorials</link><guid isPermaLink="true">http://blog.nodejitsu.com/hookio-video-tutorials</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Tue, 13 Sep 2011 02:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./using-nodejitsu-for-nko">Using Nodejitsu for Node Knockout</a>]]></title><description><![CDATA[<p>I'm happy to announce that Nodejitsu will be available as an <strong>official</strong> option for your Node Knockout entry. You will need a Nodejitsu account, so if you haven't gotten one yet, you can try joining #nodejitsu on irc.freenode.net to get your account activated...

</p>
<p><br>

</p>
<h2>First, install our CLI tool from NPM</h2>
<pre><code>npm install jitsu -g</code></pre>
<h2>Now lets fire up our Node Knockout wizard!</h2>
<pre><code>cd /path/to/mynewapp
jitsu knockout</code></pre>
<p><strong>That's it!</strong>

</p>
<p>From here you will be prompted for your Knockout Secret Code, and then <code>jitsu</code> will generate and deploy a simple helloworld application for you that will register with Node Knockout's website.

</p>
<h2>Additional Deploys</h2>
<p>Need to update your app? Add <code><span class="keyword">new</span> package.json</code> dependencies? Websockets? Custom C++ addons? No problem!

</p>
<p><strong>For new deploys just type:</strong>

</p>
<pre><code>jitsu deploy</code></pre>
<p><em>It's super simple!</em>

</p>
<h2>Questions? Problems?</h2>
<p>We've got the full Nodejitsu team on duty ready and waiting to help you. The best place to get support is in #nodejitsu on irc.freenode.net. You can also email support@nodejitsu.com 
</p>
]]></description><link>http://blog.nodejitsu.com/using-nodejitsu-for-nko</link><guid isPermaLink="true">http://blog.nodejitsu.com/using-nodejitsu-for-nko</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Fri, 26 Aug 2011 05:01:00 GMT</pubDate></item><item><title><![CDATA[<a href="./top-node-module-creators">Top node.js module creators</a>]]></title><description><![CDATA[<p>In my <a href="http://blog.nodejitsu.com/most-active-nodejs-users">ongoing</a> <a href="http://blog.nodejitsu.com/most-influential-github-users-by-location">quest</a> to make lists with my name on them, I've setup a site to view the top 100 NPM ( <a href="http://npmjs.org/">Node Package Manager</a> ) module creators. In this article I will go through the current top ten and give a quick bios for each person.

</p>
<p><strong>Warning:</strong> <em>These numbers should not be used for anything meaningful, and are possibly wrong. The data is pulled from <a href="http://search.npmjs.org"><a href="http://search.npmjs.org">http://search.npmjs.org</a></a> and uses <a href="http://github.com/substack">SubStack</a>'s nifty tool: <a href="http://github.com/substack/npmtop">npmtop</a></em>

</p>
<p>Hourly tallies can be found here: <a href="http://npmtop.nodejitsu.com"><a href="http://npmtop.nodejitsu.com">http://npmtop.nodejitsu.com</a></a>

</p>
<p><br>


</p>
<pre style="margin: 0px;">

  Generated: Fri Aug 19 2011 08:41:16 GMT+0000 (UTC) 

  rank   percent   packages   author
  ----   -------   --------   ------
     1    1.85 %     62.00    James Halliday
     1    1.85 %     62.00    TJ Holowaychuk
     3    1.59 %     53.00    AJ ONeal
     4    1.05 %     35.00    Dominic Tarr
     5    0.90 %     30.00    Isaac Z. Schlueter
     6    0.87 %     29.00    Marak Squires
     6    0.87 %     29.00    Nickolay Platonov
     8    0.72 %     24.00    Charlie Robbins
     8    0.72 %     24.00    Felix Geisendorfer
    10    0.66 %     22.00    George Stagas


</pre>

<p><br>

</p>
<h2> </h2>
<p><strong>Tied for 1st - James Halliday and TJ Holowaychuk</strong>


</p>
<p>James Halliday, aka <a href="http://github.com/substack">SubStack</a>, author of libraries such as: <a href="http://github.com/substack/dnode">dnode</a>, <a href="http://github.com/substack/node-browserify">browserify</a>, <a href="http://github.com/substack/node-burrito">burrito</a>, etc. Co-founder of <a href="http://browserling.com">Browserling</a>. All around Robot. 

</p>
<p>TJ Holowaychuk, aka <a href="http://github.com/visionmedia">visionmedia</a>, author of <a href="http://github.com/visionmedia/express">Express</a>, <a href="http://github.com/senchalabs/connect">Connect</a>, <a href="http://github.com/visionmedia/expresso">Expresso</a>, <a href="http://github.com/visionmedia/Jade">Jade</a>, etc. Engineer at <a href="http://learnboost.com">Learnboost</a>, an all-around nice guy, and he has a badass ferret named <a href="https://a248.e.akamai.net/assets.github.com/img/89d8e6624fb9153c40bd11ae7592a74e058d873e/687474703a2f2f7370686f746f732e616b2e666263646e2e6e65742f6870686f746f732d616b2d736e63332f68733233342e736e63332f32323137335f3434363937333933303239325f3535393036303239325f31303932313432365f373233383436335f6e2e6a7067">Tobi</a>.

</p>
<p>I'll keep the profiles short for these two, they are open-source champions.

</p>
<p><strong>3rd - AJ Oneal</strong>

</p>
<p><a href="https://github.com/coolaj86/">AJ</a> is a Software Consultant living in Provo Utah. He's done a lot of work re-packaging and re-bundling client-side modules ( such as <a href="https://github.com/coolaj86/node-jquery">jQuery</a> ) to work server-side and to work with the <a href="https://github.com/ender-js/Ender">Ender.js</a> framework. He also has some pretty neat looking libraries like <a href="https://github.com/coolaj86/futures">Futures</a>. When I asked him for a bios he told me he was single, looking for ladies, and his favorite animal is a <a href="http://www.hrwiki.org/wiki/Trogdor">Trogdor</a>. I think AJ might be my new internet best friend.


</p>
<p><strong>4th - Dominic Tarr</strong>

</p>
<p>Resident <a href="http://blog.nodejitsu.com/mad-science-at-nodejitsu">Mad Scientist</a> at Nodejitsu. Dominic enjoys writing test frameworks for testing test frameworks, this requires a lot of support libraries. There is only one project of his that needs to be pointed out, and it's <a href="https://github.com/dominictarr/testbed">testbed</a>. In usual fashion, there is no documentation and <a href="http://testbedjs.org">the site</a> is currently offline. I think I might have to schedule an open-source intervention for Dominic to help get his project back online. Please send words of encouragement and pull requests to <a href="mailto:madscience@nodejitsu.com">madscience@nodejitsu.com</a>

</p>
<p><strong>5th - Isaac Z. Schlueter</strong>

</p>
<p>Friend, author of <a href="http://npmjs.org">NPM</a>, works for <a href="http://joyent.com">Joyent</a>, node.js core contributor, dislikes semi-colons. Including several support libraries for NPM, <a href="https://github.com/isaacs">Isaac</a> is also the author of libraries such as: <a href="https://github.com/isaacs/node-supervisor">node-supervisor</a>, <a href="https://github.com/isaacs/nave">nave</a>, and several <a href="http://en.wikipedia.org/wiki/Test_Anything_Protocol">TAP</a> ( Test Anything Protocol ) related libraries. Isaac's projects will help you improve your node.js development workflow. If you are intending to write large amounts of node code, you should read through his project list, it will make you a better programmer. 

</p>
<p><strong>Tied for 6th - Marak Squires and Nickolay Platonov</strong>

</p>
<p>I am <a href="http://github.com/marak">Marak Squires</a>, huzaah. I'm a co-founder of Nodejitsu and the creator of the <a href="http://hook.io">hook.io</a> framework. I have a fairly eclectic collection of projects including: <a href="http://github.com/marak/say.js">say.js</a>, <a href="http://github.com/marak/Faker.js">Faker.js</a>, <a href="http://github.com/marak/JSONLoops">JSONLoops</a>, <a href="http://github.com/marak/colors.js">colors.js</a>, <a href="http://github.com/marak/webservice.js">webservice.js</a>, <a href="http://github.com/marak/translate.js">translate.js</a>, and  <a href="http://github.com/marak/node-raps">node-raps</a>. I also assist in maintaining several <a href="http://github.com/nodejitsu">Nodejitsu projects</a>. The majority of my new projects are <a href="http://github.com/hookio">hook.io hooks</a> for helping create a Standard Hook Library. 

</p>
<p>Nickolay Platonov, aka <a href="http://github.com/SamuraiJack">SamuraiJack</a>, is a JavaScript expert from Russia and the author of the <a href="http://joose.it/">Joose</a> framework. Many of his projects are related to supporting Joose and <a href="http://en.wikipedia.org/wiki/Ext_JS">ExtJS</a> to build full-stack javascript solutions with rich user interfaces. If you are interested in building enterprise class applications using Joose and ExtJS, I don't think you will find someone with more expertise than Nickolay.

</p>
<p><strong>Tied for 8th - Charlie Robbins and Felix Geisendorfer</strong>

</p>
<p>Charlie Robbins ( aka <a href="http://github.com/indexzero">indexzero</a> ) is a co-founder at Nodejitsu, maker of hot sauce, and author of libraries such as: <a href="http://github.com/indexzero/Forever">Forever</a>, <a href="http://github.com/indexzero/Winston">Winston</a>, <a href="http://github.com/indexzero/Nconf">Nconf</a>.  He also leads development for Nodejitsu on <a href="http://github.com/nodejitsu">such projects</a> as: <a href="http://github.com/nodejitsu/node-http-proxy">node-http-proxy</a>, <a href="http://github.com/nodejitsu/haibu">haibu</a>, and <a href="http://github.com/nodejitsu/jitsu">jitsu</a>. Charlie's projects are among the highest quality projects available, and I do not say this lightly. I would recommend not only incorporating Charlie's work into your production stack, but actually diving into his projects to better understand best practices for Git workflow, Github project management, and node.js software development. 

</p>
<p><a href="http://github.com/felixge/">Felix</a> is a very tall and friendly man from Germany. He is the co-founder of <a href="http://debuggable.com">debuggable</a>, the first node.js consulting company. Felix has made numerous contributions to node's core and is best known for his libraries such as: <a href="https://github.com/felixge/node-formidable">node-formidable</a> and <a href="https://github.com/felixge/node-mysql">node-mysql</a> . Felix also has a lot of smaller libraries for performing very specific and useful things. You should take your time to scan through Felix's projects, there might be a gem in there that will save you several hours of time. 

</p>
<p>Felix, like Charlie, tends to only release high-quality projects. It's a safe bet that a project from either of these two will be useful, and work as intended.

</p>
<p><strong>10th - George Stagas</strong>

</p>
<p><a href="http://github.com/stagas">George</a> is a developer from Greece and an early Nodejitsu beta-tester. In addition to writing a lot of utility libraries, George also has some neat projects like <a href="https://github.com/stagas/Maga">Maga</a>, a lightweight framework for developing multiplayer physics-based games, and <a href="https://github.com/stagas/maptail">Maptail</a>, a visual client for mapping logs of ip address to a web map based on geographic location in real-time. 

</p>
<h2>Getting Daily Tallies</h2>
<p>Since people do enjoy tracking meaningless numbers, I've setup a quick application on Nodejitsu which wraps Substacks <a href="http://github.com/substack/npmtop">npmtop</a> and outputs the results every hour. It's all open-source, check it out!

</p>
<p><a href="http://npmtop.nodejitsu.com"><a href="http://npmtop.nodejitsu.com">http://npmtop.nodejitsu.com</a></a>

</p>
<h2>Remembering what's important</h2>
<p>These numbers are meaningless, it's the data and people behind the numbers that really matter. Through exploring this data we can get a better understanding of how developers contribute to node.js. Most developers don't have the time to maintain a lot of projects, but they do create and maintain projects that are of very high quality and actively maintained. Remember not to assume more === better.

</p>
]]></description><link>http://blog.nodejitsu.com/top-node-module-creators</link><guid isPermaLink="true">http://blog.nodejitsu.com/top-node-module-creators</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Fri, 19 Aug 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./painting-a-moving-picture">Painting a moving picture.</a>]]></title><description><![CDATA[<p><em>This is Part three of a four part series leading up to <a href="http://nodeknockout.com">Node Knockout</a></em>

</p>
<p>At Nodejitsu we believe in sharing knowledge. We believe that open source software fosters innovation, relationships and offers in return something better than the sum of its parts; a continuous growth cycle. If we tell you our good ideas, you'll make them better. Now go back two steps and repeat this process.

</p>
<p>Passionate open source projects, we understand that they should be both engineered and crafted. A patient attention to detail and refinement in our products and platform remains our methodology. These characteristics: open, crafted, and connected have evolved into the current incantation of the Nodejitsu brand. <br><br>

</p>
<h2> </h2>
<h1>Build a product that works.</h1>
<p>We have a platform that has become mature and ready for public consumption. One which is accessible to everyone, yet able to exceed the requirements of the enterprise. A platform tailored to the concerns of the developer. One with a pricing model that reflects usage rather than tenancy.<br><br>

</p>
<h1>Design simple.</h1>
<p>Simple designs are highly palatable. Less is more. Signal to noise ratios are critical. Carrying over these ideas from software engineering we reached out to <a href="http://tyrussmalley.com/">Tyrus Smalley</a>, friend, industry eminent, and creative force. Going through the motions of developing a visual language was a positive experience for a lot of reasons. The most important reason being that three technical co-founders coding 20 hours a day don't spend a lot of time thinking about presentation.<br><br>

</p>
<h1>Design relevant.</h1>
<p>Our new design has lots of wide open space. Space for you to think about the content. We wanted to describe a self-healing, distributed scaling intelligence in visual terms. Draw relevant diagrams that actually help illustrate these concepts. Answer questions such as <em>What is infrastructure opacity?</em>, <em>What is distributed scaling?</em> Some of these matters culminated in <a href="http://www.nodejitsu.com/#technology">this</a> animated diagram.<br><br>

</p>
<h1>Make a foundation.</h1>
<p>At first we started using a bonsai to depict an organic form that could be shaped and crafted. We retained the concept, but simplified the form. The simplification of the branches took shape as a cloud. And the rest of the tree was depicted as a node growing outward into the cloud with more nodes.

</p>
<p><img src="/painting-a-moving-picture/logo.png"><br><br>

</p>
<p>The word mark has mature modern forms with playful ligatures that keep things from getting too serious. We added a primary color (the blue color you can see it here on this blog or on the home page). We let the dark grey take the place of the secondary color, this keeps things looking subtle.<br><br>

</p>
<p><img src="/painting-a-moving-picture/wordmark.png"><br><br>

</p>
<h1>Painting a moving picture</h1>
<p>These forms offer us a visual foundation to build on, and we'll continue to capitalize on them. But this is a fast moving technology. Node.js is in development, our product continues to evolve. So as focused as we are  on the technology side, we wont forget to keep throwing paint on it and make sure it looks as good as it works.<br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/painting-a-moving-picture</link><guid isPermaLink="true">http://blog.nodejitsu.com/painting-a-moving-picture</guid><dc:creator><![CDATA[Paolo Fragomeni]]></dc:creator><pubDate>Tue, 16 Aug 2011 17:26:36 GMT</pubDate></item><item><title><![CDATA[<a href="./getting-refunds-on-open-source-projects">Getting refunds on open-source projects</a>]]></title><description><![CDATA[<p>I remember when I had no open-source projects and I had never even heard of Github. To me, the maintainers of open-source projects were mystical beasts who only existed in ethereal form over the internet. If I needed to get support for a library, it required hours of Googling, disabling the client-side gateway for ExpertsExchange, and begging random friends over AIM for help. Usually, I would wind up either giving up completely, repeating the process by picking a new library, or applying an awful hack to make the library work for my specific situation.

</p>
<p>It was only after I had begun to heavily use Github and Node.js that I realized these mystical beasts were actually real people, who work very hard on their projects, and generally strive for quality feedback so they can improve on their work.

</p>
<p>Unfortunately, as I now help maintain and contribute to over 100 open-source projects, I've seen a lot of inappropriate behavior from developers trying to seek support. I think much of this behavior is unintentional. There are not a lot of guidelines for developers to follow who are new to open-source. In this article, I will dive into many of the common issues open-source project maintainers encounter and I will help developers better understand how they can file for a refund on the open-source project they are using. 

</p>
<p><br><br>

</p>
<h2> </h2>
<h3>There are no refunds in open-source</h3>
<p>Most people understand this, sadly, some do not. If you are going to take an aggressive or angry approach when filing a request support, you are better off finding a new project. You need to understand that the person you are reaching out to has probably spent 100s of hours working on this project, for free. They do not owe you anything. The maintainers are extending a courtesy by giving away their work for free and then making themselves available to support it. 

</p>
<p>The point is, you should try and be nice when filing for support. The maintainer of the project has literally no obligation to help you.

</p>
<p><br> 

</p>
<h3>Wrong place, wrong time</h3>
<p>Want to really annoy an open-source maintainer? Then ignore any communication channels they have setup for support. If they setup a support wiki, send them a personal email. If they setup a Github Issues tracker, email the wrong mailing list about your question. If they setup an IRC room for support, send them direct messages over Twitter. If they setup a mailing list, post your issue to an unrelated forum. 

</p>
<p>The point is, take the time to actually research if the maintainer has setup a specific channel for support. If they have, use this channel. If you are uncertain, just reach out to the maintainer and ask where the best place to post support issues are.

</p>
<p><br>

</p>
<h3>Maintainers are not psychics</h3>
<p>Here is a list of things I do not know: Who you are, what project you are asking about, what software you are using, what operating system you are on, what versions of the software you are using, what your stack traces look like, what you had for breakfast, and what the code looks like that caused your issue.

</p>
<p>If you open up a support issue without providing this information, don't be surprised when the only response you get is asking for more information. Also, I probably don't care what you had for breakfast. 

</p>
<p><br>

</p>
<h3>Read the f*cking documentation</h3>
<p>If the author has taken the time to write documentation, you should read it. I don't write documentation for myself, I write it for other people. If the information you need isn't covered in the documentation, let the author know. They probably will want to add this information so other people don't ask the same question.

</p>
<p>If there is no documentation to read, you should ask the maintainer why. If you want to help contribute to the documentation, you might find the maintainer of the project wants to be your new best-friend. If the maintainer is unwilling to help document the project, or assist you in documenting it, you should probably find a new project to use.

</p>
<p><br>

</p>
<h3>Run the f*cking tests</h3>
<p>If the author has taken the time to write unit tests for the project, you REALLY need to confirm the unit tests work before trying to get support. Unit tests help provide a common way to test and isolate issues in a project. If you are having issues and one of your tests is also failing, it will be much easier to diagnosis the problem.

</p>
<p>If you file a support issue without confirming you ran the tests, don't be surprised when the response you get is asking you to confirm the tests are working.

</p>
<p><br>

</p>
<h3>Read the f*cking code</h3>
<p>Okay, this is a bit harsh. I don't expect everyone to read every single line of the code for a project they are trying to use, that isn't very reasonable. What I do see though, is that a lot developers have a mental barrier to actually opening up the source code for the project they are trying to use. They will read the documentation, run the tests, use the example code, but when they are faced with a problem that could be solved through a one or two line change in the source code, they shut down completely. 

</p>
<p>The point is that you shouldn't be afraid to jump into the source code. Even if you don't fully understand the source code, in many cases you should be able to isolate your issue to a specific block. If you can reference this block ( or line numbers ) when opening up your support request, it will help the author better understand your problem.

</p>
<p><br>

</p>
<h3>If you don't like it, fix it</h3>
<p>Does something about a project really bother you? Does the author not care as much about it as you do? Do you find yourself angrily yelling at the nice people at the bus station due to your hatred of that inefficient algorithm you found? Here is a wonderful idea: Fix it. 

</p>
<p>Developers want to improve their project. If you find an issue, bring it up. If it's a valid concern, the author will probably want to have it fixed. In many cases, the author will consider it a valid issue, but simply not have the personal time or need to address it immediately. This is where open-source is great. Just fork the project and fix it your damn self. 

</p>
<p><br>

</p>
<h3>If you fix something, let the author know</h3>
<p>Did you actually fix a known issue? Let the author know about it. Not everyone has time to adhere to the specific coding styles for a project, so if you can't do a full blown pull-request, there is NOTHING wrong with opening a pull-request that only has the intention of showing the author how you solved the problem. 

</p>
<p>On many occasions, I've opened up requests for support in the form of a Github pull request. This way, I am telling the author: I have found a potential problem with your library, here is how I fixed it for my circumstance, here is the code I used for reference. You get extra internet points if you open the pull request with: "I don't expect this pull request to get merged, but I wanted to you show you what I did".

</p>
<p><br>

</p>
<h3>Don't get upset, rejection is normal</h3>
<p>This is a follow up from the last section. Don't assume that because you opened up a pull request, that the author will accept it. There are many reasons that a maintainer might choose to not merge in your specific patch, many of which have nothing to do with you. If your patch isn't accepted, try to assume it's for a valid technical reason and not because the author hates you.

</p>
<p>If you feel there has been an oversight, it's okay to not give up. As long as you are being logical and open to other people's views, you will find that you might learn something new, or even teach something to the maintainer. 

</p>
<p><br>

</p>
<h3>If you don't like a project, don't use it</h3>
<p>You would think this is obvious, but it's not. If you don't like a project and have no inclination to fix it, just don't use it. If you feel you are being "forced" to use a project, perhaps you should re-evaluate the life decisions which brought you to this point. 

</p>
<p><br>

</p>
<h3>Conclusion</h3>
<p>There are no refunds for open-source. If you go in with the attitude that you are owed something, you will be thoroughly disappointed. On behalf of all open-source developers and project maintainers, I ask you try and be polite the next time you ask for support. Try to remember that there is a real human being on the other side of the screen, and they actually want to help you.

</p>
]]></description><link>http://blog.nodejitsu.com/getting-refunds-on-open-source-projects</link><guid isPermaLink="true">http://blog.nodejitsu.com/getting-refunds-on-open-source-projects</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Wed, 10 Aug 2011 23:30:00 GMT</pubDate></item><item><title><![CDATA[<a href="./node-knockout-nyc">Node Knockout NYC</a>]]></title><description><![CDATA[<p>We're very happy to officially announce we will be hosting an NYC location for <a href="http://nodeknockout.com/">Node Knockout 2011</a> at <a href="http://www.generalassemb.ly/">General Assembly</a> (<a href="http://maps.google.com/maps?q=902+Broadway,+New+York,+NY+10010&amp;hl=en&amp;sll=37.0625,-95.677068&amp;sspn=44.204685,62.841797&amp;z=16">902 Broadway, 4th Floor</a>) in Union Square. For those that don't know, Node Knockout is a 48-hour, team coding contest featuring node.js. There will be beverages and snacks on hand as well as team Nodejitsu and a few other tech startups to help you out in the usage of their APIs and tools.

</p>
<h2> </h2>
<p><strong>Need to get up to speed on Node? No problem. Free Training</strong><br>In the run up to Knockout, we are also going to be teaching two <strong><em>free</em></strong> training sessions on <a href="http://nodejitsutrainingaug20.eventbrite.com">Saturday, Aug 20th</a> and <a href="http://nodejitsutrainingaug21.eventbrite.com">Sunday, Aug 21st</a>. Our friends at Pivotal Labs NYC have been kind enough to provide space for these events. 

</p>
<p><strong>Not on a Node Knockout team? Also no problem.</strong><br>Even if you don't have a team to compete with, sign up and show up. There will certainly be adhoc teams developing on the scene. Bottom line, you don't have to bring a party to enjoy the party. 

</p>
<p><strong>Thanks to all of those that made this possible!</strong><br>We would like to thank all of those who are supporting our efforts in New York including 10gen, Amazon, Done, Foursquare, Mashery, Rackspace and others.

</p>
<p><strong>Schedule</strong><br><em>Friday, Aug 26th</em><br> <em> 6pm-7pm: Nodejitsu / General Assembly Happy Hour  
 </em> 7pm-8pm: Welcome Presentations<br> <em> 8pm-1am: Game on! Let the coding begin.  
</em>Saturday, Aug 27th<em>  
 </em> 9am-1am: Doors at General Assembly are open!<br><em>Sunday, Aug 28th</em><br> <em> 7pm-9pm: Optional demos, first come, first serve  
 </em> 9am-8pm: Last sprint for finishing up projects.  
</p>
]]></description><link>http://blog.nodejitsu.com/node-knockout-nyc</link><guid isPermaLink="true">http://blog.nodejitsu.com/node-knockout-nyc</guid><dc:creator><![CDATA[Saadiq Rodgers-King]]></dc:creator><pubDate>Wed, 10 Aug 2011 21:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./the-nodejs-philosophy">The Node.js Philosophy</a>]]></title><description><![CDATA[<p><em>This is Part one of a four part series leading up to <a href="http://nodejs.org">Node Knockout</a></em>

</p>
<p>The distillation of a philosophy to coding in a particular language (or environment) takes time, trial and error, and above all a group of extremely talented and dedicated professionals. Most of the ideas central to this philosophy are not new to the practice of Software Engineering or the study of Computer Science, but merely the selection of choices that appear often in the community with motivation from choices made in node.js core. With best efforts, sources and references will be supplied to support the arguments made here.

</p>
<p>You first may ask "has there been enough time?" <a href="http://nodejs.org">Node.js</a> is still very much in its infancy as put so eloquently by Isaac Schlueter (author of <a href="http://npmjs.org">npm</a>) earlier this year at <a href="http://nodeconf.org">NodeConf</a>. That is, Node.js has barely been around for <em>two years</em>. It may be therefore premature to write this, but there has the immense growth seen in both node.js core and in the ecosystem surrounding it. Nodejitsu has been intimately involved in this growth and thus, in the opinion of the author, enough time has passed for a few granules of truth to trickle through. 
<br><br>

</p>
<h2> </h2>
<p>There surely has been a large amount of trial and error: as of writing this article there are over different 3200 modules on <a href="http://npmjs.org">npm</a> (the <a href="http://npmjs.org">node package manager</a>) many of which are failed attempts at one problem or another. And last but not least there is of course an immensely talented group of professionals working both on node.js code itself and on important modules which grow the node.js ecosystem. 

</p>
<p>Looking back over the evolution of the past two years, there is truly one central tenet to the development of node.js core set out by Ryan Dahl (the creator of <a href="http://nodejs.org">node.js</a>) that has defined the <a href="http://nodejs.org">node.js</a> philosophy this article is attempting to capture. That is, <strong><a href="http://nodejs.org">node.js</a> core should be kept as small as possible.</strong> This is very clear on both the <a href="http://groups.google.com/nodejs">node.js</a> and <a href="http://groups.google.com/nodejs-dev">node.js development</a> mailing lists where frequently feature additions are not included because they simply "do not belong in core." 

</p>
<p>The focus on a very small, performant, cross-platform compatible core was the impetus for the vast number of modules available through <a href="http://npmjs.org">npm</a> today. This is because many commonly requested features:

</p>
<ul>
<li>"Framework": templating, routing, cookies, etc.</li>
<li>Asynchronous flow control</li>
<li>Pluggable Middlewares</li>
</ul>
<p>were not available in node.js core. The need for these features from developers eager to use node.js allowed talented and prolific module authors to emerge and fill the void. This continually expanding and changing ecosystem of modules is in many ways the defining factor around the node.js philosophy: <strong>experimentation with small kernels of functionality which rely on loosely coupled components.</strong>

</p>
<p><br>
</p>
<h1>Experimentation</h1>
<p>We are no strangers to <a href="http://blog.nodejitsu.com/mad-science-at-nodejitsu">mad science at Nodejitsu</a>, but at it's core why is experimentation so core to the node.js community? With no large existing codebase to solve common web application development problems combined with Javascripts minimalistic language design many modules emerged to solve the <em>same problem(s).</em> Revisiting established problems caused many developers to ask "are the accepted approaches to solving the problem at hand necessarily the best?" This focus on experimentation has shown clear benefits: <a href="http://socket.io">socket.io</a>, <a href="http://github.com/substack/dnode">dnode</a>, <a href="http://blog.nodejs.org/2011/05/01/npm-1-0-released/">the recent redesign of npm</a> are some clear examples. I think it was put best by <a href="http://github.com/mikeal">Mikeal Rogers</a> (organizer of <a href="http://nodeconf.org">NodeConf</a>): "if you think node.js needs less modules you're $%#@!^$ crazy." 

</p>
<p><br>
</p>
<h1>Small kernels of Functionality</h1>
<p>One of the benefits of having a well established package manager like <a href="http://npmjs.org">npm</a> (especially now that <a href="http://blog.nodejs.org/2011/05/01/npm-1-0-released/">it is not possible to have version conflicts in node.js modules</a>), is that a module developer can really focus on developing the best tool for an individual task. In other words, why package two modules together if you can simply break them apart into two kernels of functionality which are codependent? <strong>Exactly.</strong> There is no reason to do this unless your source code distribution (e.g. package manager) is deficient in someway. 

</p>
<p>Another way to think about this is to consider a phrase that I use often to describe node.js core: "close to the metal." For example, there are not a lot of abstractions or conventions between the developer and the raw HTTP stream. Each step along the way is a small kernel of functionality (the <code>net</code> module, the <code>http</code> module, etc.). This low-level functionality clearly has impacted the approach of the community at large.

</p>
<p><br>
</p>
<h1>Loosely coupled components</h1>
<p><a href="http://en.wikipedia.org/wiki/Coupling_%28computer_programming%29">Coupling</a> is poison to large codebases. It allows developers to hide improperly thought out abstractions and bad APIs by strictly defining and limiting the consumer to a fixed surface area. The idea of "loosely coupling" your components is that you can easily switch one out for another. This is something that was borrowed by Rails from Merb when they merged into Rails 3.0 and something that I am very glad is engrained into the approach taken by node.js developers. Early experiments on tight coupling such as <a href="http://github.com/senchalabs/connect">Connect</a> have not been repeated in other approaches and (in the case of <a href="http://github.com/senchalabs/connect">Connect</a>) considered "harmful" by their original authors; in this case <a href="http://github.com/creationix/stack">Tim Caswell</a>.

</p>
<p>The argument in favor of loosely coupled components becoming the de-facto standard in node.js is (again) precipitated by npm. Without a strong, easy-to-use package manager with well defined semantics, module authors would be incentivized against decoupling components and releasing them separately.  

</p>
<p><br>
</p>
<h1>The Road Ahead</h1>
<p>Node.js is still not yet 1.0, yet it would be surprising for the core tenets of the philosophy to change. It is a philosophy that has led to important early-stage design choices within node.js, npm, and high-profile modules that continue to make node.js the technology to watch. It is this philosophy that results in the <a href="http://search.npmjs.org">vibrant ecosystem</a>, <a href="https://github.com/hookio/hook.io">continued flow</a> of <a href="https://github.com/dominictarr/testbed">interesting projects</a> and <a href="https://github.com/substack/node-burrito">modules</a>, and <a href="https://github.com/joyent/node/pull/1457">intelligent debate</a> <a href="https://github.com/joyent/node/pull/1412">around core functionality</a>

</p>
<p><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/the-nodejs-philosophy</link><guid isPermaLink="true">http://blog.nodejitsu.com/the-nodejs-philosophy</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Tue, 09 Aug 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./six-nodejs-cli-apps">More Than Web: Six Node.js CLI Apps</a>]]></title><description><![CDATA[<p>Node.js is best known, of course, as a tool for building and serving awesome webapps. After all, that's what Nodejitsu is all about!

</p>
<p>However, if you talk to Node.JS users you may hear something along the lines of, "Javascript is actually pretty nice for writing command line apps." As it turns out, node.js is a great platform for writing command line applications, and with <a href="http://npmjs.org">npm</a> they are as easy to install---nay, easier---than similar programs written in ruby or python and installed with rubygems or pip. In addition, node.js has all sorts of helpful libraries for writing command line apps, such as <a href="https://github.com/nodejitsu/node-prompt/">prompt</a>,
<a href="https://github.com/substack/node-optimist/">optimist</a>, and <a href="https://github.com/nodejitsu/cliff/">cliff</a>, that make writing command line interfaces easy!

</p>
<p>Here, I hope to showcase a few of the command line apps written in node.js. Many of them are still written with web development in mind. They are all written in javascript, and they are all used from the command line.

</p>
<p><br>
</p>
<h2> </h2>
<h1>forever</h1>
<p>Forever, written by Nodejitsu's Charlie Robbins, is a <a href="http://en.wikipedia.org/wiki/Process_Supervision">process supervisor</a> written in node.js. More important, however, is that forever is <em>robust</em> and <em>simple to use</em>.

</p>
<p>There are <a href="http://smarden.org/runit/">many</a> <a href="http://mmonit.com/monit/">process</a> <a href="http://cr.yp.to/daemontools.html">supervision</a> <a href="http://initng.org/trac">frameworks</a> out there. The problem with a lot of them is that they're often written with system init scenarios in mind and have their own <a href="http://en.wikipedia.org/wiki/Domain_specific_language">DSLs</a>. Other times, they're not written in a particularly user-friendly manner, or they aren't very robust. Sometimes, all of these things are true. Because of this (and other problems), myself and others before me have written their own ad-hoc process supervisors, using some unholy combination of <a href="http://en.wikipedia.org/wiki/Nohup">nohup</a>,  <a href="http://en.wikipedia.org/wiki/Gnu_screen">screen</a> and/or bash.

</p>
<p>Forever is a much better solution. In fact, forever might be the <em>best</em> solution. It's certainly one of the best I've seen.

</p>
<p>For an example, suppose you're a grad student (as I was in a past life) and you have a simulation you need to run that, due to buggy software, might as well look like this:

</p>
<pre><code>#!<span class="regexp">/usr/</span>bin/env node

console.log(<span class="string">"=================Super Number Cruncher 5000================="</span>);
console.log(<span class="string">"--Running important simulations for your thesis since now!--"</span>);

<span class="keyword">var</span> i = <span class="number">0</span>;
setInterval(<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
    <span class="keyword">if</span> (Math.random() &lt; <span class="number">0.05</span>) {
        <span class="keyword">throw</span> Error(<span class="string">'FLAGRANT ERROR'</span>);
    } <span class="keyword">else</span> {
        <span class="comment">//Generate some output data</span>
        console.log((i++)+<span class="string">','</span>+(<span class="number">273.15</span>+<span class="number">60</span>*Math.random()));
    }
}, <span class="number">500</span>);</code></pre>
<p>The output of this program looks something like this:

</p>
<pre><code><span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="regexp">/broken_science_simulation$ ./simulation</span> 
==================<span class="constant">Super</span> <span class="constant">Number</span> <span class="constant">Cruncher</span> <span class="number">5000</span>==================
---<span class="constant">Running</span> <span class="identifier">important</span> <span class="identifier">simulations</span> <span class="identifier"><span class="keyword">for</span></span> <span class="identifier">your</span> <span class="identifier">thesis</span> <span class="identifier">since</span> <span class="identifier">now!</span>---
<span class="number">0</span>,<span class="number">274.32085393052546</span>
<span class="number">1</span>,<span class="number">273.85998188573865</span>
<span class="number">2</span>,<span class="number">332.435783926025</span>
<span class="number">3</span>,<span class="number">312.9851095430553</span>
<span class="number">4</span>,<span class="number">323.98653633948413</span>
<span class="number">5</span>,<span class="number">298.41442882139233</span>
<span class="number">6</span>,<span class="number">314.28931980449704</span>
<span class="number">7</span>,<span class="number">291.39460802134124</span>
<span class="number">8</span>,<span class="number">297.300358219631</span>
<span class="number">9</span>,<span class="number">309.1636345820501</span>
<span class="number">10</span>,<span class="number">281.5037131268531</span>
<span class="number">11</span>,<span class="number">292.7776571927592</span>
<span class="number">12</span>,<span class="number">332.8452686598524</span>
<span class="number">13</span>,<span class="number">275.4756304487586</span>

/<span class="identifier">home</span>/<span class="identifier">josh</span>/<span class="identifier">broken_science_simulation</span>/<span class="identifier">simulation</span><span class="symbol">:</span><span class="number">9</span>
        <span class="identifier"><span class="keymethods">throw</span></span> <span class="constant">Error</span>(<span class="string">'FLAGRANT ERROR'</span>);
              ^
<span class="constant">Error</span><span class="symbol">:</span> <span class="constant">FLAGRANT</span> <span class="constant">ERROR</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Error</span> (<span class="identifier">unknown</span> <span class="identifier">source</span>)
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Timer</span>.<span class="identifier">callback</span> (<span class="regexp">/home/josh</span><span class="regexp">/broken_science_simulation/simulation</span><span class="symbol">:</span><span class="number">9</span><span class="symbol">:</span><span class="number">15</span>)</code></pre>
<p><a href="http://www.homestarrunner.com/sbemail50.html">What? Flagrant error?</a>

</p>
<p>(Of course, given that it's academia, it's probably written in java and <a href="http://en.wikipedia.org/wiki/MATLAB">MATLAB</a> instead, but you get the idea. Also, ignore the implications of buggy science software. It's better if you don't think about it too much.)

</p>
<p>Now, supposing that we can't track down this error because it's buried inside a proprietary software suite, we can just use forever to make it restart every time it crashes:

</p>
<pre><code>josh@pidgey:~/broken_science_simulation$ forever -o output.log -e err.log simulation
warn: Forever detected script exited <span class="keyword">with</span> code: <span class="number">1</span>
warn: Forever restarting script <span class="keyword">for</span> <span class="number">1</span> time
warn: Forever detected script exited <span class="keyword">with</span> code: <span class="number">1</span>
warn: Forever restarting script <span class="keyword">for</span> <span class="number">2</span> time
warn: Forever detected script exited <span class="keyword">with</span> code: <span class="number">1</span></code></pre>
<p>This command puts your simulation's output into output.log, and the errors into err.log. As you can see, Forever restarts your process like a boss. Here's some example text from output.log:

</p>
<pre><code><span class="number">51</span>,<span class="number">275.67675554249433</span>
<span class="number">52</span>,<span class="number">323.125968520157</span>
<span class="number">53</span>,<span class="number">299.9657142587006</span>
<span class="number">54</span>,<span class="number">285.97948576379565</span>
==================Super Number Cruncher <span class="number">5000</span>==================
---Running important simulations <span class="keyword">for</span> your thesis since now!---
<span class="number">0</span>,<span class="number">317.5622826308012</span>
<span class="number">1</span>,<span class="number">311.84217803701756</span>
<span class="number">2</span>,<span class="number">330.1117456337437</span>
<span class="number">3</span>,<span class="number">331.6873355587944</span>
==================Super Number Cruncher <span class="number">5000</span>==================
---Running important simulations <span class="keyword">for</span> your thesis since now!---
<span class="number">0</span>,<span class="number">298.9083861099556</span>
<span class="number">1</span>,<span class="number">288.8923557434231</span>
<span class="number">2</span>,<span class="number">300.0416149344295</span>
<span class="number">3</span>,<span class="number">312.97375301420686</span></code></pre>
<p>and here's some example text from err.log:

</p>
<pre><code><span class="constant">Error</span><span class="symbol">:</span> <span class="constant">FLAGRANT</span> <span class="constant">ERROR</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Error</span> (<span class="identifier">unknown</span> <span class="identifier">source</span>)
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Timer</span>.<span class="identifier">callback</span> (<span class="regexp">/home/josh</span><span class="regexp">/broken_science_simulation/simulation</span><span class="symbol">:</span><span class="number">9</span><span class="symbol">:</span><span class="number">15</span>)

/<span class="identifier">home</span>/<span class="identifier">josh</span>/<span class="identifier">broken_science_simulation</span>/<span class="identifier">simulation</span><span class="symbol">:</span><span class="number">9</span>
        <span class="identifier"><span class="keymethods">throw</span></span> <span class="constant">Error</span>(<span class="string">'FLAGRANT ERROR'</span>);
              ^
<span class="constant">Error</span><span class="symbol">:</span> <span class="constant">FLAGRANT</span> <span class="constant">ERROR</span>
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Error</span> (<span class="identifier">unknown</span> <span class="identifier">source</span>)
    <span class="identifier"><span class="keymethods">at</span></span> <span class="constant">Timer</span>.<span class="identifier">callback</span> (<span class="regexp">/home/josh</span><span class="regexp">/broken_science_simulation/simulation</span><span class="symbol">:</span><span class="number">9</span><span class="symbol">:</span><span class="number">15</span>)

/<span class="identifier">home</span>/<span class="identifier">josh</span>/<span class="identifier">broken_science_simulation</span>/<span class="identifier">simulation</span><span class="symbol">:</span><span class="number">9</span>
        <span class="identifier"><span class="keymethods">throw</span></span> <span class="constant">Error</span>(<span class="string">'FLAGRANT ERROR'</span>);
              ^</code></pre>
<p>Clearly, errors are still a problem. However, with forever you can keep the bad news from your advisor. Just restart the process, and rewrite it to serialize output and start where it left off!

</p>
<ul>
<li>Author: Charlie Robbins  </li>
<li>Web site: <a href="https://github.com/indexzero/forever">https://github.com/indexzero/forever</a>  </li>
<li>Install: <code>[sudo] npm install -g forever</code>  </li>
</ul>
<p><br>
</p>
<h1>http-server</h1>
<p>http-server, written by Nodejitsu's Marak Squires, is a <em>zero-configuration</em> http-server. This means that all you have to do to serve the files in a folder is to run http-server from the command line, in that folder, without having to set <em>any</em> options. It's as easy as file serving gets!

</p>
<p>For example, here's the content of a pure client-side web page that I wrote, and normally serve using <a href="http://jesusabdullah.github.com/virtual-window/">github pages</a>:

</p>
<pre><code>josh@pidgey:~/virtual-window$ ls
favicon.ico  frame.png  index.html  jquery.js  README.md  wall.jpg  window.css</code></pre>
<p>Of course, the smart thing to do is to test the project locally before pushing changes to github. Plus, github pages is mildly annoying to work with anyway, right? With http-server, testing it from my computer is trivial:

</p>
<pre><code><span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="regexp">/virtual-window/</span><span class="variable">$ </span><span class="identifier">http</span>-<span class="identifier">server</span>
<span class="constant">Starting</span> <span class="identifier">up</span> <span class="identifier">http</span>-<span class="identifier">server</span>, <span class="identifier">serving</span> . <span class="identifier">on</span> <span class="identifier">port</span><span class="symbol">:</span> <span class="number">8080</span>
<span class="identifier">http</span>-<span class="identifier">server</span> <span class="identifier">successfully</span> <span class="identifier">started</span><span class="symbol">:</span> <span class="identifier">localhost</span><span class="symbol">:</span><span class="number">8080</span>
<span class="constant">Hit</span> <span class="constant">CTRL</span>-<span class="constant">C</span> <span class="identifier">to</span> <span class="identifier">stop</span> <span class="identifier">the</span> <span class="identifier">server</span></code></pre>
<p>Now all I have to do is go to localhost:8080, and there it is! Just like it is on github pages, without having to do any configuration at all.

</p>
<p>http-server is also nice for quickly sharing material from my shell at a moment's notice, and for (legally, mind you) sharing games at LAN parties (for those of us that have time for such things).

</p>
<ul>
<li>Author: Marak Squires   </li>
<li>Web site: <a href="https://github.com/nodejitsu/http-server/">https://github.com/nodejitsu/http-server/</a>  </li>
<li>Install: <code>[sudo] npm install -g http-server</code>  </li>
</ul>
<p><br>
</p>
<h1>browserify</h1>
<p>You <a href="https://github.com/substack/node-browserify">may</a> have <a href="http://thechangelog.com/post/8061175821/browserify-write-client-side-javascript-server-side">heard</a> of <a href="http://substack.net/posts/24ab8c/browserify-browser-side-require-for-your-node-js">browserify</a> already. Browserify began life as a node.js module for making client-side javascript more awesome by:

</p>
<ul>
<li>Giving you a node.js-compatible, commonjs-style module system for your client-side code, helping to keep everything clean and organized.  </li>
<li>Allowing you to grab node.js packages from npm and use them client-side, not only enabling simple code reuse, but also allowing one to run code intended for the server in the <em>browser</em> in a "it's so crazy it just might work" fashion. For example, the author of browserify has used it to run <a href="https://github.com/substack/node-stackedy">pure javascript stack traces</a> in the browser.  </li>
</ul>
<p>However, not all has been peachy in the world of browserify. Many people complained about having to run this "heavyweight" solution, requiring a node server to be running in order to serve these bundles instead of, say, bundling the javascript in a "build" step and serving the results with Apache. Other solutions along a similar vein, such as <a href="http://ender.no.de/">ender.js</a>, allow you to do this, so why not Browserify?

</p>
<p>Well, the author listened, and browserify recently gained a command line interface.

</p>
<p>Here's a quick example: Suppose I would like to bundle the <a href="https://github.com/substack/node-hashish">hashish</a> library for manipulating some objects on the client side, and that I would also like to include some <a href="https://github.com/kriskowal/es5-shim">es5-shim</a> action with the <a href="https://github.com/substack/node-shimify">shimify</a> browserify middleware, just in case Mom is insisting on using IE7. Here it is:

</p>
<pre><code><span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="variable">$ </span><span class="identifier">browserify</span> --<span class="identifier"><span class="keyword">require</span></span> <span class="identifier">hashish</span> --<span class="identifier">plugin</span> <span class="identifier">shimify</span> -<span class="identifier">o</span> <span class="identifier">bundle</span>.<span class="identifier">js</span></code></pre>
<p>Like that, assuming traverse and shimify are both installed, browserify bundles traverse with es5-shim into a file called <code>bundle.js</code>. Awesome!

</p>
<ul>
<li>Author: James Halliday  </li>
<li>Web site: <a href="http://github.com/substack/node-browserify/">http://github.com/substack/node-browserify/</a>  </li>
<li>Install: <code>[sudo] npm install -g browserify</code>  </li>
</ul>
<p><br>
</p>
<h1>uglifyjs</h1>
<p>Suppose you built the bundle from the browserify example, and you checked its size:

</p>
<pre><code><span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="variable">$ </span><span class="identifier">wc</span> -<span class="identifier">c</span> <span class="identifier">bundle</span>.<span class="identifier">js</span>
<span class="number">59390</span> <span class="identifier">bundle</span>.<span class="identifier">js</span></code></pre>
<p>60 kilobytes?!

</p>
<p>Okay, that's not <em>too</em> bad, but certainly we can do better, right? After all, the source from that output isn't minified or anything. For example, here's a short snippet from <code>bundle.js</code>:

</p>
<pre><code><span class="comment">// shallow copy</span>
Hash.copy = <span class="function"><span class="keyword">function</span> <span class="params">(ref)</span> {</span>
    <span class="keyword">var</span> hash = { __proto__ : ref.__proto__ };
    Object.keys(ref).forEach(<span class="function"><span class="keyword">function</span> <span class="params">(key)</span> {</span>
        hash[key] = ref[key];
    });
    <span class="keyword">return</span> hash;
};</code></pre>
<p>Goodness, that is <em>way</em> too readable!

</p>
<p>Programmatically, browserify supports many more features than it does at the command line, including using minifiers such as <a href="https://github.com/mishoo/UglifyJS">uglifyjs</a> as source filters. Uglifyjs is a high-quality, <a href="http://www.peterbe.com/plog/comparing-google-closure-with-uglifyjs">speedy</a> javascript minifier that's a favorite amongst node.js developers.

</p>
<p>Lucky for us, uglifyjs comes with a command line application! Check it out:

</p>
<pre><code><span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="variable">$ </span><span class="identifier">browserify</span> --<span class="identifier"><span class="keyword">require</span></span> <span class="identifier">hashish</span> --<span class="identifier">plugin</span> <span class="identifier">shimify</span> | <span class="identifier">uglifyjs</span> | <span class="identifier">wc</span> -<span class="identifier">c</span>
<span class="number">21243</span></code></pre>
<p>That's <em>much</em> better.

</p>
<ul>
<li>Author: Mihai Bazon  </li>
<li>Web site: <a href="https://github.com/mishoo/UglifyJS">https://github.com/mishoo/UglifyJS</a>  </li>
<li>Install: <code>[sudo] npm install -g uglify-js</code>  </li>
</ul>
<p><br>
</p>
<h1>ngist</h1>
<p>Ngist is a command line github <a href="http://gist.github.com">gist</a> tool, similar to Chris Wanstrath's <a href="https://github.com/defunkt/gist"><code>gist</code></a> from ruby. Its use is pretty similar.

</p>
<p>Here's a really simple example of its use, after the initial git configuration step:

</p>
<pre><code><span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="variable">$ </span><span class="identifier">npm</span> <span class="identifier">search</span> <span class="string">" cli "</span> &gt; <span class="regexp">/tmp/cli</span>.<span class="identifier">npm</span>.<span class="identifier">txt</span>
<span class="identifier">npm</span> <span class="identifier">info</span> <span class="identifier">it</span> <span class="identifier">worked</span> <span class="identifier"><span class="keyword">if</span></span> <span class="identifier">it</span> <span class="identifier">ends</span> <span class="identifier">with</span> <span class="identifier">ok</span>
<span class="identifier">npm</span> <span class="identifier">info</span> <span class="identifier">using</span> <span class="identifier">npm</span><span class="number">@1</span>.<span class="number">0</span>.<span class="number">18</span>
<span class="identifier">npm</span> <span class="identifier">info</span> <span class="identifier">using</span> <span class="identifier">node</span><span class="number">@v0</span>.<span class="number">4.9</span>
<span class="identifier">npm</span> <span class="identifier">info</span> <span class="identifier">ok</span>
<span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="variable">$ </span><span class="identifier">ngist</span> /<span class="identifier">tmp</span>/<span class="identifier">cli</span>.<span class="identifier">npm</span>.<span class="identifier">txt</span>
<span class="constant">Gist</span><span class="symbol">:</span> <span class="identifier">https</span><span class="symbol">:</span>/<span class="regexp">/gist.github.com/</span><span class="number">1115238</span>
<span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="variable">$ </span></code></pre>
<p>Here, I searched npm for all modules with the word "cli" in their descriptions, then used ngist to gist the output. It worked great, <a href="https://gist.github.com/1115238">as you can see for yourself</a>.

</p>
<p>Ngist can also use the contents of the clipboard, post multiple files at once (or a combination of files and clipboard contents), allow you to set the gist description, and even use someone else's github username and token. 

</p>
<p>Finally, ngist isn't only available as a command line app; you can also use it programmatically! This seems to be a common pattern in node.js cli apps, and it's one I really like.

</p>
<ul>
<li>Author: Jacob Chapel  </li>
<li>Web site: <a href="https://github.com/chapel/ngist">https://github.com/chapel/ngist</a>  </li>
<li>Install: <code>[sudo] npm install -g ngist</code>  </li>
</ul>
<p><br>
</p>
<h1>jshint</h1>
<p>jshint is a <a href="http://en.wikipedia.org/wiki/Static_program_analysis">linting tool</a> for javascript. While a fork of the more well-known <a href="http://www.jslint.com/">jslint</a>, its stated goals are to be more flexible and less opinionated than Doug Crockford's tool. The project, in addition to the web-based linter, also has a handy-dandy node-based cli tool for linting your projects!

</p>
<p>For example, I decided to run it against <a href="https://github.com/jesusabdullah/bf.js">a project of mine</a> to see what would happen:

</p>
<pre><code><span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="variable">$ </span><span class="identifier">jshint</span> <span class="identifier">bf</span>.<span class="identifier">js</span>
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">16</span>, <span class="identifier">col</span> <span class="number">22</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">21</span>, <span class="identifier">col</span> <span class="number">21</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">24</span>, <span class="identifier">col</span> <span class="number">43</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">'?'</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">28</span>, <span class="identifier">col</span> <span class="number">21</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">31</span>, <span class="identifier">col</span> <span class="number">43</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">'?'</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">35</span>, <span class="identifier">col</span> <span class="number">21</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">40</span>, <span class="identifier">col</span> <span class="number">21</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">47</span>, <span class="identifier">col</span> <span class="number">21</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">57</span>, <span class="identifier">col</span> <span class="number">21</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">82</span>, <span class="identifier">col</span> <span class="number">22</span>, <span class="constant">Unnecessary</span> <span class="identifier">semicolon</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">91</span>, <span class="identifier">col</span> <span class="number">21</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">92</span>, <span class="identifier">col</span> <span class="number">21</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">93</span>, <span class="identifier">col</span> <span class="number">19</span>, <span class="constant">Bad</span> <span class="identifier">line</span> <span class="identifier">breaking</span> <span class="identifier">before</span> <span class="string">','</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">96</span>, <span class="identifier">col</span> <span class="number">2</span>, <span class="constant">Missing</span> <span class="identifier">semicolon</span>.
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier"><span class="keymethods">test</span></span>/<span class="identifier">tests</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">8</span>, <span class="identifier">col</span> <span class="number">2</span>, <span class="constant">Missing</span> <span class="identifier">semicolon</span>.

<span class="number">15</span> <span class="identifier">errors</span>
<span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="variable">$ </span></code></pre>
<p>Oh my! It seems that jshint does not like how I break my lines or place my semicolons! Because, <a href="http://www.youtube.com/watch?v=lZLVi4v7lSM">whatever, I do what I want</a>, I'll just dump the following into <code>~/.jshintrc</code> so I can continue to write code that makes people want to stab their eyes out:

</p>
<pre><code>{
  <span class="string">"asi"</span>: <span class="literal">true</span>,
  <span class="string">"laxbreak"</span>: <span class="literal">true</span>
}</code></pre>
<p>This tells jshint to allow automatic semicolon insertion and "lax" linebreaks. Now, when I run jshint:

</p>
<pre><code><span class="identifier">josh</span><span class="variable">@pidgey</span><span class="symbol">:</span>~<span class="variable">$ </span><span class="identifier">jshint</span> <span class="identifier">bf</span>.<span class="identifier">js</span>
<span class="identifier">bf</span>.<span class="identifier">js</span>/<span class="identifier">bf</span>.<span class="identifier">js</span><span class="symbol">:</span> <span class="identifier">line</span> <span class="number">82</span>, <span class="identifier">col</span> <span class="number">22</span>, <span class="constant">Unnecessary</span> <span class="identifier">semicolon</span>.

<span class="number">1</span> <span class="identifier">error</span></code></pre>
<p>There, that's not so bad! The offending code on line 82 is <em>for</em> loop shenanigans I picked up from doing too much <a href="http://140byt.es/">code golf</a>, and I should probably rewrite it. Thanks, jshint!

</p>
<ul>
<li>Author: Brent Lintner (node package)  </li>
<li>Web site: <a href="http://github.com/jshint/node-jshint/">http://github.com/jshint/node-jshint/</a>  </li>
<li>Install: <code>[sudo] npm install -g jshint</code>  </li>
</ul>
<p><br>
</p>
<h1>Wrapping up</h1>
<p>Forever, http-server, browserify, uglify, ngist and jshint are just a few of the command line applications written in node.js and available on npm! They are easy to install, and are crazy useful. In another blog post, I will discuss how to build your own command line applications with node.js, using options parsers like <a href="https://github.com/substack/node-optimist/">optimist</a>, command line formatting tools like <a href="">colors</a> and <a href="https://github.com/nodejitsu/cliff/">cliff</a>, and <a href="https://github.com/nodejitsu/node-prompt/">prompt</a>, an easy to use module for prompting the command line for input. Stay tuned!

</p>
<p><br><br>
</p>
]]></description><link>http://blog.nodejitsu.com/six-nodejs-cli-apps</link><guid isPermaLink="true">http://blog.nodejitsu.com/six-nodejs-cli-apps</guid><dc:creator><![CDATA[Josh Holbrook]]></dc:creator><pubDate>Fri, 05 Aug 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./distribute-nodejs-apps-with-hookio">Distribute Node.js Apps with Hook.io</a>]]></title><description><![CDATA[<p><em>This is Part two of a four part series leading up to <a href="http://nodeknockout.com">Node Knockout</a></em>

</p>
<p>Nodejitsu is very happy to announce the latest stable version of <a href="https://github.com/hookio/hook.io/">hook.io</a>. This release marks a combined effort from the Nodejitsu team working across six time-zones and four countries. But what does this mean for the application developer and what is <a href="http://hook.io">hook.io</a> anyway? Hook.io is a full-featured I/O framework for node.js that enables a simple way to distribute your application across multiple node.js processes using the new <a href="https://github.com/hij1nx/EventEmitter2">EventEmitter2</a> API and leveraging the power of <a href="http://en.wikipedia.org/wiki/Crash-only_software">Crash-only software</a>. 

</p>
<p>In a nutshell, <a href="https://github.com/hookio/hook.io/">hook.io</a> allows you to split your node.js program into multiple worker processes, that will be automatically restarted upon any user-generated faults, allowing you to increase performance and fault-tolerance. Interested in learning more? Read on!
<br><br>

</p>
<h2> </h2>
<h1>Wait a second, EventEmitter2?</h1>
<p>No, you didn't read it wrong; Nodejitsu has been working on <a href="https://github.com/hij1nx/EventEmitter2">EventEmitter2</a> for the last couple of months and there has been positive feedback about bringing it into node.js core. <a href="https://github.com/hij1nx/EventEmitter2">EventEmitter2</a> is a node.js event emitter implementation with namespaces, wildcards, TTL and browser support. Even if it is not brought into node.js core, it will continued to have the full support and backing of Nodejitsu; now and forever.

</p>
<p>Lets take a look at how <a href="https://github.com/hij1nx/EventEmitter2">EventEmitter2</a> works: 

</p>
<distribute-nodejs-apps-with-hookio>

<p>If you don't pass in <code>{ wildcard: <span class="literal">true</span> }</code> when creating a new Emitter, then <a href="https://github.com/hij1nx/EventEmitter2">EventEmitter2</a> works exactly as it does now in node.js core. In addition to all the new features, <a href="https://github.com/hij1nx/EventEmitter2">EventEmitter2</a> will also work seamlessly in the browser, so it can be used in conjunction with modules like <a href="http://github.com/substack/node-browserify">browserify</a>.
<br><br>

</p>
<h1>A simple Hook.io program</h1>
<p><a href="https://github.com/hookio/hook.io/">Hook.io</a> programs in general are simple and collaborative, so don't be surprised if you end up writing very small programs that only respond to a couple of events. This is the nature of <a href="https://github.com/hookio/hook.io/">hook.io</a>, as I will discuss later in the article. So what does such a simple program look like? 

</p>
<distribute-nodejs-apps-with-hookio>

<p>Of course, this hook is a contrived example. If you're looking for some real-world examples checkout <a href="https://github.com/hookio/webhook">hook.io-webhook</a> or <a href="https://github.com/hookio/request">hook.io-request</a>. You could look at this hook as a simple heartbeat, every second this hook will emit the <code>hello</code> event with the auto-discovered hook name.

</p>
<p>Lets assume that you have created a parent hook which has spawned two instances of the <code>helloworld</code> hook. This parent hook acts as an intermediary between the two children hooks and rebroadcasts their messages to all peers. By emitting <code>hello</code> in the hook code, a <code><span class="identifier">hook</span>-<span class="identifier"><span class="keymethods">id</span></span><span class="symbol">:</span><span class="symbol">:<span class="identifier">hello</span></span></code> message is sent to the parent hook who in turn rebroadcasts it to all peers. As a result, any peer hook wishing to receive this message must listen for <code>*::hello</code>. Lets take look at a simple network diagram for this message:

</p>
<p><img src="/distribute-nodejs-apps-with-hookio/hook.io-helloworld.png">
<br><br>

</p>
<h1>The hook.io ecosystem</h1>
<p>The real power of the <a href="https://github.com/hookio/hook.io/">hook.io</a> project is that there are a ton of logic-specific hooks for you to build programs on. Just take a look at the <a href="https://github.com/hookio/">hook.io Github page</a>. Here's a quick sample of hooks:

</p>
<ul>
<li><a href="http://github.com/hookio/cron">cron</a>: Execute Hook Events as Tasks</li>
<li><a href="http://github.com/hookio/irc">irc</a>: Full IRC bindings</li>
<li><a href="http://github.com/hookio/helloworld">helloworld</a>: Emits hello event on interval</li>
<li><a href="http://github.com/hookio/logger">logger</a>: Multi-transport Logger ( Console, File, Redis, Mongo, Loggly )</li>
<li><a href="http://github.com/hookio/mailer">mailer</a>: Sends emails</li>
<li><a href="http://github.com/hookio/pinger">pinger</a>: Pings URLS on intervals ( useful for monitoring )</li>
<li><a href="http://github.com/hookio/request">request</a>: Simple wrapper for <a href="http://github.com/mikeal/request"><a href="http://github.com/mikeal/request">http://github.com/mikeal/request</a></a></li>
<li><a href="http://github.com/hookio/repl">repl</a>: Rainbow Powered REPL</li>
<li><a href="http://github.com/hookio/twilio">twilio</a>: Make calls and send SMS through <a href="http://www.twilio.com/">Twilio</a></li>
<li><a href="http://github.com/hookio/twitter">twitter</a>: Wrapper to Twitter API</li>
<li><a href="http://github.com/hookio/webhook">webhook</a>: Emits received HTTP requests as Events ( with optional JSON-RPC 1.0 Support )</li>
</ul>
<p><br><br>

</p>
<h1>Roadmap and beyond</h1>
<p><a href="https://github.com/hookio/hook.io/">Hook.io</a> is in some ways a established project and in others a young project. <a href="http://github.com/marak">Marak Squires</a> gave a <a href="http://blip.tv/jsconf/marak-squires-the-evented-web-hook-io-3900861">talk on Hook.io at JSConf 2010</a>, but most of that code has been completely rewritten for the <code>0.5.x</code> and <code>0.6.x</code> versions to take full advantage of <a href="https://github.com/hij1nx/EventEmitter2">EventEmitter2</a>, <a href="https://github.com/substack/dnode">dnode</a>, and <a href="http://github.com/indexzero/forever">Forever</a>.

</p>
<p><a href="https://github.com/hookio/hook.io/">Hook.io</a> is now deeply integrated into <a href="https://github.com/nodejitsu/haibu-carapace">haibu-carapace</a>, the event-based application host used by <a href="https://github.com/nodejitsu/haibu">haibu</a>. It is also leveraged by other important projects at Nodejitsu such as <a href="https://github.com/nodejitsu/kohai">kohai</a> and <a href="https://github.com/marak/station">station</a>. On the horizon you can look forward to more examples, tutorials, and network transports for you to build hook programs out in "hook-land". Stay tuned!
<br><br>

</p>
</distribute-nodejs-apps-with-hookio></distribute-nodejs-apps-with-hookio>]]></description><link>http://blog.nodejitsu.com/distribute-nodejs-apps-with-hookio</link><guid isPermaLink="true">http://blog.nodejitsu.com/distribute-nodejs-apps-with-hookio</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Tue, 02 Aug 2011 05:08:36 GMT</pubDate></item><item><title><![CDATA[<a href="./hiring-systems-engineer">Hiring a Systems Engineer</a>]]></title><description><![CDATA[<p>Nodejitsu is looking to hire a systems engineer with expert knowledge in Linux server administration and systems programming. At Nodejitsu, we deploy 100s of servers at a time in seconds from our node.js command line tools. We then monitor, manage, and heal these servers in real-time using...our node.js monitoring and deployment framework. We also write a lot of open-source software. see: <a href="http://github.com/nodejitsu"><a href="http://github.com/nodejitsu">http://github.com/nodejitsu</a></a>

</p>
<p><br>

</p>
<h2> </h2>
<p>Now that we've had the time to build up our infrastructure, we need you to come in and start applying the UNIX philosophy to our systems. Your role will be to "own" our servers and work with the entire team to make sure our services always stay up. We are currently expanding our platform to become a utility provider agnostic system, and we'll need your expert systems programming knowledge to help facilitate integrating with cloud computing providers ( such as: Rackspace, AWS, Joyent, etc...) and setting up redundant dedicated environments across the globe.


</p>
<p><strong>Requirements:</strong>

</p>
<ul>
<li>Expert Level Knowledge of Linux Server Administration in High Availability Production Systems</li>
<li>Expert Knowledge in Shell Scripting, C, Assembly, OSI Model, Systems / Networking Security</li>
<li>High aptitude for self-management</li>
<li>Availability to report on-site in New York City or San Francisco</li>
</ul>
<p><strong>Preferable:</strong>

</p>
<ul>
<li>Dislikes JavaScript</li>
<li>Prefers talking to our 1000s of servers instead of people</li>
<li>Has read every single BOFH story</li>
</ul>
<p><strong>Compensation</strong>

</p>
<ul>
<li>100-120k per year depending on experience</li>
<li>Equity in Nodejitsu ( vested over time )</li>
<li>Health Benefits</li>
</ul>
<p>Interested candidates can apply by emailing <a href="mailto:hiring@nodejitsu.com">hiring@nodejitsu.com</a>
</p>
]]></description><link>http://blog.nodejitsu.com/hiring-systems-engineer</link><guid isPermaLink="true">http://blog.nodejitsu.com/hiring-systems-engineer</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Wed, 27 Jul 2011 20:22:52 GMT</pubDate></item><item><title><![CDATA[<a href="./mad-science-at-nodejitsu">Mad Science at Nodejitsu</a>]]></title><description><![CDATA[<p>Hi, I'm <a href="http://github.com/dominictarr">Dominic Tarr</a>. I am a Mad Scientist from New Zealand. I live in a tree, sail around in <a href="http://www.flickr.com/photos/dominictarr/sets/72157613394576223/">a boat</a> and hack Node.js. Historically, I've only worked for ninja themed companies, and recently I have started contracting for Nodejitsu. Here at Nodejitsu, there are always a couple of Mad Science projects on the go. Normal people might call these "side projects", but Mad Scientists don't do "side projects".

</p>
<p>We do <em>Mad Science</em>. <br><br>

</p>
<h2> </h2>
<p>First there is the Science part, a Mad Science project has to be a bold idea about how some big problem might be solved. Then there is the Mad part. This is the way that once you've thought of your mad science idea, you can't forget it. It niggles away at you, and whenever you encounter your problem again you remember it, thinking, this problem could be solved with some <em>Mad Science</em>.

</p>
<p>The <em>only</em> option you have left is to try and build it.

</p>
<p>One mad science project associated with nodejitsu is Marak's <a href="http://github.com/marak/hook.io">Hook.io</a>. Hook.io is a generic implementation of "web events". Events are happening everywhere on the internet, all the time. But how do you listen to them? And what amazing applications could you build if you could easily connect all these different events together in an organized way?

</p>
<p><a href="http://github.com/marak">Marak</a> did <a href="http://blip.tv/jsconf/marak-squires-the-evented-web-hook-io-3900861">a talk</a> on hook.io at JsConf 2010. since then hook.io has been on the back burner as nodejitsu has been ramping up, but it has recently reemerged with a new approach, based on a marriage between dnode (substack's RPC protocol), <a href="http://socket.io">socket.io</a> (cross browser websocket support) and <a href="https://github.com/hij1nx/EventEmitter2">EventEmitter2</a> (another nodejitsu Mad Science project which is a reworking of node's native EventEmitter, but with proper namespaced events)

</p>
<p>I also have a mad science project, Meta-Modular. Meta-Modular is based on the idea that version numbers are wrong, and are not the way your dependencies should be specified. 
Instead, you should declare your dependencies by specifying what tests a dependency should pass. Then, in theory, any implementation of a dependency that passes the test should work in that slot. However, implementing a system like this needs not just a way to dynamically inject dependencies into a test run, but also to analyze large amounts of multi-dimentional data, to see what combinations of dependencies work with what tests.

</p>
<p>Imagine the time that could be saved if there was a service that could tell you what forks passed a particular test. And imagine what could then be done with that time, and that knowledge!

</p>
<p>As you explore a mad science idea you inevitably encounter difficulties. Success usually feels like it is a month away, and that the new approach it the one, but you never know.

</p>
<p>To illustrate this problem I like to use the example of the three parallel rivers in Yunnan province in China. In South West China the Yangtze, Mekong, and Salween rivers, three of the largest rivers in Asia, emerge from the Tibetan Plateau and flow parallel through three gorges between four mountain ranges. Suppose you are the plucky adventurer at one side of this, and you want to know whats on the other side...surely it is a lush fertile plain. So you climb the first mountain range, and what do you find? A gorge, and another mountain range. Surely the plain is on the other side of that, so you cross the river and the next mountain range. By now many members of your party have died of exposure or drowned in dangerous river crossings. You get to the top of this range...only to see another gorge, and another mountain range. This is when you start to ask yourself, just how many gorges are there?

</p>
<p>Should you give up? Or push on into the unknown?

</p>
<p>For the truly heroic adventurer, this is not even a question.

</p>
<p>So far, Marak has attacked the evented web problem three times in node.js, with two other attempts using Python's Twisted and even Coldfusion. I've tried meta-modular in Java, Ruby, and now Node.js. Currently it manifests itself as <a href="http://testbedjs.org">testbedjs.org</a> which is an <a href="https://github.com/dominictarr/testbed">open-source</a> community based continuous integration system.

</p>
<p>There are many Mad Scientists working in Node.js. Infact, Node <em>is</em> a mad science project. <a href="http://github.com/ry">Ryan</a> has been working on the idea of a <em>tinyclouds</em> framework for years. Ultimately, the idea is many lightweight asynchronous evented servers, which communicate by message passing. Before Node got popular, Ry tried out many solutions using Ruby, C, Haskell, Lua, Nginx, whatever he thought would be the best way to solve his problem. Check out some of ry's older work at <a href="http://tinyclouds.org/libebb/"><a href="http://tinyclouds.org/libebb/">http://tinyclouds.org/libebb/</a></a> and <a href="https://github.com/ry/ebb/"><a href="https://github.com/ry/ebb/">https://github.com/ry/ebb/</a></a>.

</p>
<p>It seems Ry struck gold when he switched to v8 and JavaScript, and suddenly many other mad scientists saw the potential and started working with Node.js. We see people like <a href="https://github.com/isaacs">Isaacs</a>, <a href="https://github.com/creationix/">Tim Caswell</a>, <a href="https://github.com/guille">Guillermo Rauch</a>, <a href="https://github.com/mranney">Matt Ranney</a>, <a href="https://github.com/pquerna">Paul Querna</a>, <a href="https://github.com/substack">James Halliday</a>, and <a href="https://github.com/jashkenas">Jeremy Ashkenas</a> all gravitating towards Node.

</p>
<p>Ryan's hard work and Mad Science has enabled other Mad Scientists to expand on their own visions. Just imagine what the next generation of Mad Science will yield. I predict that hook.io will make Ruby on Rails look like PHP and the concepts behind Meta-Modular will make Github style code hosting look like SourceForge.

</p>
<p>The only question now is, what is YOUR mad science project?
</p>
]]></description><link>http://blog.nodejitsu.com/mad-science-at-nodejitsu</link><guid isPermaLink="true">http://blog.nodejitsu.com/mad-science-at-nodejitsu</guid><dc:creator><![CDATA[Dominic Tarr]]></dc:creator><pubDate>Fri, 01 Jul 2011 15:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./working-at-nodejitsu">Working at Nodejitsu</a>]]></title><description><![CDATA[<p>Hey, I am Nico Reed and I work as an intern at nodejitsu. I am majoring in math with a minor in computer science at BYU. I have been hacking on several of nodejitsu's projects in the last two months and here are some of the things I have done:


</p>
<p>Right off the bat on the very first day, I got assigned to modifying the blog code. If you go to <a href="http://blog.nodejitsu.com">the blog homepage</a> and look at the very awesome RSS feed button on the right, that was my very first thing I did for nodejitsu. It took a few hours to do the very simple two line change, but in the process I learned Wheat, Haml and more about Github and I got the change pushed to production the very same day!


</p>
<p><br>
</p>
<h2> </h2>
<p>Later, I was set on bug fixing duty for <a href="https://github.com/nodejitsu/haibu">haibu</a>. Haibu can be described as the "node.js application server" at nodejitsu. Haibu's job is to spawn up the applications, make sure that they stay up, and clean up after the applications terminate. We run thousands of Haibu servers and communicate with them through simple RESTful requests. There was a bug related to an unclean exit where Haibu would get killed, but the children would never get cleaned up. <a href="http://github.com/indexzero">Charlie</a> gave me a few pointers on the relevant files and the general structure of the code and then left the rest up to me. This is where I learned about better structuring node.js programs. I came from a fairly dominate background of php as well as being a young self-taught programmer, so I was used to a very adhoc organization technique, so aside from fixing an important production issue, I also got to see and work on properly structured code.

</p>
<p>At nodejitsu, through the <a href="http://handbook.nodejitsu.com">database api</a>, users are able to provision various no-sql databases from places like RedisToGo, CouchIris, and MongoHQ. Originally there were three code bases to provision a database from each of these services. However, my task was to integrate these three code bases together into one library that abstracted away the different libraries. After the refactor, I implemented the library in the core stack, so it could be accessible through the api interface. This allowed me to allow jitsu to interface with these providers to easily provision and deprovision databases. In case you have not heard of it, <a href="https://github.com/nodejitsu/jitsu">Jitsu</a> is the command line tool to manage your apps on the nodejitsu cloud. It also has well written code that uses several tricks ( and CLI libraries like: <a href="https://github.com/nodejitsu/node-prompt">prompt</a>, <a href="http://github.com/nodejitsu/cliff">cliff</a>, <a href="http://github.com/indexzero/nconf">nconf</a>, <a href="http://github.com/marak/colors.js">colors</a>, <a href="https://github.com/substack/node-optimist">optimist</a> ) to make writing new commands super easy. These changes are currently in the pipeline, so sometime soon, you will see the database service exposed to you and hopefully it will be fully functional!  

</p>
<p>Another large task I've been working on is integrating the <a href="http://mailchimp.com">MailChimp</a> api into the entire nodejitsu stack and API. During my first week, I got assigned to working with the MailChimp API to provide methods for users to do basic subscribing and unsubscribing of emails. Later, I got assigned to integrating the api I had just created into <a href="http://develop.nodejitsu.com">develop.nodejitsu.com</a>. This was quite a bit of work which involved managing the MailChimp keys, learning the client-side code which used <a href="https://github.com/hij1nx/Porter.git">Porter</a> and <a href="https://github.com/hij1nx/SugarSkull">SugarSkull</a>, and getting all the errors to propagate correctly to the user. This project will have a few more tricks up its sleeve, but already, you can see the fully functional implementation at develop.nodejitsu.com under the addons tabs.

</p>
<p>More recently, I got placed in charge of managing the open-source project <a href="https://github.com/nodejitsu/cliff">cliff</a>. The primary enhancement I made was to the documentation. I gave many examples of how to use each of the functions and showed you the output in full color detail. I also changed how the length of a string was being calculated, so now you can use the console escape codes to <a href="http://github.com/marak/colors.js/">color</a> your output and the padding will be correctly calculated. Go ahead and check it out: <a href="https://github.com/nodejitsu/cliff">cliff</a>

</p>
<p>Aside from all these projects, I've also been working with a few people at nodejitsu on a new community geared project which has not yet been released. There has been quite a bit of effort put into it and hopefully this new project will be really helpful to the node community!


</p>
]]></description><link>http://blog.nodejitsu.com/working-at-nodejitsu</link><guid isPermaLink="true">http://blog.nodejitsu.com/working-at-nodejitsu</guid><dc:creator><![CDATA[Nico Reed]]></dc:creator><pubDate>Fri, 24 Jun 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./http-server">http-server, a command-line http server</a>]]></title><description><![CDATA[<p><code>http-server</code> is a simple, zero-configuration command-line http server.  It is powerful enough for production usage, but it's simple and hackable enough to be used for testing, local development, and learning.

</p>
<p><br>


</p>
<h2>Installation:</h2>
<p>Installation is via <code>npm</code>.  If you don't have <code>npm</code> yet:

</p>
<pre><code> curl http:<span class="comment">//n</span>pmjs.org/install.sh | sh</code></pre>
<p>Once you have <code>npm</code>:

</p>
<pre><code> npm install http-server -g</code></pre>
<p>This will install <code>http-server</code> globally so that it may be run from the command line.

</p>
<h2>Usage:</h2>
<pre><code> http-server [path] [options]</code></pre>
<p><img src="https://github.com/nodeapps/http-server/raw/master/screenshots/start.png">

</p>
<p>The entire /mypath tree will now be available at <code>http:<span class="comment">//l</span>ocalhost:<span class="number">8080</span>/</code>.  

</p>
<p><img src="https://github.com/nodeapps/http-server/raw/master/screenshots/directory.png">

</p>
<h2>Available Options:</h2>
<p><code>-p</code> Port to listen for connections on (defaults to 8080)

</p>
<p><code>-a</code> Address to bind to (defaults to 'localhost')

</p>
<p><code>-i</code> Display AutoIndex (defaults to 'True')

</p>
<p><code>-s</code> or <code>--silent</code> In silent mode, log messages aren't logged to the console.

</p>
<p><code>-h</code> or <code>--help</code> Displays a list of commands and exits.


</p>
<p><em>Now let's get hacking!</em>
</p>
]]></description><link>http://blog.nodejitsu.com/http-server</link><guid isPermaLink="true">http://blog.nodejitsu.com/http-server</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Thu, 16 Jun 2011 19:55:35 GMT</pubDate></item><item><title><![CDATA[<a href="./http-proxy-intro">Proxying HTTP and Websockets in Node </a>]]></title><description><![CDATA[<p>Here at Nodejitsu, we believe strongly in supporting the thriving open-source community around us, and one of our more popular open-source tools is <a href="http://github.com/nodejitsu/node-http-proxy">node-http-proxy</a>. It is full-featured, robust, and extremely easy to use - not to mention battle-hardened by <strong>ongoing production use</strong> at <a href="http://nodejitsu.com">nodejitsu.com</a>.  The request that loaded this page, for example, was routed to our blog by <code>http-proxy</code>.

</p>
<p>This guide is geared toward beginners and people who are unfamiliar with reverse HTTP proxying, websocket proxing, load balancing, virtual host configuration, request forwarding, and other web proxying concepts - those who already know what they're doing and just want to see the syntax should <a href="/http-proxy-intro#sampleCode">skip down to the sample code.</a>  

</p>
<p><br>



</p>
<h2>When should I use http-proxy?</h2>
<p>Let's go over a very basic use case: you have one server, but you have more than one application hosted, each of which needs to handle requests for a specific domain.

</p>
<p>The solution is to set up a proxy that listens for connections on one public port (i.e. 80), and then proxies the requests it receives to the proper application (each on its own non-public port) based on the hostname in each request.



</p>
<h2>But that sounds complicated!</h2>
<p>Not for you it isn't!  The <code>http-proxy</code> API is extremely simple, and you'll be proxying requests in no time at all.  First, though, you'll need to install <code>http-proxy</code>.  The recommended installation method is via <code>npm</code>.
If you don't have npm yet:

</p>
<pre><code> curl http:<span class="comment">//n</span>pmjs.org/install.sh | sh</code></pre>
<p>Once npm is installed (or if you have it already) the simplest installation is as follows:

</p>
<pre><code> cd myapp
 npm install http-proxy</code></pre>
<p><a name="sampleCode"></a>

</p>
<p>This will install <code>http-proxy</code> to <code>myapp/node_modules/http-proxy</code> - once that's done, it's time to write some code!  Let's look at the simplest kind of proxy first:


</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> http = require(<span class="string">'http'</span>),
    httpProxy = require(<span class="string">'http-proxy'</span>);
<span class="comment">//</span>
<span class="comment">// Create a basic proxy server in one line of code...</span>
<span class="comment">//</span>
<span class="comment">// This listens on port 8000 for incoming HTTP requests </span>
<span class="comment">// and proxies them to port 9000</span>
httpProxy.createServer(<span class="number">9000</span>, <span class="string">'localhost'</span>).listen(<span class="number">8000</span>);

<span class="comment">//</span>
<span class="comment">// ...and a simple http server to show us our request back.</span>
<span class="comment">//</span>
http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res)</span> {</span>
  res.writeHead(<span class="number">200</span>, { <span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span> });
  res.write(<span class="string">'request successfully proxied!'</span> + <span class="string">'\n'</span> + JSON.stringify(req.headers, <span class="literal">true</span>, <span class="number">2</span>));
  res.end();
}).listen(<span class="number">9000</span>);</code></pre></div></p>
<h2>Wait... really?  Just one line of code?</h2>
<p>Yes, really: one line of code to send all the requests that hit <code>localhost:9000</code> to the waiting http server at <code>localhost:8000</code>, without requiring you to expose <code>localhost:8000</code> directly.

</p>
<p>This doesn't solve our problem, though: this code will proxy all the requests to the same place, rather than routing them by hostname.  Don't worry: adding the extra functionality we need will be easy.

</p>
<p><div class="snippet"><pre><code>var http = require('http'),
    httpProxy = require('http-proxy');

<span class="comment">//</span>
<span class="comment">// </span>Just <span class="keyword">set</span> up your options...
<span class="comment">//</span>
var options = {
  hostnameOnly: <span class="literal">true</span>,
  router: {
    'domainone.com': '<span class="number">127.0</span>.<span class="number">0.1</span>:<span class="number">9000</span>',
    'domaintwo.net': '<span class="number">127.0</span>.<span class="number">0.1</span>:<span class="number">9001</span>',
    'domainthree.org': '<span class="number">127.0</span>.<span class="number">0.1</span>:<span class="number">9002</span>'
  }
}

<span class="comment">//</span>
<span class="comment">// </span>...and <span class="keyword">then</span> pass them <span class="keyword">in</span> when you create your proxy.
<span class="comment">//</span>
var proxyServer = httpProxy.createServer(options).listen(<span class="number">80</span>);
</code></pre></div></p>
<p>That's all the code you need to route to different ports/apps based on domain.  It's also possible to leave out the <code>hostnameOnly</code> option and route based on path as well:

</p>
<p><div class="snippet"><pre><code>var http = require('http'),
    httpProxy = require('http-proxy');

<span class="comment">//</span>
<span class="comment">//L</span>eave out the hostnameOnly field this time, or <span class="keyword">set</span> it to <span class="literal">false</span>...
<span class="comment">//</span>
var options = {
  router: {
    'domainone.com/appone': '<span class="number">127.0</span>.<span class="number">0.1</span>:<span class="number">9000</span>',
    'domainone.com/apptwo': '<span class="number">127.0</span>.<span class="number">0.1</span>:<span class="number">9001</span>',
    'domaintwo.net/differentapp': '<span class="number">127.0</span>.<span class="number">0.1</span>:<span class="number">9002</span>'
  }
}


<span class="comment">//</span>
<span class="comment">//.</span>..and <span class="keyword">then</span> pass <span class="keyword">in</span> your options like last time.
<span class="comment">//</span>
var proxyServer = httpProxy.createServer(options).listen(<span class="number">80</span>);
</code></pre></div></p>
<p>That's it!  It's really that easy.  Set up your options, and you're only one line of code away from a battle-hardened, production-proven reverse HTTP proxy.  

</p>
<h2>But what if I want to set up custom proxying logic?</h2>
<p>No problem - <code>http-proxy</code> still has your back.  

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> http = require(<span class="string">'http'</span>),
    httpProxy = require(<span class="string">'http-proxy'</span>);

<span class="comment">//</span>
<span class="comment">// Create a proxy server with custom application logic</span>
<span class="comment">//</span>
httpProxy.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res, proxy)</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// Put your custom server logic here</span>
  <span class="comment">//</span>
  
  <span class="keyword">if</span> (req.url.match(<span class="regexp">/apples/</span>)) {
    req.url = req.url.replace(<span class="regexp">/apples/</span>, <span class="string">'pears'</span>);
  }

  proxy.proxyRequest(req, res, {
    host: <span class="string">'localhost'</span>,
    port: <span class="number">9000</span>
  });
}).listen(<span class="number">8000</span>);

http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res)</span> {</span>
  res.writeHead(<span class="number">200</span>, { <span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span> });
  res.write(<span class="string">'request successfully proxied: '</span> + req.url +<span class="string">'\n'</span> + JSON.stringify(req.headers, <span class="literal">true</span>, <span class="number">2</span>));
  res.end();
}).listen(<span class="number">9000</span>);</code></pre></div></p>
<h2>That example was a little contrived, wasn't it?</h2>
<p>Fine, smarty-pants - how's a <strong>round-robin load-balancing strategy</strong> for you?

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> httpProxy = require(<span class="string">'http-proxy'</span>);
<span class="comment">//</span>
<span class="comment">// A simple round-robin load balancing strategy.</span>
<span class="comment">// </span>
<span class="comment">// First, list the servers you want to use in your rotation.</span>
<span class="comment">//</span>
<span class="keyword">var</span> addresses = [
  {
    host: <span class="string">'ws1.0.0.0'</span>,
    port: <span class="number">80</span>
  },
  {
    host: <span class="string">'ws2.0.0.0'</span>,
    port: <span class="number">80</span>
  }
];

httpProxy.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res, proxy)</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// On each request, get the first location from the list...</span>
  <span class="comment">//</span>
  <span class="keyword">var</span> target = addresses.shift();

  <span class="comment">//</span>
  <span class="comment">// ...then proxy to the server whose 'turn' it is...</span>
  <span class="comment">//</span>
  proxy.proxyRequest(req, res, target);

  <span class="comment">//</span>
  <span class="comment">// ...and then the server you just used becomes the last item in the list.</span>
  <span class="comment">//</span>
  addresses.push(target);
});

<span class="comment">// Rinse; repeat; enjoy.</span></code></pre></div></p>
<h2>That was cool, but I'm still not impressed.</h2>
<p>Well how about proxying socket.io <a href="http://en.wikipedia.org/wiki/WebSockets">websockets</a>?  Something like this can help <a href="http://github.com/learnboost/socket.io">socket.io</a> to scale properly:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> sys = require(<span class="string">'sys'</span>),
    http = require(<span class="string">'http'</span>),
    colors = require(<span class="string">'colors'</span>),
    websocket = require(<span class="string">'./../vendor/websocket'</span>),
    httpProxy = require(<span class="string">'node-http-proxy'</span>);

<span class="keyword">var</span> utils = require(<span class="string">'socket.io/lib/socket.io/utils'</span>),
    io = require(<span class="string">'socket.io'</span>);

<span class="comment">//</span>
<span class="comment">// Create the target HTTP server...</span>
<span class="comment">//</span>
<span class="keyword">var</span> server = http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res)</span> {</span>
  res.writeHead(<span class="number">200</span>);
  res.end();
});
server.listen(<span class="number">8080</span>);

<span class="comment">//</span>
<span class="comment">// ...now setup socket.io on the target HTTP server to handle websocket requests...</span>
<span class="comment">//</span>
<span class="keyword">var</span> socket = io.listen(server);
socket.on(<span class="string">'connection'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(client)</span> {</span>
  sys.debug(<span class="string">'Got websocket connection'</span>);

  client.on(<span class="string">'message'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(msg)</span> {</span>
    sys.debug(<span class="string">'Got message from client: '</span> + msg);
  });

  socket.broadcast(<span class="string">'from server'</span>);
});

<span class="comment">//</span>
<span class="comment">// ...next, create a proxy server with node-http-proxy...</span>
<span class="comment">//</span>
<span class="keyword">var</span> proxy = httpProxy.createServer(<span class="number">8080</span>, <span class="string">'localhost'</span>);
proxy.listen(<span class="number">8081</span>);

<span class="comment">//</span>
<span class="comment">// ...and setup the web socket to wait for connections from our proxy.</span>
<span class="comment">//</span>
<span class="keyword">var</span> ws = <span class="keyword">new</span> websocket.WebSocket(<span class="string">'ws://localhost:8081/socket.io/websocket/'</span>, <span class="string">'borf'</span>);

ws.on(<span class="string">'open'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  ws.send(utils.encode(<span class="string">'from client'</span>));
});

ws.on(<span class="string">'message'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(msg)</span> {</span>
  sys.debug(<span class="string">'Got message: '</span> + utils.decode(msg));
});
 
</code></pre></div></p>
<p>For further information on <code>http-proxy</code>, please visit the <a href="http://github.com/nodejitsu/node-http-proxy">node-http-proxy github page.</a>


</p>
]]></description><link>http://blog.nodejitsu.com/http-proxy-intro</link><guid isPermaLink="true">http://blog.nodejitsu.com/http-proxy-intro</guid><dc:creator><![CDATA[Charlie McConnell]]></dc:creator><pubDate>Thu, 09 Jun 2011 19:55:35 GMT</pubDate></item><item><title><![CDATA[<a href="./node-mailer-redux">Node Mailer Redux</a>]]></title><description><![CDATA[<p>At NodeJitsu we know how important it is to build quality open-source software and when there is a problem with one of our projects, we want to fix it.
We also know that often the right solution involves reaching out to the community and helping contribute to other people's libraries.
When we found out there were bugs in our STMP client library, <a href="https://github.com/marak/node\_mailer">node_mailer</a>, we wanted to find what was best for both ourselves and the community.
We decided to research the current landscape for node.js mailers and try to make an informed descision.
Since our library is mostly concerned with creating an easy API for sending mail, we wanted to look at alternative solutions for a solid SMTP implementation.

</p>
<p>In this article I will discuss our approach for fixing the node_mailer library and how we actually helped fix issues in another mailer project along the way.

</p>
<h2>Libraries</h2>
<p>First we evaluated many of the modules at hand that are commonly used for mailing (funny enough, there are several modules matching <code>/<span class="identifier">node</span>[-<span class="number">_</span>]<span class="number">?m</span><span class="identifier">ailer</span>/<span class="identifier">i</span></code>).
There were various issues with each project and none of the other projects supported the full feature set we wanted for sending emails.
We had to make a hard choice: Rewrite our entire node_mailer project ( which would have taken a lot of development hours ) or abandon it ( which would leave 100s of developers without a working library ).
After further reasearch we realized there was a third option: Apply patches to another mailer project, then use this as a dependency for our mailer.
We could get the functionality we wanted with minimal work and help improve someone else's project.
We considered this approach the best, both for ourselves and for the community as a whole.

</p>
<h2>NodeMailer</h2>
<p>We ended up choosing to use <a href="http://www.nodemailer.org/">NodeMailer</a> as a dependency because it was feature rich, mature, extensible, and easy to use.
It was also recommended in this poignant <a href="https://github.com/Marak/node_mailer/issues/20/">node_mailer issue</a>.
NodeMailer is inspired by Google's <a href="http://code.google.com/intl/et-EE/appengine/docs/python/mail/">Mail Python API</a> library and has very nice documentation.
Also, NodeMailer uses a pipelined state callback letting us easily hook both before and after events while extending it.
For those of you out there who use unicode in your account info, it supported UTF-8! Amazingly, the turnaround time on tickets that were reproducible bugs was around a day.
This library was looking very good.

</p>
<p>But, there were some downsides:

</p>
<ul>
<li>NodeMailer did not support StartTLS.</li>
<li>We couldn't queue up multiple messages.</li>
</ul>
<p>So, it was decided to kick some bug ass and get those 2 issues resolved.

</p>
<p>Thanks to <a href="https://github.com/Tootallnate">TooTallNate</a>'s example floating around we were able to get <a href="https://github.com/andris9/Nodemailer/commit/ff3bb176ebe2acd78cf16c64c8dd03b0b88f83fa">StartTLS going in short order</a>.

</p>
<p>For message queueing we had to dig a bit deeper.
The SMTP logic was in both the SMTPClient and Message interfaces.
If we wanted robust queueing we would need to put it all in one place unless we wanted to spawn up entirely new clients as a queue (yikes!).
So, <a href="https://github.com/andris9/Nodemailer/commit/5b8fe88ba43e6251ecccff65992e744403abdba7">that bug too was defeated</a> handily.
For now though, that lives alone in node_mailer.
We will get that pushed out to NodeMailer once we get some design stuff ironed out.

</p>
<p>Along the way we had some minor fixes for some SMTP reply codes, a parser bug that would only occur in very edgy situations, and a whole lotta kicking ass.

</p>
<p>The new fine tuned <a href="http://github.com/marak/node_mailer">node_mailer</a> on Github is working better than ever and feels good to use.
We were able to fix the problems we had with our node_mailer library and help patch up <a href="http://github.com/andris/NodeMailer">NodeMailer</a>.
Both libraries are better now and it's a win for the node community.

</p>
<h2>Future</h2>
<p>There are still a few things to do to make this module something we can call the definitive answer to Node's emailing needs.
Hopefully, the community can work with us to get a couple more features bore into <a href="http://github.com/andris/Nodemailer">Nodemailer</a> to make it better than ever!
If you want to get started head on over to the github issues for Nodemailer, and the <a href="http://github.com/marak/node_mailer">node_mailer</a> you know and love will get them downstream.
</p>
]]></description><link>http://blog.nodejitsu.com/node-mailer-redux</link><guid isPermaLink="true">http://blog.nodejitsu.com/node-mailer-redux</guid><dc:creator><![CDATA[Bradley Meck]]></dc:creator><pubDate>Tue, 31 May 2011 14:24:35 GMT</pubDate></item><item><title><![CDATA[<a href="./package-dependencies-done-right">Package.json dependencies done right</a>]]></title><description><![CDATA[<p><strong>This is part one of a three part post on <a href="http://npmjs.org">npm</a></strong> 

</p>
<p><strong>Dependency management.</strong> Need I say more? Entire developer ecosystems live and die by how dependency management works. Ask a Ruby developer what they would do without RubyGems, or ask (most) Java developers how to get things done without Maven. Most importantly: ask a node.js developer how to get things done without <a href="http://npmjs.org">npm</a>.

</p>
<p><a href="http://npmjs.org">Npm</a> recently received a pretty serious makeover in <a href="http://blog.nodejs.org/2011/05/01/npm-1-0-released/">Version 1.0</a>. If you haven't read up on what changed between <a href="https://github.com/isaacs/npm/tree/v0.3.18">0.3.18</a> and <a href="https://github.com/isaacs/npm/tree/v1.0.6">1.0</a>, you should read <a href="http://github.com/isaacs/">Isaac Schlueter's</a> (or simply @isaacs), the author of npm, <a href="http://blog.nodejs.org/2011/05/01/npm-1-0-released/">blog post</a> now. 

</p>
<p>Npm installs modules and applications based on an interpretation of the <a href="http://wiki.commonjs.org/wiki/Packages/1.1">package.json specification</a>. The most important part of this is how it determines the which version(s) of your dependencies to download. In this article I will examine:
<br><br>

</p>
<ol>
<li>How <a href="http://npmjs.org">npm</a> works with dependencies in a package.json manifest.</li>
<li>Best practices for specifying modules and node.js dependencies.</li>
</ol>
<p><br>

</p>
<h2> </h2>
<p><strong>tldr;? Jump down to <a href="#best-practices">Best Practices</a></strong>
<br><br>

</p>
<h1>Semantic versioning in <a href="http://npmjs.org">npm</a></h1>
<p>There are two separate (but equally important) entities that must have specified versions in a  package.json manifest: modules dependencies and node version. All of these version numbers are interpreted using a slightly modified <a href="http://semver.org">semantic version</a> (or semver) specification. 

</p>
<p>What is slightly modified about it? It accepts the '-' character as a valid character in build strings. So <code>0.2.0-1</code> is valid in npm semantic versioning, but not in the official <a href="http://semver.org">semver spec</a>. Personally, I like this flavor of semver and hope that it will get pulled in up-stream.

</p>
<p>Ok, so npm uses <a href="http://semver.org">semver</a>, awesome. Now what? Lets take a look at a naive example:

</p>
<p><div class="snippet"><pre><code>{
  "name": "naive",
  "description": "A package using naive versioning",
  "author": "A confused individual &lt;iam@confused.com&gt;",
  "dependencies": {
    "express": "&gt;= 1.2.0",
    "optimist": "&gt;= 0.1.0"
  },
  "engine": "node 0.4.1"
}</code></pre></div>

</p>
<p>The versions for both the <code>dependencies</code> and <code>node</code> properties in the example above are interpreted using <a href="http://github.com/node-semver">node-semver</a>, a library created and maintained by <a href="http://github.com/isaacs/">isaacs</a> for working with semantic version strings. 

</p>
<p>Now suppose that we install the above example using npm:

</p>
<ol>
<li>The node version installed on the current system is compared against the version specified in the package.json. If the node version does not satisfy the target version, the installation fails.</li>
<li>For each dependency specified in the <code>dependencies</code> property, the highest version which satisfies the specified semantic version string is downloaded and placed into the <code>node_modules</code> folder in the target directory. If there is no version available in the npm registry which satisfies the target version, the installation fails. </li>
</ol>
<p><a name="best-practices"></a>
</p>
<h1>Dependencies: Best Practices</h1>
<p>"Best practices" is a term that is often misused and thus can be ambiguous in this context. For such reasons, it is important to make clear the goals behind this particular versioning scheme:

</p>
<ol>
<li>Strive to be forwards compatible with node.js (within reason)</li>
<li>Keep the dependencies of multiple installations of the same app cohesive</li>
<li>Reduce the surface area of potential bugs due to breaking changes</li>
</ol>
<p>Here is a sample package.json that uses the best practices we will discuss:

</p>
<p><div class="snippet"><pre><code>{
  "name": "best-practices",
  "description": "A package using versioning best-practices",
  "author": "Charlie Robbins &lt;charlie@nodejitsu.com&gt;",
  "dependencies": {
    "colors": "0.x.x",
    "express": "2.3.x",
    "optimist": "0.2.x"
  },
  "devDependencies": {
    "vows": "0.5.x"
  },
  "engine": "node &gt;= 0.4.1"
}</code></pre></div>

</p>
<p><strong>When specifying modules dependencies: use <code>1.0.x</code> syntax</strong>

</p>
<p>Until recently, I was guilty of not following this guideline: I continued to use the <code>&gt;= 0.2.0</code> syntax illustrated above in the naive.package.json example. At first glance there doesn't seem to be anything wrong with that style. You're saying "If there are changes in the future I want them." 

</p>
<p>The problem arises because <em>authors are conveying meaning in their versions</em>. Not every version will be completely backwards compatible with the particular version you were using when you wrote your application. This is conveyed in the version string:

</p>
<p><em>e.g.: 0.3.18</em>

</p>
<ul>
<li>Major Version <em>(0)</em> </li>
<li>Minor Version <em>(3)</em></li>
<li>Patch Version <em>(18)</em></li>
</ul>
<p>Changes to the major and minor parts of the version mean that changes have happened, although there is no convention to convey they are breaking. Changes to patch versions are used to express that a fix has been made and it is (usually) safe to upgrade.

</p>
<p>Conversely, when using the <code>0.2.x</code> syntax you're saying: "If there are patch changes in the future I want them, but no minor or major versions." Given the description of the meaning conveyed by each of the version components above this means you won't <strong>be tearing your hair out over breaking changes in a module you depend on</strong>.

</p>
<p><br>
<strong>When specifying node versions in <em>modules</em>: use <code>&gt;= 0.4.0</code> or <code>0.4.x | 0.5.x</code> syntax</strong>

</p>
<p>Don't write modules and publish them on <a href="http://npmjs.org">npm</a>? Skip this and jump down to <a href="#node-dependency-in-apps">specifying node versions in apps</a>. 

</p>
<p>As a module author it is your responsibility to consciously follow anything you take as a dependency and ensure that you update your module(s) accordingly. Beyond that, you must also realize that (if you're lucky) your module will be used on the <a href="http://github.com/joyent/node/tree/master">bleeding edge</a>. As such, you must accommodate these valid scenarios. <em>At the end of the day it is the choice of the user to decide on their target node version and you should not limit their choices unless you are explicitly aware of a problem in future versions of node.js core.</em>

</p>
<p><br>
<a name="node-dependency-in-apps"></a>
<strong>When specifying node versions in <em>apps</em>: use <code>0.4.x</code> or <code>0.4.0</code> syntax</strong>

</p>
<p>As with any sufficiently important problem, there are nuances to dependency management you should be aware of. One such nuance is the difference between specifying dependencies in an application vs. modules. 

</p>
<p>Module authors encounter a much wider surface area of use cases, and as such should be more liberal in the versions of node.js they accept. On the other hand, application developers typically have no upstream dependencies and should be more explicit about what version of node.js they are expecting on the target system. 

</p>
<p>For example, at <a href="http://nodejitsu.com">Nodejitsu</a> we will use the highest version of node.js which satisfies the <code>node</code> specified version. So if you use <code>0.4.x</code>, but are really expecting <code>0.4.5</code>, you should indicate this in your package.json or else you may encounter unexpected behavior.

</p>
<p><br>
<strong>Take advantage of <code>devDependencies</code></strong>

</p>
<p>The package.json specification used by <a href="http://npmjs.org">npm</a> has an additional property for separately listing dependencies which are only required for development purposes. Why separate you might ask? Besides not having to download these dependencies from the registry when running in production, <a href="http://npmjs.org">npm</a> it is required if you wish to take advantage of a couple of neat npm features such as <code><span class="identifier"><span class="keymethods">test</span></span></code>:

</p>
<pre>
  $ pwd
  /Users/Charlie/GitHub/nconf

  $ npm test
  npm info it worked if it ends with ok
  npm info using npm@1.0.6
  npm info using node@v0.4.8
  npm info pretest nconf@0.1.9
  npm info test nconf@0.1.9

  &gt; nconf@0.1.9 test /Users/Charlie/GitHub/nconf
  &gt; vows test/*-test.js --spec

  (...)
</pre>

<p>If I had not specified my test library, <code>vows</code>, in the <code>devDependencies</code> section of the package.json for <code>nconf</code> I would have received:

</p>
<pre>
  $ npm test
  npm info it worked if it ends with ok
  npm info using npm@1.0.6
  npm info using node@v0.4.8
  npm info pretest nconf@0.1.9
  npm info test nconf@0.1.9

  &gt; nconf@0.1.9 test /Users/Charlie/GitHub/nconf
  &gt; vows test/<em>-test.js --spec

  sh: vows: command not found
  npm info nconf@0.1.9 Failed to exec test script
  npm ERR! nconf@0.1.9 test: `vows test/</em>-test.js --spec<code>
  npm ERR! </code>sh "-c" "vows test/*-test.js --spec"` failed with 127
  npm ERR! 
  npm ERR! Failed at the nconf@0.1.9 test script.

  (...)
</pre>

<p><br>
</p>
<h1>Conclusion</h1>
<p>Node.js is evolving rapidly: it has been less than a month since npm 1.0 was released which <a href="http://blog.nodejs.org/2011/05/01/npm-1-0-released/">dramatically changed</a> the way in which dependencies are handled. <em><strong>More importantly:</strong></em> the modules on-top of node.js critical to building scalable web applications are evolving even faster, making the best practices outlined here that much more important if you want to cope. 

</p>
<p>As with any complex ecosystem, this is a process and these practices may change over time as the goals outlined change. We'll keep you posted at <a href="http://nodejitsu.com">Nodejitsu</a>.

</p>
<p><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/package-dependencies-done-right</link><guid isPermaLink="true">http://blog.nodejitsu.com/package-dependencies-done-right</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Tue, 24 May 2011 17:22:52 GMT</pubDate></item><item><title><![CDATA[<a href="./single-page-apps-with-nodejs">Single Page Apps with Node.js.</a>]]></title><description><![CDATA[<p>While I was at <a href="http://nodeconf.com/">nodeconf</a>, I caught some of <a href="https://github.com/HenrikJoreteg">Henrik Joreteg</a>'s b-track <a href="http://www.slideshare.net/HenrikJoreteg/node-conf-building-realtime-webapps">talk</a> which was an introduction to <strong>Single Page Apps</strong>. Node.js is a great platform for Single Page Apps because of it's real-time capabilities. This is a subject that has been obscured and confused by buzzwords and <a href="http://en.wikipedia.org/wiki/Fear,_uncertainty_and_doubt">FUD</a>. Henrik had a limited time to talk, so let's revisit this subject.

</p>
<h2> </h2>
<p><br>
</p>
<h1>The Single Page App is not hype, it's an option.</h1>
<p>First off, we need to clarify some nomenclature. Two characteristics clearly differentiate <strong>Web Sites</strong> from <strong>Web Apps</strong>. A Web Site is primarily informational, it has limited interactive behavior per page. A good example of a Web Site is eBay. Conversely, a Web App is far more interactive. It attempts to emulate or capitalize on familiar behaviors found in the applications on your desktop. An example of this might be the New York Times Web Reader <a href="http://www.nytimes.com/chrome/">App</a>

</p>
<p>A <strong>Single Page App</strong> is just a Web App, but what's unique is the anatomy. It's all in the name. Essentially, all of the markup is served up on the first request. Subsequent requests are then made to a REST API which provides JSON. Content transformations may also occur by means of a Web Socket or a remote procedure call.

</p>
<p><br>
</p>
<h1>The Advantages.</h1>
<p>Aside from the obvious gains in user experience such as not having to reload the entire page for content changes, there's a long term Return of Investment to this approach. Since your data layer is decoupled from your UI, you can easily create a native app for a mobile device and leverage your existing APIs without the sky falling on you. <a href="http://en.wikipedia.org/wiki/Black_box">Black boxes</a> are cool. It's a lot simpler to write a next-generation app against an API of data than an router full of templates. 

</p>
<p>The bottom line is that single page apps are efficient. They have a small footprint on the server, consume less bandwidth and are more conducive to a service oriented architecture.

</p>
<p><br>
</p>
<h1>The Disadvantages.</h1>
<p>What about SEO and the hash-bang shit storm I've been hearing about? This is <a href="http://en.wikipedia.org/wiki/Fear,_uncertainty_and_doubt">FUD</a>. There are certainly some radical perspectives on this subject, and usually extremists are narrow sighted. If you rely on SEO and you need your app to load without Javascript, you might not want to build a <strong>Web App</strong>. You should be building a <strong>Web Site</strong>. Advertising and promotion shouldn't drive the usability of an application.

</p>
<p>Here's some <em>art</em> to try to explain the anatomy of a <strong>Single Page App</strong>.

</p>
<p><img src="/single-page-apps-with-nodejs/SPAs.png">

</p>
<p>Single Page Apps are simple. First, serve what's needed of the html. Second, speak with APIs using Javascript. Keep in mind there may be slightly more html than usual, so it should be very well organized and commented.

</p>
<p><br>
</p>
<h1>The Tools</h1>
<p><strong>SugarSkull</strong>

</p>
<p><strong>Single Page App</strong> is a misleading inscription. We actually have a single body of markup and we want to present the user with many views. Enter SugarSkull. <a href="https://github.com/hij1nx/SugarSkull">SugarSkull</a> is a client side URL router. It's the smallest amount of glue needed for building dynamic single page applications. Not a jQuery plugin: <em>no dependencies</em>.

</p>
<p><div class="snippet"><pre><code><span class="comment">// </span>define a <span class="keyword">set</span> of artificial urls
var router = Router({

  '/dog': { <span class="comment">// </span>a regular expression that represents a part of a route
    '/angry': { <span class="comment">// </span>another potential route part
      on: [growl, freakout] <span class="comment">// </span>a list of functions to execute when that route is requested
    }
    on: bark <span class="comment">// </span>a single function to execute whent the route is requested
  },

  '/cat': {
    '/squish': {
      once: freakout <span class="comment">// </span>a function that will only get executed once after the route is requested
    }
    on: meow
  }

});</code></pre></div>

</p>
<p>You might also find that <a href="http://documentcloud.github.com/backbone/">backbone.js</a> is quite complimentary to SugarSkull with its Views and Models. Long lived data on the client means less round trips to the server, and that's one of the main goals.


</p>
<p><strong>Local Storage</strong>

</p>
<p>Persistent local storage reduces round trips. The state of the application can be complex, user preferences and other unshared data can be decentralized. There are some good hacks for dealing with shitty browsers, Google Gears for example. But since you are creating a <strong>Web App</strong> you should be mostly concerned with modern browsers. You can find out more about it here as you dive into <a href="http://diveintohtml5.org/storage.html">HTML5</a>


</p>
<p><strong>Socket.io</strong>

</p>
<p>"<a href="http://socket.io">Socket.io</a> aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms." What else can be said? This is exactly what we want for single page apps, responsive network interactions. Let's take a closer look.

</p>
<h2>On the client side</h2>
<p><div class="snippet"><pre><code><span class="comment">// Let's create a new socket and assign it to a local variable.</span>
<span class="keyword">var</span> socket = <span class="keyword">new</span> io.Socket();

<span class="comment">// Establish a connection back to the server from the browser.</span>
socket.connect();

<span class="comment">// Attach a handler to the window load event.</span>
window.onload = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  
  <span class="comment">// Attach an event to the click event of document's body.</span>
  document.body.onclick = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    
    <span class="comment">// Come up with some kind of stupid message.</span>
    <span class="keyword">var</span> message = <span class="string">'The time is now '</span> + <span class="keyword">new</span> Date();
    console.log(<span class="string">'Sending the message "'</span> + message + <span class="string">'"'</span>);
    
    <span class="comment">// Send the message to the server.</span>
    socket.send(message);
  };
};

<span class="comment">// Create a handler for when a message arrives from the server.</span>
socket.on(<span class="string">'message'</span>, <span class="function"><span class="keyword">function</span><span class="params">(message)</span> {</span> 
  <span class="comment">// When a message arrives, replace the body of the document with the message.</span>
  document.body.innerHTML = message;
});
</code></pre></div>

</p>
<h2>On the server side</h2>
<p><div class="snippet"><pre><code><span class="comment">// lets include some modules</span>
<span class="keyword">var</span> http = require(<span class="string">'http'</span>), 
    io = require(<span class="string">'socket.io'</span>),
    fs = require(<span class="string">'fs'</span>);

<span class="comment">// for the sake of this example, lets have some html to serve up.</span>
<span class="keyword">var</span> html = fs.readFileSync(<span class="string">'socketio.html'</span>).toString();

<span class="comment">// business as usual, create an http server.</span>
<span class="keyword">var</span> server = http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(request, response)</span> {</span>
  <span class="comment">// serve up the client page.</span>
  response.writeHead(<span class="number">200</span>, {<span class="string">'Content-Type'</span>: <span class="string">'text/html'</span>});
  response.end(html);
});

<span class="comment">// listen on port</span>
server.listen(<span class="number">80</span>);

<span class="comment">// attach socket.io to the server</span>
<span class="keyword">var</span> socket = io.listen(server);

<span class="comment">// set up an event that handles connections that get made to the server.</span>
<span class="comment">// the callback for this event will supply the socket as a parameter.</span>
socket.on(<span class="string">'connection'</span>, <span class="function"><span class="keyword">function</span><span class="params">(client)</span> {</span>
  <span class="comment">// on the socket we can attach events, lets respond to the client when</span>
  <span class="comment">// we recieve a message.</span>
  client.on(<span class="string">'message'</span>, <span class="function"><span class="keyword">function</span><span class="params">(message)</span> {</span>
    <span class="comment">// we can log the message on the server side.</span>
    console.log(message); 
    <span class="comment">// then send it back to the client.</span>
    client.send(<span class="string">'Thanks for telling me "'</span> + message + <span class="string">'"'</span>);
  });
});</code></pre></div>

</p>
<p>Our communication vector is short, concise and that means snappy user interfaces. Socket.io is awesome. So is <a href="http://substack.net/posts/85e1bd/DNode-Asynchronous-Remote-Method-Invocation-for-Node-js-and-the-Browser">dnode</a>. But Web sockets aren't available everywhere. Much of the web has started to uses REST. Porter is a nice little way to organize your REST communications.

</p>
<p><strong>Porter</strong>

</p>
<p><a href="http://github.com/hij1nx/porter">Porter</a> is a lightweight, resourced oriented, abstraction layer for JSON-REST. It will generate methods needed to access resources based on a JSON configuration. It will balance your code's signal to noise ratio by simplifying the communication interfaces. Applications with a lot of ajax calls can get ugly.

</p>
<p><div class="snippet"><pre><code><span class="identifier">var</span> <span class="identifier">porter</span> = <span class="constant">Porter</span>({

  <span class="regexp">//</span> <span class="identifier">define</span> <span class="identifier">a</span> <span class="identifier">resource</span> <span class="identifier">group</span>
  <span class="identifier">users</span><span class="symbol">:</span> {
    <span class="regexp">//</span> <span class="identifier">define</span> <span class="identifier">a</span> <span class="identifier">resource</span>, <span class="identifier">a</span> <span class="identifier">verb</span> <span class="identifier"><span class="keyword">and</span></span> <span class="identifier">a</span> <span class="identifier">uri</span> <span class="identifier">with</span> <span class="identifier">some</span> <span class="identifier">tokens</span> <span class="identifier"><span class="keymethods">replace</span></span>
    <span class="identifier">search</span><span class="symbol">:</span> [<span class="string">'get'</span>, <span class="string">'/api/users/:partialname'</span>],
    <span class="identifier"><span class="keymethods">update</span></span><span class="symbol">:</span> [<span class="string">'post'</span>, <span class="string">'/api/apps/:username'</span>]
  },

  <span class="identifier">apps</span><span class="symbol">:</span> {
    <span class="identifier">list</span><span class="symbol">:</span> [<span class="string">'get'</span>, <span class="string">'/api/apps/:username'</span>],
    <span class="identifier">create</span><span class="symbol">:</span> [<span class="string">'post'</span>, <span class="string">'/api/apps/:username/:appname'</span>]
  }

});

<span class="regexp">//</span> <span class="identifier">porter</span> <span class="identifier">will</span> <span class="identifier">transformt</span> <span class="identifier">the</span> <span class="identifier">above</span> <span class="identifier">defintion</span> <span class="identifier">into</span> <span class="identifier">usable</span> <span class="identifier"><span class="keymethods">methods</span></span>...
<span class="identifier">porter</span>.<span class="identifier">users</span>.<span class="identifier">search</span>(

  { <span class="identifier">partialname</span><span class="symbol">:</span> <span class="string">'bill'</span> }, <span class="regexp">//</span> <span class="identifier">supply</span> <span class="identifier">the</span> <span class="identifier">value</span> <span class="identifier">of</span> <span class="identifier">the</span> <span class="identifier">token</span> <span class="identifier">to</span> <span class="identifier"><span class="keymethods">replace</span></span> <span class="identifier"><span class="keyword">in</span></span> <span class="identifier">the</span> <span class="identifier">url</span>

  <span class="identifier">function</span>(<span class="identifier">error</span>, <span class="identifier">response</span>) {
    <span class="regexp">//</span> <span class="identifier"><span class="keyword">do</span></span> <span class="identifier">something</span>...
  }

);</code></pre></div>

</p>
<h1>Conclusion</h1>
<p>The idea is simple. Serve up a base presentation document. Manipulate it with Javascript. Get more data from the server and repeat previous step. From a performance perspective, Single Page Apps are nearly on parity with native apps (in the context of a modern browser). Nearly every operating system supports a modern browser. And with HTML, CSS and Javascript as the SDK way more people can join the party.

</p>
<p><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/single-page-apps-with-nodejs</link><guid isPermaLink="true">http://blog.nodejitsu.com/single-page-apps-with-nodejs</guid><dc:creator><![CDATA[Paolo Fragomeni]]></dc:creator><pubDate>Sun, 22 May 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./ibm-doesnt-care-about-nodejs-people">IBM doesn't care about node.js people</a>]]></title><description><![CDATA[<p>I've been working with and contributing to the node.js community since 2009. I've authored a lot of <a href="http://github.com/marak">modules</a>, I've help recruit <a href="http://github.com/indexzero">a</a> <a href="http://github.com/hij1nx">lot</a> <a href="http://www.bennadel.com/">of</a> <a href="https://github.com/indutny">good</a> <a href="https://github.com/fotoverite">people</a> into the community, and I'm fortunate enough to have regular communication with all the core members. I remember when node's <a href="http://nodejs.org/docs/v0.4.5/api/all.html#file_System">FS module</a> required three nested asynchronous calls with insane arguments to actually read or write a file. I remember having to beg people like <a href="http://github.com/ry">Ry</a>, <a href="http://github.com/isaacs">Isaacs</a>, <a href="http://github.com/polotek">Polotek</a>, <a href="http://github.com/mikeal">Mikeal</a>, binary42, inimino, <a href="http://github.com/janl">Jan</a>, and <a href="http://github.com/creationix">Tim Caswell</a> ( to name a few ) to teach me the basics. I remember when node was an obscure project with little support or documentation. Since my first days in 2009 I've done everything I can to help promote and improve the usage of node.js.

</p>
<p>For all of these reasons I list above, I become considerably disappointed when I see an article like <a href="http://www.ibm.com/developerworks/opensource/library/os-nodejs/index.html">this</a> appear on IBM Developer Networks. I can understand that node.js is still a relatively new technology ( it's not even v1.0.0 as per <a href="http://semver.org">SemVer</a> yet ), but that is no excuse for an industry leader like IBM to allow such a blatantly misleading article to appear on their site. It's not my intention to single anyone out, but it's apparent that the author of the article has a limited understanding of node.js, has performed a trivial amount of research, and most importantly has no understanding of how open-source projects work in the age of Github. 

</p>
<p>Normally if I encounted such an unresearched and misleading article on the internet I'd just ignore it. Unfortunately, I can't ignore this. IBM is a serious name that people trust. To have an article on IBM.com spreading misinformation about node.js is wrong. IBM needs to update or remove this article. In this blog post I will distill and address the main points which are "wrong" in IBM's article


</p>
<p><br>

</p>
<h2> </h2>
<h1>Not understanding open-source in the age of Github</h1>
<p>A major recurring theme I noticed in the article was a complete lack of mentioning any node.js module authors, any github repos, or anything about <a href="http://npmjs.org">npm</a> and the <a href="http://search.npmjs.org">npm module repository</a>. node.js was built on <a href="http://github.com">Github</a>. It is one of the first major open-source projects to begin it's lifecycle on Github. Anyone who has committed to node.js or created a node.js module uses Github. There are <a href="http://githits.me">numerous listings</a> and <a href="http://blog.nodejitsu.com/most-active-nodejs-users">rankings</a> of <a href="https://github.com/joyent/node/wiki/modules">node.js module</a> authors and <a href="https://github.com/search?type=Everything&amp;language=&amp;q=node.js&amp;repo=&amp;langOverride=&amp;x=0&amp;y=0&amp;start_value=1">node.js Github members</a>. There is a vibrant IRC room ( #node.js on irc.freenode.net ) with 600+ active members. There is a <a href="http://groups.google.com/group/nodejs">mailing list</a> with 100s of messages per day. I follow 500+ node.js developers on my <a href="http://github.com/marak">Github activity stream</a>. There is an incredible amount of project activity based around Github.

</p>
<p><br>

</p>
<p><img src="./ibm-doesnt-care-about-nodejs-people/yuno.png">

</p>
<p><br>


</p>
<h1>Incorrect / Confusing Terminology</h1>
<p>Early in the article I found this line explaining how node.js works internally:

</p>
<p><em>"...node solves the problem by changing how a connection is made to the server. Instead of spawning a new OS thread for each connection (and allocating the accompanying memory with it), each connection creates a process, which doesn't require the memory block to go with it."</em>

</p>
<p>The ambiguity and glossing over of the word "process" is wrong. This is bad technical writing. 

</p>
<p>I asked <a href="http://github.com/isaacs">Isaacs</a> ( author of <a href="http://npmjs.org">npm</a> ) if he could clearly explain why this is wrong and his response was:

</p>
<pre><code>[17:21] &lt;isaacs&gt; Marak: i don't even know where to start</code></pre>
<p><strong>Moving on...</strong>

</p>
<p><em>"Yes, node is a server program. However, it is definitely not like Apache or Tomcat. Those servers are stand-alone server products, ready to install and deploy applications instantly. You could be up and running with a server in a minute with these products. node is definitely not this. Apache can add a PHP module to allow developers to create dynamic web pages, and programmers using Tomcat can deploy JSPs to create dynamic web pages. node is definitely not this."</em>

</p>
<p>Ahh! This is where I start to lose it. The author doesn't understand that node is much more then just a web-server. The http server in node is a part of ONE module out of <a href="https://github.com/joyent/node/tree/master/lib">twenty-five core modules</a> and currently 2000+ <a href="http://search.npmjs.org">npm modules</a>. The <a href="http://search.npmjs.org/#/_analytics">analytics</a> on npm are a bit terrifying. We are seeing ten new packages released per day. Why did you not mention npm at all? 

</p>
<p><br>

</p>
<p><img src="./ibm-doesnt-care-about-nodejs-people/modules.png">

</p>
<p><br>


</p>
<p><strong>At the risk of having a stroke, I continue reading...</strong>

</p>
<p><em>"At this early point in node's life (currently on version 0.4.6), it is not a ready-to-run server program, where you can expect to install it, drop your files into it, and have a fully functioning web server. It still requires a non-trivial amount of work to get even the basic functionality of a web server up and running after installation is complete."</em>

</p>
<p>You can't just drop in pages and starting build node.js web apps in seconds? I disagree with this assertion. I'll explain towards the end of my post, until then let's move on to the next section in the IBM article titled "How node works", first paragraph:

</p>
<p><em>"Server-side JavaScript is a relatively new concept, one which was written about a couple of years ago here on developerWorks when discussing the Aptana Jaxer product (see Resources)."</em>


</p>
<p>Umm? <a href="http://en.wikipedia.org/wiki/Server-side_JavaScript">Server-side javascript</a> has been around since 1996. WTF does Jaxer have to do with how node.js works? 


</p>
<p><br>

</p>
<p><img src="./ibm-doesnt-care-about-nodejs-people/livewire.png">

</p>
<p><br>

</p>
<p>At this point I start to fear I might have an aneurysm. <br><br>

</p>
<h1>Asserting invalid facts as truth</h1>
<p>Enough of the nitpicking, let's jump down to the author's conclusion about what node.js is good for and bad for.


</p>
<p><strong>What does the author think node is good for?</strong>

</p>
<p>He asserts node is good for <strong>A RESTful API</strong> and a <strong>Twitter queue</strong>. These sound pretty reasonable to me. No objections here.

</p>
<p>Then he goes on to state: 

</p>
<p><em>"A company that has a large distributed website (think Facebook or Flickr), could decide to devote entire boxes to simply serving up images. node would be a good solution for this problem because the company can use it to code an easy file retriever and then handle tens of thousands of connections. node would look for the image file, return it or a 404 error, and do nothing else. This setup would allow these types of distributed websites to reduce the number of server boxes they need to serve static files such as images, .js files, and .css files."</em>


</p>
<p>Hrmmm? Last time I checked binary file support in JavaScript was not that great. I've also heard Ry talk about node's performance in regards to serving static files compared to other well-developed tools as as nginx. The conclusion is you shouldn't use node if all you need is a static file server. 


</p>
<p><strong>What does the author think node is bad for?</strong>

</p>
<p><strong>"Dynamically created pages"</strong>

</p>
<p><em>"Currently, node doesn't provide a default way to create dynamic pages. For example, when using JavaServer Pages (JSP) technology you can create an index.jsp page that contains loops in JSP snippets like &lt;% for (int i=0; i</em>

</p>
<p>Do you have any idea how node works? There are literally <a href="https://github.com/joyent/node/wiki/modules#templating">20x different node.js templating engines</a> that support pretty much every single style of markup you'd ever want. I understand you really like Apache and Tomcat, but your understanding of node is just WRONG. 

</p>
<p><em>"...Therefore, if you wanted to provide a server-side solution for this in node, you'd have to code the entire solution yourself."</em>


</p>
<p><a href="https://github.com/visionmedia/express">Express</a>? <a href="https://github.com/senchalabs/connect">Connect</a>? <a href="https://github.com/mde/geddy">Geddy</a>? <a href="https://github.com/marak/webservice.js">webservice.js</a>? I guess these projects haven't been being worked on for over a year. Someone should definitely step up and build a node.js MVC framework, I think there might only be <a href="https://github.com/joyent/node/wiki/modules#web-frameworks">30x of them available now</a>.

</p>
<p><br>

</p>
<p><img src="./ibm-doesnt-care-about-nodejs-people/framework.png">

</p>
<p><br>

</p>
<p><strong>"Relational database heavy applications"</strong>


</p>
<p><em>"node is designed to be fast, asynchronous, and non-blocking. Databases don't necessarily share these goals. They are synchronous and blocking, as calls to the database on writes and reads block until a result is generated. So, a web application that requires a lot of database calls, a lot of reads, and a lot of writes with every request would be a bad match for node, since the relational database itself would be negating many of the strengths of node. (The new NoSQL databases are a better match for node, but that's another topic entirely.)"</em>

</p>
<p><br>


</p>
<p><img src="./ibm-doesnt-care-about-nodejs-people/database.png">

</p>
<p><br>

</p>
<p>Don't make broad assertions about node on topics such as "relational database heavy applications". This is highly ambiguous and leads me to believe the author doesn't understand the finer points of application architecture and design. There are <a href="https://github.com/joyent/node/wiki/modules#database">several non-blocking implementations</a> of most SQL and NOSQL databases in node. 

</p>
<p>Why would I ever design an application in node.js that performed "lots" of database I/O on every single request? It sounds like an uninformed opinion based on experiences in a narrow field of software development. 

</p>
<p><br>

</p>
<h1>Lack of Research</h1>
<p>There is no excuse for this. If you are going to put an article up on IBM.com, you should spend more than an afternoon researching it. I didn't start blogging about node.js until I had already built a project and published it to npm. I didn't dare start blogging about the node.js ecosystem or usage until I had been with the project for almost a year. 

</p>
<p>It is irresponsible to spread incorrect information like this on such a well respected channel ( IBM developer networks ).

</p>
<p><br>

</p>
<h1>Unfair comparisons to legacy technologies</h1>
<p>I feel I've touched on this a few times already, but it should be apparent that the author has a particular bias for his favorite technologies. He compares node.js unfairly to technology which he obviously has a vested stake in. If you want to promote your own technologies, that is fine by me. Just don't spread misinformation about node.js in an effort to make your technology look better.

</p>
<p><br>


</p>
<h1>Conclusion</h1>
<p>IBM should pull the article or ask the author to rewrite it. The article is providing a dis-service to any new developers who might stumble along it as their first introduction to node.js.


</p>
<p><em>Artwork courtesey of <a href="http://memegenerator.net/"><a href="http://memegenerator.net/">http://memegenerator.net/</a></a></em>
</p>
]]></description><link>http://blog.nodejitsu.com/ibm-doesnt-care-about-nodejs-people</link><guid isPermaLink="true">http://blog.nodejitsu.com/ibm-doesnt-care-about-nodejs-people</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Thu, 12 May 2011 22:26:36 GMT</pubDate></item><item><title><![CDATA[<a href="./analyze-nodejs-dependencies-like-magic">Analyze node.js Dependencies like MAGIC</a>]]></title><description><![CDATA[<p>Dependencies are the careful balance between modularity, reuse, and ease-of-use. When working with Nodejitsu (and node.js in general) dependencies are managed through the <a href="https://github.com/isaacs/npm/blob/master/doc/json.md">package.json</a> <code>dependencies</code> property. Creating a package.json is an important step in node.js application comprehension. For more information on this checkout <a href="http://github.com/issacs/npm">npm</a> and our CLI tool <a href="http://github.com/nodejitsu/jitsu">jitsu</a>, both of which will help you understand creating package.json files.

</p>
<p>Making sure your package.json has all the right ingredients is important! Nodejitsu is happy to announce the release of a simple and elegant tool for determining and analyzing your dependencies, aptly named: <a href="http://github.com/nodejitsu/require-analyzer">require-analyzer</a>. This post will walk you through how to use the library as well as outline our <a href="http://github.com/nodejitsu/jitsu">jitsu</a> integration and upcoming <a href="http://github.com/issacs/npm">npm</a> integration.
<br><br>

</p>
<h2> </h2>
<h1>Using require-analyzer</h1>
<p>There are two distinct ways to use the <code><span class="identifier"><span class="keyword">require</span></span>-<span class="identifier">analyzer</span></code> library: from the command line or through code. The command line tool is designed to work with <code>package.json</code> files; make sure that you have created one for your project beforehand.

</p>
<p>Lets take a look at how I used <code><span class="identifier"><span class="keyword">require</span></span>-<span class="identifier">analyzer</span></code> to analyze its own dependencies:
</p>
<pre>
  $ require-analyzer
  info:  require-analyzer starting in /path/to/require-analyzer
  warn:  No dependencies found
  info:  Analyzing dependencies...
  info:  Done analyzing raw dependencies
  info:  Retrieved packages from npm
  info:  Additional dependencies found
  data:  {
  data:    async: '&gt;= 0.1.8',
  data:    findit: '&gt;= 0.0.3',
  data:    npm: '&gt;= 0.3.18'
  data:  }
  info:  Updating /path/to/require-analyzer/package.json
  info:  require-analyzer updated package.json dependencies
</pre>

<p>If you're a power user (you know who you are) don't fret: the <code><span class="identifier"><span class="keyword">require</span></span>-<span class="identifier">analyzer</span></code> API is fully available through pure node.js code. The easiest way to use <code><span class="identifier"><span class="keyword">require</span></span>-<span class="identifier">analyzer</span></code> programmatically is through the <code>.analyze()</code> method. This method will use <code><span class="identifier">fs</span>.<span class="identifier"><span class="keymethods">stat</span></span>()</code> on the path supplied and attempt one of three options:

</p>
<ol>
<li>If it is a directory that has a package.json, analyze <code><span class="identifier"><span class="keyword">require</span></span></code> statements from <code>package.main</code></li>
<li>If it is a directory with no package.json analyze every <code>.js</code> or <code>.coffee</code> file in the directory tree </li>
<li>If it is a file, then analyze <code><span class="identifier"><span class="keyword">require</span></span></code> statements from that individual file.</li>
</ol>
<p>Lets dive into a quick sample usage:

</p>
<analyze-nodejs-dependencies-like-magic>

<h1>Integration with jitsu</h1>
<p>Our primary motivation for writing <a href="http://github.com/nodejitsu/require-analyzer">require-analyzer</a> was to make deploying to <a href="http://nodejitsu.com">Nodejitsu</a> easier than ever. Our CLI tool, <a href="http://github.com/nodejitsu/jitsu">jitsu</a>, will look inside your <code>package.json</code> for the <code>scripts.start</code> property, then analyze the <code><span class="identifier"><span class="keyword">require</span></span></code> statements used by that script automagically for you before your application is even deployed to our platform. <strong>Simple. Friction-free. Awesome. Work get's done. Go home early.</strong>

</p>
<p>Here's a sample of the output:
</p>
<pre>
  info:   Analyzing your application dependencies in bin/server
  info:   Found new dependencies
  data:   {
  data:       colors: '&gt;= 0.5.0',
  data:       http-proxy: '&gt;= 0.5.0',
  data:       loggly: '&gt;= 0.3.2',
  data:       node-static: '&gt;= 0.5.3',
  data:       optimist: '&gt;= 0.1.9',
  data:       request: '&gt;= 1.9.5',
  data:       winston: '&gt;= 0.2.7'
  data:   }
  warn:   New dependencies will be added for you automatically.
</pre> 

<h1>Roadmap</h1>
<p>If you're curious how <a href="http://github.com/nodejitsu/require-analyzer">require-analyzer</a> works it's relatively straight-forward: it finds a set of files to require, then spawns a child process which monkey patches <code>Module._load()</code> in node.js core to observe your <code><span class="identifier"><span class="keyword">require</span></span>()</code> statements (<a href="https://github.com/nodejitsu/require-analyzer/blob/master/bin/find-dependencies">code anyone?</a>). <a href="http://github.com/nodejitsu/require-analyzer">require-analyzer</a> then parses that output and cross references the results with packages installed via <a href="http://github.com/issacs/npm">npm</a>.

</p>
<p>This approach is more elegant than some static analysis approaches used in <a href="https://github.com/duostack/npm-detect">other attempts at this problem</a>, but it is by no means a perfect approach. Lazy loading of dependencies or dependencies used in binary scripts are not captured by the default CLI tool. These are issues we look forward to improving upon in the coming weeks.

</p>
<p>Another important point of interest for us is the integration with <a href="http://github.com/issacs/npm">npm</a>. The name for the library actually came out of a discussion with <a href="http://blog.izs.me">isaacs</a> (author of npm; much respect), and we've come to see that there is some shared ground between <a href="http://github.com/nodejitsu/jitsu">jitsu</a> and <a href="http://github.com/issacs/npm">npm</a> (especially in the <code>npm init</code> command). 

</p>
<p><strong>Stay tuned for more big announcements leading up to and during <a href="http://nodeconf.com">NodeConf</a>.</strong>
<br><br>

</p>
</analyze-nodejs-dependencies-like-magic>]]></description><link>http://blog.nodejitsu.com/analyze-nodejs-dependencies-like-magic</link><guid isPermaLink="true">http://blog.nodejitsu.com/analyze-nodejs-dependencies-like-magic</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Mon, 25 Apr 2011 17:22:52 GMT</pubDate></item><item><title><![CDATA[<a href="./updating-node-http-proxy">Updating to node-http-proxy v0.5.0</a>]]></title><description><![CDATA[<p>Beyond all of the hype that you might be hearing about node.js these days at it's core it has always been about one thing: <em><strong>fast network programming</strong></em>. This aspect of node.js is why we created and have maintained <a href="http://github.com/nodejitsu/node-http-proxy">node-http-proxy</a> for <a href="https://github.com/nodejitsu/node-http-proxy/commit/30b68c153270619119ec36615bb54ee7a2816ecc">almost a year</a> now. The project has matured with contributions from notable members of the community and a lot of maintenance from yours truly; we have been working on this since <a href="https://github.com/joyent/node/tree/v0.1.98">node.js 0.1.98</a> afterall.

</p>
<p>This article marks the release of node-http-proxy v0.5.0 which has some breaking changes to make the API more extensible for the next <a href="https://github.com/nodejitsu/node-http-proxy/blob/master/examples/web-socket-proxy.js">WebSocket</a> and <a href="https://github.com/nodejitsu/node-http-proxy/blob/master/examples/basic-proxy-https.js">HTTPS</a> support. We'll be reviewing changes since <a href="https://github.com/nodejitsu/node-http-proxy/tree/v0.3.0">v0.3.0</a>, which is still in use in many environments. tl;dr? Checkout the <a href="https://github.com/nodejitsu/node-http-proxy/blob/master/CHANGELOG.md">Changelog for the project</a>.
<br><br>

</p>
<h2> </h2>
<h1>Who is affected?</h1>
<p>From the beginning, <a href="http://github.com/nodejitsu/node-http-proxy">node-http-proxy</a> has been designed with an extremely flexible API that allows you to use it as a stand-alone proxy server or in conjunction with another HTTP server (for example, a <a href="https://github.com/senchalabs/connect">connect server</a>). If you're using the <a href="https://github.com/nodejitsu/node-http-proxy/blob/master/examples/basic-proxy.js">stand-alone</a> proxy you have nothing to worry about, that API hasn't changed at all:

</p>
<pre>
  require('http-proxy').createServer(port, host, options).listen(8000);
</pre>

<p>APIs for other more-custom tailored use-cases have changed, so read on below. All of these code samples are also available as <a href="https://github.com/nodejitsu/node-http-proxy/tree/master/examples">examples on GitHub</a>.

</p>
<p><br>
</p>
<h1>Use http.Agent in node.js 0.3.6+</h1>
<p>We took advantage of the new http.Agent APIs introduced in node.js v0.3.6+. This allowed us to remove the "pool" module dependency because instances of http.Agent now perform socket pooling. 
<br><br>

</p>
<h1>No more eager request buffering</h1>
<p>It is no longer necessary to create an instance of HttpProxy for each incoming connection. The motivation for that design choice was that we could eagerly buffer the incoming request in-case the user decides to wait before proxying (i.e. <a href="https://github.com/nodejitsu/node-http-proxy/blob/master/examples/latent-proxy.js">latent proxying</a>). This turns out to be less than ideal for memory performance because not every scenario will require request buffering. The onus is therefore now on the user using the new <code>.buffer()</code> method:

</p>
<h2>Old (v0.3.0)</h2>
<p><div class="snippet"><pre><code><span class="keyword">var</span> http = require(<span class="string">'http'</span>),
    httpProxy = require(<span class="string">'http-proxy'</span>);
    
<span class="comment">//</span>
<span class="comment">// Create a proxy server with custom application logic</span>
<span class="comment">//</span>
httpProxy.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res, proxy)</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// Wait for two seconds then respond: this simulates</span>
  <span class="comment">// performing async actions before proxying a request</span>
  <span class="comment">//</span>
  setTimeout(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    proxy.proxyRequest(<span class="number">9000</span>, <span class="string">'localhost'</span>);      
  }, <span class="number">2000</span>);
}).listen(<span class="number">8000</span>);</code></pre></div>

</p>
<h2>New (v0.5.0)</h2>
<p><div class="snippet"><pre><code><span class="keyword">var</span> http = require(<span class="string">'http'</span>),
    httpProxy = require(<span class="string">'http-proxy'</span>);
    
<span class="comment">//</span>
<span class="comment">// Create a proxy server with custom application logic</span>
<span class="comment">//</span>
httpProxy.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res, proxy)</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// Buffer the request first</span>
  <span class="comment">//</span>
  <span class="keyword">var</span> buffer = proxy.buffer(req);
  
  <span class="comment">//</span>
  <span class="comment">// Wait for two seconds then respond: this simulates</span>
  <span class="comment">// performing async actions before proxying a request</span>
  <span class="comment">//</span>
  <span class="comment">// Note: Now we have to pass both `req` and `res` to </span>
  <span class="comment">// `.proxyRequest()`.</span>
  <span class="comment">//</span>
  setTimeout(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    proxy.proxyRequest(req, res, {
      host: <span class="string">'localhost'</span>,
      port: <span class="number">9000</span>,
      buffer: buffer
    });      
  }, <span class="number">2000</span>);
}).listen(<span class="number">8000</span>);</code></pre></div>

</p>
<p>It's also important to note in the above <code>v0.5.0</code> code sample how the arguments passed to <code>.proxyRequest()</code> have changed from a list of arguments to the following signature: <code>proxy.proxyRequest(req, res, options)</code> where options must include the <code>host</code> and <code>port</code> properties.
<br><br>

</p>
<h1>Using WebSocket Support</h1>
<p>Websockets are handled automatically when using the <code>httpProxy.createServer()</code>, but if you want to use it in conjunction with a stand-alone HTTP + WebSocket (such as <a href="http://socket.io">socket.io</a>) server here's how:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> http = require(<span class="string">'http'</span>),
    httpProxy = require(<span class="string">'http-proxy'</span>);
    
<span class="comment">//</span>
<span class="comment">// Create an instance of node-http-proxy</span>
<span class="comment">//</span>
<span class="keyword">var</span> proxy = <span class="keyword">new</span> httpProxy.HttpProxy();

<span class="keyword">var</span> server = http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res)</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// Proxy normal HTTP requests</span>
  <span class="comment">//</span>
  proxy.proxyRequest(req, res, {
    host: <span class="string">'localhost'</span>,
    port: <span class="number">8000</span>
  })
});

server.on(<span class="string">'upgrade'</span>, <span class="function"><span class="keyword">function</span><span class="params">(req, socket, head)</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// Proxy websocket requests too</span>
  <span class="comment">//</span>
  proxy.proxyWebSocketRequest(req, socket, head, {
    host: <span class="string">'localhost'</span>,
    port: <span class="number">8000</span>
  });
});</code></pre></div>

</p>
<p><br>
</p>
<h1>Proxying over HTTPS</h1>
<p>Proxying over HTTPS is a common scenarios for reverse proxies. You want your proxy server running on HTTPS while each of your target servers is running HTTP. Both HTTPS -&gt; HTTPS and HTTPS -&gt; HTTP proxying is now possible in <a href="http://github.com/nodejitsu/node-http-proxy">node-http-proxy</a> v0.5.0.

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> fs = require(<span class="string">'fs'</span>),
    https = require(<span class="string">'https'</span>),
    httpProxy = require(<span class="string">'http-proxy'</span>);
    
<span class="keyword">var</span> options = {
  https: {
    key: fs.readFileSync(<span class="string">'path/to/your/key.pem'</span>, <span class="string">'utf8'</span>),
    cert: fs.readFileSync(<span class="string">'path/to/your/cert.pem'</span>, <span class="string">'utf8'</span>)
  }
};

<span class="comment">//</span>
<span class="comment">// Create a standalone HTTPS proxy server</span>
<span class="comment">//</span>
httpProxy.createServer(<span class="number">8000</span>, <span class="string">'localhost'</span>, options).listen(<span class="number">8001</span>);

<span class="comment">//</span>
<span class="comment">// Create an instance of HttpProxy to use with another HTTPS server</span>
<span class="comment">//</span>
<span class="keyword">var</span> proxy = <span class="keyword">new</span> httpProxy.HttpProxy({ https: <span class="literal">true</span> });
https.createServer(options.https, <span class="function"><span class="keyword">function</span> <span class="params">(req, res)</span> {</span>
  proxy.proxyRequest(req, res, {
    host: <span class="string">'localhost'</span>, 
    port: <span class="number">8000</span>
  })
}).listen(<span class="number">8002</span>);

<span class="comment">//</span>
<span class="comment">// Create the target HTTPS server for both cases</span>
<span class="comment">//</span>
https.createServer(options.https, <span class="function"><span class="keyword">function</span> <span class="params">(req, res)</span> {</span>
  res.writeHead(<span class="number">200</span>, { <span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span> });
  res.write(<span class="string">'hello https\n'</span>);
    res.end();
}).listen(<span class="number">8000</span>);</code></pre></div>

</p>
<p><br>
</p>
<h1>Roadmap</h1>
<p>Clearly <a href="http://github.com/nodejitsu/node-http-proxy">node-http-proxy</a> has come a long way since v0.1.0. But where do we go from here?
<br><br>

</p>
<ol>
<li>Add Whitelist / Blacklist Support</li>
<li>Support Gzip</li>
<li>Proxy Authentication</li>
<li><a href="http://github.com/nodejitsu/node-http-proxy/issues">Add something yourself!</a></li>
</ol>
<p><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/updating-node-http-proxy</link><guid isPermaLink="true">http://blog.nodejitsu.com/updating-node-http-proxy</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Sat, 16 Apr 2011 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./javascript-trampoline-party">JavaScript Trampoline Party</a>]]></title><description><![CDATA[<p>If you have been following our blog, you might have noticed I've been posting a lot of "amazing news" entries. This entry is no exception.

</p>
<p><br>

</p>
<h1>It's a JavaScript Trampoline Party at the <a href="http://www.houseofairsf.com/">House of Air</a>!</h1>
<h1>We'll be giving out 25 free tickets!</h1>
<h1>There is also Trampoline Dodgeball!</h1>
<h1>4/28/2011 between 7pm-9pm</h1>
<p><br>


</p>
<p>Nodejitsu is sponsoring a small kick off party in San Fransisco the week before <a href="http://2011.jsconf.us/">JSConf</a> and <a href="http://nodeconf.com/">NodeConf</a>. Our team will be at both conferences and we'll sponsoring / speaking at NodeConf. We are doing <a href="http://blog.nodejitsu.com/nodejs-training-sessions">training sessions</a> before and between JsConf and NodeConf, so please be sure to sign up if you haven't' already.

</p>
<p>So back to the Trampoline Javascript Party....where is it going to be? What is the <a href="http://www.houseofairsf.com/">House of Air</a>? Who will the lucky 25 be that get to go...

</p>
<h2> </h2>
<p>The <a href="http://www.houseofairsf.com/">House of Air</a> is a trampoline park located at <a href="http://maps.google.com/maps?q=Building+926+926+%22Old%22+Mason+Street+West+Crissy+Field+The+Presidio+of+San+Francisco,+CA+94129.&amp;oe=utf-8&amp;client=firefox-a&amp;ie=UTF8&amp;hl=en&amp;hq=building+926+926+old+mason+street+west+crissy+field+the&amp;hnear=Presidio+of+San+Francisco,+San+Francisco,+California&amp;z=14">Building 926 926 "Old" Mason Street West Crissy Field The Presidio of San Francisco, CA 94129</a>. It has multiple trampoline areas, including a free-jump colosseum and an arena for non-stop five minute rounds of trampoline dodgeball. It's an amazingly fun place to go to and I've never had a bad time going there. I'd advise against eating any bacon cheeseburgers before attending the park...but perhaps I am getting a bit ahead of myself.

</p>
<p>We've got 25 tickets to give away and we'll be giving them on a first come first serve basis on the following ranked items:

</p>
<ol>
<li>If you are a Node.js Ninja</li>
<li>If you are a JavaScript Ninja</li>
<li>If you are have a Github account</li>
<li>If you are following <a href="http://github.com/Nodejitsu">Nodejitsu</a> team members on <a href="http://github.com/Nodejitsu">Github</a></li>
<li>If you have a twitter and are following <a href="http://twitter.com/nodejitsu">@Nodejitsu</a> or our team members</li>
</ol>
<p>You'll be allowed to bring guests...so let us know how many guests you intend to bring. <em>Bonus points if you are planning to bring your development team as your guests.</em>


</p>
<p>We've only got a limited amount of spots, so we won't be able to accommodate everyone... If you still want to go and don't know if you'll make the list, you can always buy a ticket directly on the House Of Air website on the the date and time of the event <a href="https://clients.mindbodyonline.com/ASP/home.asp?studioid=12728">here</a>. I can't guarantee any spots will be available outside of our block, but there should be at least a few.


</p>
<h2>If you'd like to apply please submit your github handle and desired guest count to:</h2>
<p><a href="mailto:jumparound@nodejitsu.com">jumparound@nodejitsu.com</a>


</p>
<p>After the event, we'll be moving the party to an undisclosed location nearby where we can sip on tasty drinks and eat delicious food.

</p>
<p><em>I look forward to seeing some JavaScript Ninjas in action</em>

</p>
<p>Here's a good video of the free-jump area:

</p>
<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/-9bLQXwnI3w" frameborder="0" allowfullscreen="allowfullscreen"></iframe>


<p>And here is a video of some Ninja Trampoline Dodgeball Skills

</p>
<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/l1DbEccmnoY" frameborder="0" allowfullscreen="allowfullscreen"></iframe>


]]></description><link>http://blog.nodejitsu.com/javascript-trampoline-party</link><guid isPermaLink="true">http://blog.nodejitsu.com/javascript-trampoline-party</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Thu, 14 Apr 2011 05:11:50 GMT</pubDate></item><item><title><![CDATA[<a href="./rest-easy-test-any-api-in-nodejs">RESTeasy: Test any API in node.js</a>]]></title><description><![CDATA[<p>It seems like every developer has their own (passionate) opinion about how software should be tested:

</p>
<ul>
<li><em>"I would kill myself without <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>"</em></li>
<li><em><strong>ZOMG!</strong> How could you write software without <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a>!?!</em></li>
<li><em>"Testing? Meh. I try to have <a href="http://en.wikipedia.org/wiki/Unit_testing">unit tests</a>..."</em></li>
</ul>
<p>I think more developers than not fall into the mindset of the last quote; we want to test our software but we don't have the time, or resources to make 100% test coverage a reality. The underlying fact behind this dirty secret is that testing can be quite difficult and requires the utmost dedication to flesh out completely. 

</p>
<p>This excess of verbosity and difficulty was the motivation for writing <a href="http://indexzero.github.com/api-easy">APIeasy</a>: a simple tool for writing BDD tests for <strong>any</strong> REST API. This article will explore a sample API written in node.js and how it can be tested with <a href="http://indexzero.github.com/api-easy">APIeasy</a>.
<br><br>
</p>
<h2> </h2>
<p><strong>Update:</strong> So the Internet and I were talking and it turns out there is already a library called RESTeasy. But I mean, who still uses Java anyway? In response to a request from the Internet at-large (i.e. the authors of the existing RESTeasy library) I have changed the name of this library to <a href="http://indexzero.github.com/api-easy">APIeasy</a>. 
<br><br>

</p>
<h1>Getting started</h1>
<p><a href="http://indexzero.github.com/api-easy">APIeasy</a> will let you test <strong>any</strong> API, not just APIs written in node.js. So if you're writing in PHP, Ruby, or Python and looking for a good way to get started in node, here's your answer. For the sake of this example, however, we will be writing our API in node.

</p>
<p>The following code sample creates a simple JSON-based web service using <a href="http://github.com/cloudhead/journey">journey</a> with a couple of simple routes:

</p>
<ul>
<li><code>GET  /ping:  Responds <span class="keyword">with</span> { pong: <span class="literal">true</span> }</code></li>
<li><code>POST /ping:  Responds <span class="keyword">with</span> the POST data</code> </li>
<li><code>GET  /login: Responds <span class="keyword">with</span> { token: <span class="regexp">/\d+/</span> }</code></li>
<li><code>GET  /restricted: Responds <span class="keyword">with</span> { authorized: <span class="literal">true</span> } <span class="keyword">if</span> the correct token is sent</code>
<br><br></li>
</ul>
<p><div class="snippet"><pre><code><span class="keyword">var</span> http = require(<span class="string">'http'</span>),
    journey = require(<span class="string">'journey'</span>);

<span class="comment">//</span>
<span class="comment">// Create a journey router. Not familiar with journey? Checkout:</span>
<span class="comment">// http://github.com/cloudhead/journey</span>
<span class="comment">//</span>
<span class="keyword">var</span> token, router = <span class="keyword">new</span> journey.Router({ 
  strict: <span class="literal">false</span>,
  strictUrls: <span class="literal">false</span>,
  api: <span class="string">'basic'</span>
});

<span class="comment">//</span>
<span class="comment">// Create a simple (and not production ready) function</span>
<span class="comment">// for authorization incoming requests.</span>
<span class="comment">//</span>
<span class="function"><span class="keyword">function</span> <span class="title">isAuthorized</span> <span class="params">(req, body, next)</span> {</span>
  <span class="keyword">return</span> parseInt(req.headers[<span class="string">'x-test-authorized'</span>], <span class="number">10</span>) !== token 
    ? next(<span class="keyword">new</span> journey.NotAuthorized())
    : next();
}

<span class="comment">//</span>
<span class="comment">// GET /ping: </span>
<span class="comment">//   * Responds with 200</span>
<span class="comment">//   * Responds with `{ pong: true }`</span>
<span class="comment">//</span>
router.get(<span class="string">'/ping'</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res)</span> {</span>
  res.send(<span class="number">200</span>, {}, { pong: <span class="literal">true</span> });
});

<span class="comment">//</span>
<span class="comment">// POST /ping</span>
<span class="comment">//   * Responds with 200</span>
<span class="comment">//   * Responds with the data posted</span>
<span class="comment">//</span>
router.post(<span class="string">'/ping'</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res, data)</span> {</span>
  res.send(<span class="number">200</span>, {}, data);
});

<span class="comment">//</span>
<span class="comment">// GET /login</span>
<span class="comment">//   * Responds with 200</span>
<span class="comment">//   * Responds with { token: /\d+/ }</span>
<span class="comment">//</span>
router.get(<span class="string">'/login'</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res)</span> {</span>
  <span class="keyword">if</span> (!token) {
    token = Math.floor(Math.random() * <span class="number">100</span>);
  }
  
  res.send(<span class="number">200</span>, {}, { token: token });
});

<span class="comment">//</span>
<span class="comment">// Filter requests to /restricted using isAuthorized.</span>
<span class="comment">//</span>
router.filter(isAuthorized, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// GET /restricted</span>
  <span class="comment">//   * Responds with 200</span>
  <span class="comment">//   * Responds with { authorized: true }</span>
  <span class="comment">//</span>
  <span class="keyword">this</span>.get(<span class="string">'/restricted'</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res)</span> {</span>
    res.send(<span class="number">200</span>, {}, { authorized: <span class="literal">true</span> });
  });
});

<span class="comment">//</span>
<span class="comment">// Create a simple HTTP server to </span>
<span class="comment">// consume our router.</span>
<span class="comment">//</span>
http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(request, response)</span> {</span>
  <span class="keyword">var</span> body = <span class="string">""</span>;

  request.addListener(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(chunk)</span> {</span> body += chunk });
  request.addListener(<span class="string">'end'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    <span class="comment">//</span>
    <span class="comment">// Dispatch the request to the router</span>
    <span class="comment">//</span>
    router.handle(request, body, <span class="function"><span class="keyword">function</span> <span class="params">(result)</span> {</span>
      response.writeHead(result.status, result.headers);
      response.end(result.body);
    });
  });
}).listen(<span class="number">8000</span>);
</code></pre></div>

</p>
<p><br>
</p>
<h1>Creating an APIeasy suite</h1>
<p>So what are the concerns that one might have when testing such an API taking into consideration the benefits of descriptive tests (read: BDD)?

</p>
<ol>
<li>Ensure the correct HTTP response code is returned</li>
<li>Ensure the correct response body is returned</li>
<li>Ensure that a custom assertion on the HTTP response is satisfied</li>
<li>Organize tests so that each test has a meaningful description</li>
</ol>
<p><a href="http://indexzero.github.com/api-easy">APIeasy</a> addresses all of these concerns in a simple, fluent (i.e. chainable) API. The core of this API are helper methods for making common types of HTTP request. Each of these methods will perform an HTTP request against the current path for the suite configured by calls to <code>.path()</code> or <code>.unpath()</code>. The optional parameters configure the subpath to the resource, URI paramaters, and optional request body.

</p>
<ul>
<li><code>.get(<span class="comment">/* [uri, params] */</span>)</code>: </li>
<li><code>.post(<span class="comment">/* [uri, data, params] */</span>)</code></li>
<li><code>.put(<span class="comment">/* [uri, data, params] */</span>)</code> </li>
<li><code>.del(<span class="comment">/* [uri, data, params] */</span>)</code></li>
<li><code>.head(<span class="comment">/* [uri, params] */</span>)</code>. </li>
</ul>
<p>After a call to one of these methods has been made the user can add tests for this particular request by using <code>.expect()</code> which has a couple of options:

</p>
<ul>
<li><code>.expect(200)</code>: Ensures that a <code>200</code> response code is returned</li>
<li><code>.expect(200, { some: 'body' })</code>: Ensures that a <code>200</code> <em>and</em> that the response body is <code>{ some: 'body' }</code></li>
<li><code>.expect(<span class="function"><span class="keyword">function</span> <span class="params">(error, response, body)</span> {</span> ... })</code>: Ensures that the custom assertion on the <code>error</code>, <code>response</code> and <code>body</code> is met.
<br><br></li>
</ul>
<p><div class="snippet"><pre><code>var APIeasy = require('api-easy');

<span class="comment">//</span>
<span class="comment">// </span>Create a APIeasy test suite <span class="keyword">for</span> our API
<span class="comment">//</span>
var suite = APIeasy.describe('api');

<span class="comment">//</span>
<span class="comment">// </span>Add some discussion around the vowsjs tests.
<span class="comment">// </span>Not familiar with vows? Checkout:
<span class="comment">// </span>http:<span class="comment">//v</span>owsjs.org 
<span class="comment">//</span>
suite.discuss('When using the API')
     .discuss('the Ping resource');</code></pre></div>

</p>
<p>In the above code sample we create a <a href="http://indexzero.github.com/api-easy">APIeasy</a> suite, and then add some discussion around the tests we are about to create. Each method on the <a href="http://indexzero.github.com/api-easy">APIeasy</a> suite returns the suite itself so we can continue to add additional tests and test context to the suite. 
<br><br>

</p>
<h1>Adding tests with APIeasy</h1>
<p><a href="http://indexzero.github.com/api-easy">APIeasy</a> allows you to add both tests and set default options for each outgoing HTTP request against your API. Lets add some tests for the <code>/ping</code> route in our sample API:

</p>
<p><div class="snippet"><pre><code><span class="comment">//</span>
<span class="comment">// </span>Here we will configure our tests to use 
<span class="comment">// </span>http:<span class="comment">//l</span>ocalhost:<span class="number">8080</span> as the remote address
<span class="comment">// </span>and to always send 'Content-Type': 'application/json'
<span class="comment">//</span>
suite.use('localhost', <span class="number">8000</span>)
     .setHeader('Content-Type', 'application/json');
     <span class="comment">//</span>
     <span class="comment">// </span>A GET Request to /ping
     <span class="comment">// </span>  should respond with <span class="number">200</span>
     <span class="comment">// </span>  should respond with { pong: <span class="literal">true</span> }
     <span class="comment">//</span>
     .get('/ping')
       .expect(<span class="number">200</span>, { pong: <span class="literal">true</span> })
      <span class="comment">//</span>
      <span class="comment">// </span>A POST Request to /ping
      <span class="comment">// </span>  should respond with <span class="number">200</span>
      <span class="comment">// </span>  should respond with { dynamic_data: <span class="literal">true</span> }
      <span class="comment">//</span>
     .post('/tests', { dynamic_data: <span class="literal">true</span> })
       .expect(<span class="number">200</span>, { dynamic_data: <span class="literal">true</span> })
</code></pre></div>

</p>
<p><br>
</p>
<h1>Adding sequential tests</h1>
<p>As you build more complex test suites, you will want to add and remove discussion text using the <code>.discuss()</code> and <code>.undiscuss()</code> methods. This design is similar to the native Javascript Array <code>.<span class="identifier"><span class="keymethods">shift</span></span>()</code> and <code>.<span class="identifier"><span class="keymethods">unshift</span></span>()</code> except that the operations are switched: <code>.discuss()</code> will append the string to the set of discussion used in the current suite and <code>.undiscuss()</code> will remove the latest discussion string.

</p>
<p>Testing APIs also frequently requires that certain tests be run in sequence (i.e. one test <strong>must</strong> be run after another). <a href="http://indexzero.github.com/api-easy">APIeasy</a> makes this possible through the <code>.<span class="identifier"><span class="keyword">next</span></span>()</code> method. Tests after an invocation of <code>.<span class="identifier"><span class="keyword">next</span></span>()</code> will be added to a separate <a href="http://vowsjs.org">vows</a> batch ensuring that they run after the current tests.

</p>
<p><div class="snippet"><pre><code><span class="comment">//</span>
<span class="comment">// Add more tests</span>
<span class="comment">//</span>
suite.undiscuss()
     .discuss(<span class="string">'when authenticating'</span>)
     .get(<span class="string">'/login'</span>)
     .expect(<span class="number">200</span>)
     .expect(<span class="string">'should respond with the authorize token'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, res, body)</span> {</span>
       <span class="keyword">var</span> result = JSON.parse(body);
       assert.isNotNull(result.token);

       suite.before(<span class="string">'setAuth'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(outgoing)</span> {</span>
         outgoing.headers[<span class="string">'x-test-authorized'</span>] = result.token;
         <span class="keyword">return</span> outgoing;
       });
     })
     <span class="comment">//</span>
     <span class="comment">// Before we can test our request to /restricted </span>
     <span class="comment">// the request to /login must respond. To ensure this</span>
     <span class="comment">// we make a call to .next() before our next call to .get()</span>
     <span class="comment">//</span>
     .next()
     .get(<span class="string">'/restricted'</span>)
       .expect(<span class="number">200</span>, { authorized: <span class="literal">true</span> })</code></pre></div>

</p>
<p>As you can see in the above code sample, <code>.<span class="identifier"><span class="keyword">next</span></span>()</code> is extremely important because we can only make a successful request to <code>/restricted</code> <em>after</em> we have gotten an authentication token from our request to <code>/login</code>. 
<br><br>

</p>
<h1>Running your test suite</h1>
<p><a href="http://indexzero.github.com/api-easy">APIeasy</a> is built on top of <a href="http://vowsjs.org">vows</a>, a test library for node.js. Running your <a href="http://indexzero.github.com/api-easy">APIeasy</a> tests is simple: just use the vows test runner:

</p>
<p><pre>
  vows your-test-suite.js
</pre>
<br>

</p>
<h1>More documentation</h1>
<p>There is more information available on <a href="http://indexzero.github.com/api-easy">APIeasy</a> at the <a href="http://github.com/indexzero/api-easy">GitHub project page</a>. Most of the documentation is written using the <a href="http://www.literateprogramming.com/">literate programming</a> tool, <a href="http://github.com/indexzero/docco">docco</a>. Read the source code here: <a href="http://indexzero.github.com/api-easy"><a href="http://indexzero.github.com/api-easy">http://indexzero.github.com/api-easy</a></a>. APIeasy is a work in-progress, so submit your issues and feedback. Your feedback is valuable.<br><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/rest-easy-test-any-api-in-nodejs</link><guid isPermaLink="true">http://blog.nodejitsu.com/rest-easy-test-any-api-in-nodejs</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Fri, 08 Apr 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./nodejs-training-sessions">Node.js Training Sessions</a>]]></title><description><![CDATA[<p>As part of my ongoing series of amazing news, I'm proud to announce <a href="http://Nodejitsu.com">Nodejitsu</a>, in conjunction with the fine folks @ <a href="http://bocoup.com">Bocoup</a>, will be hosting three upcoming training workshops about our favorite technology...<a href="http://nodejs.org">Node.js</a>!

</p>
<p>These workshops will be in: New York, Boston, and Portland ( before <a href="http://nodeconf.com/">NodeConf</a> ) on the following dates:

</p>
<ul>
<li><a href="http://www.eventbrite.com/event/1472258565">April 23 : New York, New York</a></li>
<li><a href="http://www.eventbrite.com/event/1529212917">April 30 : Boston, Massachusetts</a></li>
<li><a href="http://training.bocoup.com/Pre-NodeConf2011/">May 4th : Portland, Oregon</a></li>
</ul>
<p>The training workshops will feature members of the Nodejitsu development team walking through a full day program that will take you from the basics of async programming in JavaScript all the way to running an entire Node.js stack in production.


</p>
<p><strong>Morning</strong>

</p>
<ul>
<li>From the Browser to the Server</li>
<li>Characteristics of Async Programming</li>
<li>Buffers, Streams, and EventEmitters</li>
<li>Speaking HTTP like a Native</li>
<li>File System</li>
<li>Assertions</li>
<li>Async Iteration</li>
</ul>
<p><strong>Afternoon</strong>

</p>
<ul>
<li>Getting started with <a href="http://npmjs.org">npm</a></li>
<li>Lets build a Web Service</li>
<li>Routing with <a href="http://github.com/cloudhead/journey">Journey</a></li>
<li>Relax! with <a href="https://github.com/cloudhead/cradle">Cradle</a> and <a href="https://github.com/cloudhead/resourcer">Resourcer</a></li>
<li>Serve Static Assets with <a href="https://github.com/cloudhead/node-static">node-static</a></li>
<li>Handle session and cookies</li>
<li>Logging with <a href="https://github.com/indexzero/winston">Winston</a></li>
<li>Get Real-(time) with <a href="http://socket.io">Socket.io</a></li>
<li>Testing with <a href="http://vowsjs.org">Vows</a></li>
<li>Go Prod with <a href="https://github.com/indexzero/forever">Forever</a> and <a href="https://github.com/LearnBoost/cluster">Cluster</a></li>
</ul>
<p><br>

</p>
<h2> </h2>
<p>We look forward to helping get as many developers production ready with Node.js as we can! We'll be answering any Node questions you can think up and we'll be sticking around after each workshop to hack and possibly get some tasty drinks!

</p>
<p>For those of you who are planning to be in Portland for <a href="http://nodeconf.com/">NodeConf</a> or <a href="http://2011.jsconf.us/">JSConf</a> this year, I highly recommend you try to make it to our <a href="http://training.bocoup.com/Pre-NodeConf2011/">Oregon session</a>. We'll have the entire team there, some special guests, and I'll even be giving a presentation on the basics of building and publishing open-source node modules.

</p>
<p>If you can't make it to any of these three node.js training sessions, don't fret! There will be more in the future! If you'd like Nodejitsu to come to your event or company we'd be glad to start a dialog! Feel free to reach out to us at <a href="mailto:info@nodejitsu.com">info@nodejitsu.com</a> anytime!

</p>
<p><em>Until the next batch of amazing news....Ninja Out!</em>
</p>
]]></description><link>http://blog.nodejitsu.com/nodejs-training-sessions</link><guid isPermaLink="true">http://blog.nodejitsu.com/nodejs-training-sessions</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Wed, 06 Apr 2011 17:20:00 GMT</pubDate></item><item><title><![CDATA[<a href="./intern-at-nodejitsu">Intern at Nodejitsu</a>]]></title><description><![CDATA[<h4>Nodejitsu is looking to hire three individuals for paid internship positions in the following locations:</h4>
<ul>
<li>On-site @ Nodejitsu Corporate offices in <a href="http://maps.google.com/maps?q=union+square+manhattan&amp;ie=UTF8&amp;hq=&amp;hnear=Union+Square,+New+York&amp;gl=us&amp;z=14">Union Square, Manhattan</a> ( at <a href="http://www.generalassemb.ly/">General Assembly</a> )</li>
<li>On-site @ Nodejitsu's <a href="http://blog.nodejitsu.com/the-west-coast-hack-haus">West Coast Hack Haus</a> in <a href="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Lower+Haight,+CA&amp;aq=0&amp;sll=40.735863,-73.991084&amp;sspn=0.036225,0.078878&amp;gl=us&amp;ie=UTF8&amp;hq=&amp;hnear=Lower+Haight,+San+Francisco,+California&amp;z=15">Lower Haight, San Francisco</a></li>
<li>Telecommute ( international may apply )</li>
</ul>
<p>Nodejitsu is a platform as a service and marketplace for <a href="http://nodejs.org">Node.js</a> applications. We build a lot of cool and complex software using cutting edge technologies and we maintain a lot of open-source projects. Check out our <a href="http://github.com/nodejitsu">github page</a> or hop into #nodejs on irc.freenode.net to find out more. Compensation will be a competitive hourly rate based on experience. Full-time and part-time are available.

</p>
<p><br>


</p>
<h4>Responsibilities:</h4>
<ul>
<li>Become a master of Node.js and JavaScript</li>
<li>Help maintain and contribute to Nodejitsu's open-source projects</li>
<li>Build your own open-source projects</li>
<li>Work directly on Nodejitsu's platform and production stack</li>
<li>Help promote Node.js through informative blog posts and tutorials</li>
</ul>
<p><br>

</p>
<h2> </h2>
<h4>Requirements:</h4>
<ul>
<li>Familiarity with the basic tenants of software development</li>
<li>Experience building a full-stack web application ( front-end, http server, back-end, database)</li>
<li>Intermediate knowledge of JavaScript, DOM, HTML, CSS</li>
<li>Ability to work at least 20 hours a week</li>
</ul>
<p><br>

</p>
<h4>Preferred Experience:</h4>
<ul>
<li>Experience building Node.js applications or modules</li>
<li>Active Github user</li>
<li>Intermediate knowledge of Node.js</li>
<li>Intermediate knowledge of linux systems administration</li>
<li>Experience with community building / blogging</li>
</ul>
<p>If you are interested please send an email to <a href="mailto:hiring@nodejitsu.com">hiring@nodejitsu.com</a> and be sure to use the one of following subjects in your email to let us know which location you are applying for: 

</p>
<p><strong>Nodejitsu Internship - NYC</strong>

</p>
<p><strong>Nodejitsu Internship - SF</strong>

</p>
<p><strong>Nodejitsu Internship - Telecommute</strong>



</p>
<p><br>

</p>
<p><em>We look forward to hearing from the next batch of potential Nodejiterns!</em>
</p>
]]></description><link>http://blog.nodejitsu.com/intern-at-nodejitsu</link><guid isPermaLink="true">http://blog.nodejitsu.com/intern-at-nodejitsu</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Tue, 29 Mar 2011 17:22:52 GMT</pubDate></item><item><title><![CDATA[<a href="./6-must-have-nodejs-modules">6 Must Have Node.js Modules</a>]]></title><description><![CDATA[<p>So you're thinking about using node.js: awesome. If you're new to the community you're probably thinking "what's the best node.js module / library for X?" I think it's really true when experienced language gurus say "80% of your favorite language is your favorite library." This is the first in a series of articles will give you a high-level overview of some of our favorite node.js libraries at Nodejitsu. Today we'll take a look at these libraries:

</p>
<p><br>

</p>
<ol>
<li><a href="https://github.com/cloudhead/cradle">cradle</a>: A high-level, caching, CouchDB library for Node.js</li>
<li><a href="https://github.com/substack/node-findit">findit</a>: Walk a directory tree in node.js</li>
<li><a href="https://github.com/mranney/node_redis">node_redis</a>: Redis client for node</li>
<li><a href="https://github.com/cloudhead/node-static">node-static</a>: RFC2616 compliant HTTP static-file server module, with built-in caching.</li>
<li><a href="https://github.com/substack/node-optimist">optimist</a>: Light-weight option parsing for node.js</li>
<li><a href="https://github.com/Leonidas-from-XIV/node-xml2js">xml2js</a>: Simple XML to JavaScript object converter.</li>
</ol>
<p><br>

</p>
<h2> </h2>
<h1>cradle: A high-level, caching, CouchDB library for Node.js</h1>
<p>If you're using <a href="http://couchdb.apache.org/">CouchDB</a> you should be using <a href="https://github.com/cloudhead/cradle">cradle</a>. Cradle stands above the other CouchDB libraries in the node.js community: it has a robust LRU (least recently used) cache, bulk document processing, and a simple and elegant API:

</p>
<p><div class="snippet"><pre><code><span class="comment">//</span>
<span class="comment">// Create a connection</span>
<span class="comment">//</span>
<span class="keyword">var</span> conn = <span class="keyword">new</span>(cradle.Connection)(<span class="string">'http://living-room.couch'</span>, <span class="number">5984</span>, {
  cache: <span class="literal">true</span>,
  raw: <span class="literal">false</span>
});

<span class="comment">//</span>
<span class="comment">// Get a database</span>
<span class="comment">//</span>
<span class="keyword">var</span> database = conn.database(<span class="string">'newyorkcity'</span>);

<span class="comment">//</span>
<span class="comment">// Now work with it</span>
<span class="comment">//</span>
database.save(<span class="string">'flatiron'</span>, {
  description: <span class="string">'The neighborhood surrounding the Flatiron building'</span>,
  boundaries: {
    north: <span class="string">'28 Street'</span>,
    south: <span class="string">'18 Street'</span>,
    east: <span class="string">'Park Avenue'</span>,
    west: <span class="string">'6 Avenue'</span>
  }
}, <span class="function"><span class="keyword">function</span> <span class="params">(err, res)</span> {</span>
  console.log(res.ok) <span class="comment">// True</span>
});</code></pre></div>

</p>
<p><br>

</p>
<h1>findit: Walk a directory tree in Node.js</h1>
<p>A common set of problems that I see on the <a href="http://groups.google.com/group/nodejs">nodejs mailing list</a> are advanced file system operations: watching <strong>all</strong> the files in a directory, enumerating an entire directory, etc. Recently, when working on my fork of <a href="https://github.com/indexzero/docco">docco</a> to respect directory structure in the documentation produced I needed such a feature. It was surprisingly <a href="https://github.com/indexzero/docco/blob/master/src/docco.coffee#L251">easy</a>: 

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> findit = require(<span class="string">'findit'</span>);

findit.find(<span class="string">'/dir/to/walk'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(file)</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// This function is called each time a file is enumerated in the dir tree</span>
  <span class="comment">//</span>
  console.log(file);
});</code></pre></div>

</p>
<p><br>

</p>
<h1>node_redis: Redis client for Node.js</h1>
<p>There have been a lot of <a href="http://redis.io/">redis</a> clients released for node.js. The question has become: which client is the right one to use? When selecting an answer to this question for any library you want to look for a few things including: <strong>the author, the recent activity, and the number of followers on GitHub.</strong> In this case the author is <a href="https://github.com/mranney">Matt Ranney</a>, a member of the node.js core team. The most recent commit was <a href="https://github.com/mranney/node_redis/commit/1a14e24faa130c561ce75d138a54f1ecddb45c6e">yesterday</a>, and the repository has over 300 followers. 

</p>
<p>Redis is really fast, and extremely useful for storing volatile information like sessions and cached data. Lets take a look at some sample usage:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> redis = require(<span class="string">"redis"</span>),
    client = redis.createClient();

client.on(<span class="string">"error"</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  console.log(<span class="string">"Error "</span> + err);
});

client.set(<span class="string">"string key"</span>, <span class="string">"string val"</span>, redis.print);
client.hset(<span class="string">"hash key"</span>, <span class="string">"hashtest 1"</span>, <span class="string">"some value"</span>, redis.print);
client.hset([<span class="string">"hash key"</span>, <span class="string">"hashtest 2"</span>, <span class="string">"some other value"</span>], redis.print);
client.hkeys(<span class="string">"hash key"</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, replies)</span> {</span>
  console.log(replies.length + <span class="string">" replies:"</span>);
  replies.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(reply, i)</span> {</span>
      console.log(<span class="string">"    "</span> + i + <span class="string">": "</span> + reply);
  });
  client.quit();
});</code></pre></div>

</p>
<p><br>

</p>
<h1>node-static: RFC2616 compliant HTTP static-file server module, with built-in caching</h1>
<p>I bet you're wondering "What the $%^@ is RFC2616?" <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a> is the standards specification for HTTP 1.1, released in 1999. This spec is responsible for outlining how (among other things) files should be served over HTTP. Thus, when choosing a node.js static file server, its important to understand which libraries are standards compliant and which are not: <a href="https://github.com/cloudhead/node-static">node-static</a> is. In addition, it has some great built-in caching which will speed up your file serving in highly concurrent scenarios. 

</p>
<p>Using node-static is easy, lets make a static file server in 7 lines of Javascript:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> static = require(<span class="string">'node-static'</span>);

<span class="comment">//</span>
<span class="comment">// Create a node-static server instance to serve the './public' folder</span>
<span class="comment">//</span>
<span class="keyword">var</span> file = <span class="keyword">new</span>(static.Server)(<span class="string">'./public'</span>);

require(<span class="string">'http'</span>).createServer(<span class="function"><span class="keyword">function</span> <span class="params">(request, response)</span> {</span>
  request.addListener(<span class="string">'end'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    <span class="comment">//</span>
    <span class="comment">// Serve files!</span>
    <span class="comment">//</span>
    file.serve(request, response);
  });
}).listen(<span class="number">8080</span>);</code></pre></div>

</p>
<p><br>

</p>
<h1>optimist: Light-weight option parsing for Node.js</h1>
<p>One of the great things about node.js is how easy it is to write (and later publish with <a href="http://npmjs.org">npm</a>) simple command-line tools in Javascript. Clearly, when one is writing a command line tool one of the most important things is to have a robust command line options parser. Our library of choice for this at <a href="http://nodejitsu.com">Nodejitsu</a> is <a href="https://github.com/substack/node-optimist">optimist</a> by <a href="https://github.com/substack">substack</a>. 

</p>
<p>Lets take a look at a sample CLI script reminiscent of <a href="http://en.wikipedia.org/wiki/Bizz_buzz">FizzBuzz</a>:

</p>
<p><div class="snippet"><pre><code>#!<span class="regexp">/usr/</span>bin/env node
<span class="keyword">var</span> argv = require(<span class="string">'optimist'</span>).argv;

<span class="keyword">if</span> (argv.rif - <span class="number">5</span> * argv.xup &gt; <span class="number">7.138</span>) {
  console.log(<span class="string">'Buy more riffiwobbles'</span>);
}
<span class="keyword">else</span> {
  console.log(<span class="string">'Sell the xupptumblers'</span>);
}</code></pre></div>

</p>
<p>Using this CLI script is easy:

</p>
<pre>
$ ./node-optimist.js --rif=55 --xup=9.52
Buy more riffiwobbles

$ ./node-optimist.js --rif 12 --xup 8.1
Sell the xupptumblers
</pre>

<p>This library has support for <code>-a</code> style arguments and <code>--argument</code> style arguments. In addition any arguments passed without an option will be available in <code>argv._</code>. For more information on this library check out the <a href="https://github.com/substack/node-optimist">repository on GitHub</a>.

</p>
<p><br>

</p>
<h1>xml2js: Simple XML to Javascript object converter</h1>
<p>Writing clients in node.js for APIs that expose data through <a href="http://json.org">JSON</a> is almost too easy. There is no need for a complex, language-specific JSON parsing library that one might find in languages such as <a href="http://flori.github.com/json/">Ruby</a> or <a href="http://docs.python.org/library/json.html">Python</a>. Just use the built-in Javascript <code>JSON.parse</code> method on the data returned and <strong>voila!</strong> you've got native Javascript objects. 

</p>
<p>But what about APIs that only expose their data through <strong>XML</strong>? You could use the native <a href="https://github.com/polotek/libxmljs">libxmljs</a> module from <a href="https://github.com/polotek">polotek</a>, but the overhead of dealing with individual XML nodes is non-trivial and (in my opinion) can lead to excess complexity. There is another, simpler option: the lesser known <a href="https://github.com/Leonidas-from-XIV/node-xml2js">xml2js</a> library available on <a href="http://npmjs.org">npm</a> and <a href="https://github.com/Leonidas-from-XIV/node-xml2js">GitHub</a>.

</p>
<p>Lets suppose that we had some <strong>XML</strong> (/me dies a little inside):

</p>
<p><div class="snippet"><pre><code>&lt;?xml version=<span class="string">"1.0"</span> encoding=<span class="string">"UTF-8"</span>?&gt;
&lt;root&gt;
  &lt;child foo=<span class="string">"bar"</span>&gt;
    &lt;grandchild baz=<span class="string">"fizbuzz"</span>&gt;grandchild content&lt;/grandchild&gt;
  &lt;/child&gt;
  &lt;sibling&gt;<span class="keyword">with</span> content!&lt;/sibling&gt;
&lt;/root&gt;</code></pre></div>

</p>
<p>Parsing this using xml2js is actually surprisingly easy:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> fs = require(<span class="string">'fs'</span>),
    eyes = require(<span class="string">'eyes'</span>),
    xml2js = require(<span class="string">'xml2js'</span>);

<span class="keyword">var</span> parser = <span class="keyword">new</span> xml2js.Parser();

parser.on(<span class="string">'end'</span>, <span class="function"><span class="keyword">function</span><span class="params">(result)</span> {</span>
  eyes.inspect(result);
});

fs.readFile(__dirname + <span class="string">'/foo.xml'</span>, <span class="function"><span class="keyword">function</span><span class="params">(err, data)</span> {</span>
  parser.parseString(data);
});</code></pre></div>

</p>
<p>The output we would see is: 

</p>
<p><div class="snippet"><pre><code>{
  child: {
    @: { foo: 'bar' },
    grandchild: {
      <span class="comment">#: 'grandchild content',</span>
      @: { baz: 'fizbuzz' }
    }
  },
  sibling: 'with content!'
}
</code></pre></div>

</p>
<p>If you haven't already noticed, xml2js transforms arbitrary XML to JSON in the following way:

</p>
<ul>
<li>All entity tags like <code>&lt;child&gt;</code> become keys in the corresponding JSON.</li>
<li>Simple tags like <code>&lt;sibling&gt;<span class="keyword">with</span> content&lt;/sibling&gt;</code> become simple key:value pairs (e.g. sibling: 'with content!')</li>
<li>More complex tags like <code>&lt;child&gt;...</code> and <code>&lt;grandchild&gt;...</code> become complex key:value pairs where the value is an Object literal with two important properties: <ol>
<li><code>@</code>: An Object representing all attributes on the specified tag</li>
<li><code><span class="comment">#</span></code>: Any text content for this XML node.  </li>
</ol>
</li>
</ul>
<p>This simple mapping can greatly simplify the XML parsing logic in your node.js application and is worth checking out if you ever have to deal with the three-headed dog we all love to hate. 

</p>
<p><br>

</p>
<h1>Just getting started</h1>
<p>This is the first in a series of articles where we will outline at a high level the best-of-the-best for modules, libraries and techniques in node.js that you should be aware of. If you're interested in writing your own node.js modules and publishing them to <a href="http://npmjs.org">npm</a>, check out <a href="http://howtonode.org/how-to-module">isaacs new article: How to Module</a> over at <a href="http://howtonode.org">howtonode.org</a>.

</p>
<p><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/6-must-have-nodejs-modules</link><guid isPermaLink="true">http://blog.nodejitsu.com/6-must-have-nodejs-modules</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Tue, 01 Mar 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./the-west-coast-hack-haus">The West Coast Hack Haus</a>]]></title><description><![CDATA[<p>Good news everyone! As part of a series of amazing upcoming news, I'm proud to be reporting from Nodejitsu's brand new West Coast Hack Haus in San Francisco! Our main corporate headquarters will remain in Manhattan at the very awesome <a href="http://www.generalassemb.ly/">General Assembly</a>, but we just couldn't resist getting a West Coast presence. Anyone from the original <a href="http://groups.google.com/group/nycjs">NYC.js</a> days at the old <a href="http://pivotallabs.com/">Pivotal Labs</a> offices will remember some of the JavaScript parties we had in New York and I hope to continue this tradition in San Francisco.

</p>
<p><br>

</p>
<h2> </h2>
<p><img src="the-west-coast-hack-haus/page.jpg">

</p>
<p><em>( terrible camera phone shot )</em>

</p>
<p>The West Coast Hack Haus is located in <a href="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Lower+Haight,+San+Francisco&amp;aq=&amp;sll=37.0625,-95.677068&amp;sspn=38.690438,93.076172&amp;ie=UTF8&amp;hq=&amp;hnear=Lower+Haight,+San+Francisco,+California&amp;z=15">Lower Haight, San Francisco</a>. It's super spacious and we've got plenty of couches for wayward programmers visiting from out of town. Anytime, day or night, is a good time for a JavaScript party! If anyone wants to come to hang out or work on some code, just shoot me a message over Github or in the node.js IRC room.


</p>
<p>If anyone knows any good meetups in the Bay Area, please reach out. I'd love to attend and I'm <em>always</em> ready to give a lightning talk :-)

</p>
<p><br>

</p>
<!--<img src = "http://nodejitsu.com/img/ninja.png" style="border:none;"/>-->

<p><em>Let the JavaScript Party Begin!</em>


</p>
]]></description><link>http://blog.nodejitsu.com/the-west-coast-hack-haus</link><guid isPermaLink="true">http://blog.nodejitsu.com/the-west-coast-hack-haus</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Fri, 25 Feb 2011 09:24:36 GMT</pubDate></item><item><title><![CDATA[<a href="./micro-templates-are-dead">Micro Templates Are Dead... forget about it.</a>]]></title><description><![CDATA[<p>Don't like that title? You probably disagree. That's because "micro templating" is a subject of contention. Everyone has their own idea of how it should work. People argue about which engine is N milliseconds faster than the next, or why one should use curly braces instead of angle brackets. A divided community rearranges the deck chairs on the titanic. In this article, we explore the ineptitudes of traditional micro templating. As well as demonstrate how Node.js can untangle the mess.
<br><br>

</p>
<h2> </h2>
<h1>The problem</h1>
<p>Today, most templating requires you to pepper your markup with 'stubs' or 'placeholders'. Like Java JSPs or Django Templates. It may remind you of the 90's...

</p>
<pre>
&lt;div id='&lt;%=futureData%&gt;'&gt;foo&lt;/div&gt;
</pre>

<pre>
&lt;ul&gt;{%for d.length}&lt;li id='{%d.futureData}'&gt;&lt;/li&gt;{%end for}&lt;/ul&gt;
</pre>

<p>It's non-standard, and it's a hack. Blending decision making into your presentation layout will lead to maintenance problems as the complexity of your program grows. As well, it will become more challenging for designers to manipulate and understand the new aspects and rules of the front-end they are working with. Why did anyone ever do this? It's just the evolution of web frameworks. In the beginning, web server frameworks treated html files like raw strings because they didn't have a working DOM. Here's an example...

</p>
<pre>
&lt;div id='foo'&gt;&lt;%=futureDataGoesHere%&gt;&lt;/div&gt;
</pre>
ends up getting parsed, evaluated, and regurgitated as...
<pre>
&lt;div id='foo'&gt;some new value&lt;/div&gt;
</pre>
Even worse. lets say you are a front-end developer or maintainer. You're inspecting the DOM, trying to find out why a style is only sometimes wrong. You deduce there are conditions in the HTML! Now you need to look at the file on the server. Goodness! There's some cryptic syntax in that markup! You could trace hundreds of lines of Python or Java, but you're a front-end developer, so forget that. Consider it a wild goose chase and file a bug. <strong>OR</strong> you can go node.js FTW.
<pre>
&lt;%=if(userAge=='35'){&gt;
  &lt;div class='&lt;%=whyIsTheCSSborked%&gt;'&gt;&lt;/div&gt;
&lt;%=}&gt;
</pre>

<h1>The solution</h1>
<p>If the web server had a working DOM, we could maintain the purity of the document and the node we want to manipulate would be accessible to our externalized decision-making code. We should have the same abilities on the server as on the client...

</p>
<p>Markup...
</p>
<pre>
&lt;div id='myId'&gt;&lt;/div&gt;
</pre>
Code...
<pre>
$("#myId").html("blam-o!!");
</pre>

<p>Why is that good? It's standards compliant. No workarounds like &lt;%=foo%&gt; or {$bla}. It promotes portable code by decoupling presentation from decision making. Can this be really done? Yes!

</p>
<p>Node.js has a working DOM, its called <a href="https://github.com/tmpvar/jsdom">JSDOM</a>. This in concert with Weld, our data/DOM mapping tool, is all you need to build markup that is populated with data and ready to serve. Let's take a look at these tools in action. First we'll load jQuery, then get some data. It doesn't matter where the data comes from. For simplicity's sake let's just use an array of objects.
<br><br>
</p>
<h1>Welding data to the DOM.</h1>
<micro-templates-are-dead>

<p>Here is the corresponding markup that our script above will load...

</p>
<p><div class="snippet"><pre><code>&lt;ul class="contacts"&gt;
  &lt;li class="contact"&gt;
    &lt;span class="name"&gt;My Name&lt;/span&gt;
    &lt;p class="title"&gt;Leet Developer&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;</code></pre></div>

</p>
<p>And here's what it will produce...

</p>
<p><div class="snippet"><pre><code>&lt;ul class="contacts"&gt;
  &lt;li class="contact"&gt;
    &lt;span class="name"&gt;Paolo&lt;/span&gt;
    &lt;p class="title"&gt;Code Slayer&lt;/p&gt;
  &lt;/li&gt;
  &lt;li class="contact"&gt;
    &lt;span class="name"&gt;Elijah&lt;/span&gt;
    &lt;p class="title"&gt;Code Pimp&lt;/p&gt;
  &lt;/li&gt;  
&lt;/ul&gt;</code></pre></div>

</p>
<p>I bet you're thinking "what just happened?" Exactly! By default, Weld uses a heuristic that assumes each of the keys in the data's <code>key: value</code> pairs is an '#id', a '.class' or 'name' in the template's HTML. This addresses the 80/20 of cases. If you want, you can supply more explicit instructions by providing a <code>bind</code> parameter which maps selectors to keys in your data.

</p>
<p>To be more explicit during binding, let's say you have html where a span has the class 'name', but you don't want the data with the key 'name' to map to that, you want it to map to something else...

</p>
<p><div class="snippet"><pre><code>&lt;ul class=<span class="string">"contacts"</span>&gt;
  &lt;li class=<span class="string">"contact"</span>&gt;
    &lt;span class=<span class="string">"name"</span>&gt;Hello my name is &lt;span class=<span class="string">"firstAndLast"</span>&gt;My Name&lt;<span class="regexp">/span&gt;&lt;/</span>span&gt;
    &lt;p class=<span class="string">"title"</span>&gt;Leet Developer&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;</code></pre></div>

</p>
<p>Let's say this is the data to bind...

</p>
<p><div class="snippet"><pre><code><span class="identifier">var</span> <span class="identifier">data</span> = [
  { 
    <span class="identifier"><span class="keymethods">name</span></span><span class="symbol">:</span> <span class="string">'Paulo'</span>,  
    <span class="identifier">title</span><span class="symbol">:</span> <span class="string">'code exploder'</span> 
  },
  { 
    <span class="identifier"><span class="keymethods">name</span></span><span class="symbol">:</span> <span class="string">'Elijah'</span>, 
    <span class="identifier">title</span><span class="symbol">:</span> <span class="string">'code pimp'</span> 
  }
];
</code></pre></div>

</p>
<p>Just add explicit assignments with the bind parameter...

</p>
<p><div class="snippet"><pre><code>weld('.contact', data, { 
  bind: { 
    'name': '.firstAndLast', 
    'title': '.title' 
  } 
});</code></pre></div>

</p>
<p>And we end up with this...

</p>
<p><div class="snippet"><pre><code>&lt;ul class=<span class="string">'contacts'</span>&gt;
  &lt;li class=<span class="string">'contact'</span>&gt;
    &lt;span class=<span class="string">'name'</span>&gt;Hello my name is &lt;span class=<span class="string">'firstAndLast'</span>&gt;hij1nx&lt;<span class="regexp">/span&gt;&lt;/</span>span&gt;  
    &lt;p class=<span class="string">'title'</span>&gt;code slayer&lt;/p&gt;
  &lt;/li&gt;
  &lt;li class=<span class="string">'contact'</span>&gt;
    &lt;span class=<span class="string">'name'</span>&gt;Hello my name is &lt;span class=<span class="string">'firstAndLast'</span>&gt;tmpvar&lt;<span class="regexp">/span&gt;&lt;/</span>span&gt;  
    &lt;p class=<span class="string">'title'</span>&gt;code pimp&lt;/p&gt;
  &lt;/li&gt;  
&lt;/ul&gt;</code></pre></div>

</p>
<p>Weld is like template antimatter for Javascript. It is the antithesis of most templating technology. There is no special sugar required to add data into your markup. And best of all it works in the browser and on your node.js server! In the end we get more readable presentation, markup and decision making code that is maintainable by developers with more varying skill sets.
<br><br>
</p>
<h1>How do I do X with Weld?</h1>
<p>Checkout the project <a href="https://github.com/hij1nx/weld">here</a> on github, developed by <a href="http://twitter.com/hij1nx">hij1nx</a> and <a href="http://twitter.com/tmpvar">tmpvar</a> of the <a href="http://nodejitsu.com">Nodejitsu</a> team.

</p>
<p>If you want to learn more about JSDOM, go <a href="https://github.com/tmpvar/jsdom">here</a> it's an awesome project.
<br><br><br>
</p>
</micro-templates-are-dead>]]></description><link>http://blog.nodejitsu.com/micro-templates-are-dead</link><guid isPermaLink="true">http://blog.nodejitsu.com/micro-templates-are-dead</guid><dc:creator><![CDATA[Paolo Fragomeni]]></dc:creator><pubDate>Thu, 17 Feb 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./ten-node-apps-that-need-to-exist">Ten node applications that need to exist</a>]]></title><description><![CDATA[<p>I've been studying the node.js ecosystem for a little while now and while the pace of library and module development has been astounding, the pace of application development has been a bit slower. The primary reason for this is simply that node is young and until recently the API has been a fast moving target. As node and it's many libraries start to mature, a lot of people have been asking, "What are the killer node.js applications?" In this article, I create a list of what I feel are ten "killer node.js applications" and then dive ways in which they can be implemented.

</p>
<p><br>

</p>
<ol>
<li>An instant message application that can be included on any webpage with one line of JavaScript</li>
<li>A chat room application that can be included on any webpage with one of JavaScript</li>
<li>A real-time multiuser sketchpad</li>
<li>A file and media drop box</li>
<li>A streaming Twitter client</li>
<li>A blogging / Content Management System</li>
<li>An online project management tool with Vows / Cucumber integration.</li>
<li>A social bookmarking application</li>
<li>A browser based hackable and family friendly massive multi-player game.</li>
<li>A Micro-wiki application with distributed version control</li>
</ol>
<p><br>


</p>
<h2> </h2>
<p>Now before we dive into each proposed application, let's set a few ground rules. Each application needs to be full-featured, open-source, and most importantly, easily configurable and deployable. The goal is for any newbie developer to be able to start using and customizing any of these applications with minimal effort either locally or on a Node.js hosting platform such as <a href="http://nodejitsu.com/">Nodejitsu</a>. I also tried to keep the scope of this list limited to applications which could hit version v1.0.0 in a few months with a small team of developers.

</p>
<p><br>

</p>
<h1>The list</h1>
<h2>1. Instant Messaging Application</h2>
<p>Any serious JavaScript developer has probably been asked to build a "facebook chat" in the past few years. There are even some services which provide this as a SaAS. The best current solution I've seen for node.js so far is <a href="http://ajaxim.com/">AjaxIM</a> by <a href="http://unwieldy.net/">Joshua Gross</a>. The initial version relied on PHP, but it appears they are moving away from this dependency. It looks like a great start, but like most node applications it's still under active development.

</p>
<h2>2. A Chat Application</h2>
<p>Doing a Chat application is the hello world of node's http module. There are many many solutions that do this already, but none of them are full-featured or mature. There needs to be a concerted effort to push one of the existing libraries forward, or simply start a new code base with the recent advancements to node's core and libraries like <a href="http://socket.io">socket.io</a>

</p>
<h2>3. A browser based real-time multiuser sketchpad</h2>
<p>There are a lot of really great things we can do with node.js and HTML5's canvas. <a href="http://mrdoob.com">Mr. Doob</a> released a <a href="http://mrdoob.com/projects/multiuserpad/">multi-user sketchpad</a> which he created over a weekend. I chatted with Mr. Doob about releasing the source, but there are a few security concerns he'd have to address before it could be stable. Real-time sketching collaboration tools have been around for a while, but there has never been an easy to hack open-source one that works using a standard browser. This type of tool could be used for a variety of purposes and industries across almost any device.

</p>
<h2>4. A file and media drop box</h2>
<p>Think what <a href="http://en.wikipedia.org/wiki/Drop.io">drop.io</a> was, but open-source. You can setup a private file server somewhere, or you pay for hosting on a node.js hosting service like Nodejitsu. There would be drag and drop file transfers and a nice web gui to view / manage files and media assets.

</p>
<h2>5. A streaming Twitter client</h2>
<p>I'm not a huge fan of Twitter, but a lot of other people are. Building a custom Twitter client can be a good starting point for new developers. I'm also told developers get requests to build custom Twitter clients. <a href="http://streamie.org/">Streamie</a> by <a href="http://nonblocking.io/">Malte Ubl</a> is a hackable node.js Twitter client which is pretty solid. I'd recommend checking it out.

</p>
<h2>6. A blogging / CMS engine</h2>
<p>Node needs a goto Content Management System / blogging engine. Ruby on Rails has Radiant, PHP has Wordpress, node needs it's own. The Nodejitsu blog is a custom build of <a href="http://github.com/creationix/">Tim Caswell's</a> blogging software, <a href="http://github.com/creationix/wheat/">Wheat</a>. I applaud Tim for his great work in building Wheat, it's a great little git based blogging engine. The problem is, it's currently just a blogging engine. Wheat doesn't have any of the features you'd want in a full-featured CMS or Blog. Should these features be added to Wheat? The answer is probably no, but the point is Wheat is a great example of the first steps in building such an application. 

</p>
<h2>7. An online project management tool with Vows / Cucumber integration.</h2>
<p>This is more a techie tool, but it's an essential tool for anyone who wants to do serious node.js project development. This is about building a solid suite of tools to be able to quickly develop node.js applications. The Nodejitsu team has started an initiative for this called <a href="http://github.com/nodejitsu/prenup/">Prenup</a> ( see related blog post: <a href="http://blog.nodejitsu.com/kyuri-and-prenup-our-node-knockout-entries"><a href="http://blog.nodejitsu.com/kyuri-and-prenup-our-node-knockout-entries">http://blog.nodejitsu.com/kyuri-and-prenup-our-node-knockout-entries</a></a> ), but like most node projects, it's still alpha and could use a bit of work. I urge anyone who is interested in agile software development in node to check out <a href="http://github.com/nodejitsu/kyuri/">Kyuri</a> and <a href="http://github.com/nodejitsu/prenup/">Prenup</a>. 

</p>
<h2>8. A social bookmarking site</h2>
<p>Think Reddit or Digg. Reddit actually is already open-source, but is written in Python and is not geared towards real-time at all. There is a unique opportunity to rethink these services in the context of real-time applications. In many ways, social bookmarking has replaced traditional forum software creating larger and more agile online communities. An easy to customize real-time social bookmarking application in node will lead to a whole new generation of communities. I haven't seen any good initiatives for this yet, but I have been working on a few prototypes.

</p>
<h2>9. A browser based and family friendly massive multi-player game</h2>
<p>What node could really use is a browser based game that was easy to use, customize, and be G rated enough to used as an educational tool. There is <a href="http://stephank.github.com/orona/bolo.html">Orona</a>, a tank game by <a href="http://stephan.kochen.nl/">Stephan Kochen</a>, but it's very alpha. Tim Caswell has done some experiments with his <a href="https://github.com/creationix/adventure">Adventure</a> game and <a href="https://github.com/creationix/world-db">world-db</a>, but these are just experiments. Someone could step up and make a two dimensional tile game where you went around and collected items / solved puzzles with other players. This would make a great educational tool as it would be easy for anyone ( such as a teacher ) to setup a private game server ( for their students ), and then begin to dive into customizing the game as a way of teaching programming.

</p>
<h2>10. A micro-wiki application with distributed version control</h2>
<p>Node needs a generic Wiki application that is both small in size and able to maintain versions of documents across multiple instances. This will allow for a decentralized Wikipedia which could also be sharded onto local storage, and to smaller devices like mobile phones. <a href="http://www.tiddlywiki.com/">TiddlyWiki</a> is a neat project by <a href="http://www.osmosoft.com/">Jeremy Ruston</a> which is built on this idea. Some work has been done with node and TiddyWiki, but I couldn't find anything about using node to synchronize multiple TiddlyWiki instances.

</p>
<p><br>

</p>
<h1>Conclusion</h1>
<p>It's easy to say that something needs to get done, but without execution an idea is worth little. I can only hope that by listing these applications, someone will be inspired to build something. If they happen to build a useful application in node.js, I know that we at <a href="http://nodejitsu.com/">Nodejitsu</a> will be happy to support it on our platform.


</p>
<p><em>ninja out</em>

</p>
]]></description><link>http://blog.nodejitsu.com/ten-node-apps-that-need-to-exist</link><guid isPermaLink="true">http://blog.nodejitsu.com/ten-node-apps-that-need-to-exist</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Fri, 11 Feb 2011 10:24:36 GMT</pubDate></item><item><title><![CDATA[<a href="./a-simple-webservice-in-nodejs">A simple web service in node.js</a>]]></title><description><![CDATA[<p>I recently gave a talk at <a href="http://adicu.com/devfest2011">ADICU Devfest 2011</a> on node.js. The talk was aimed at Computer Science students who did not know anything about node.js and more importantly, how to get started building simple and elegant web services from scratch. The slides (and code) from my talk are available on <a href="http://github.com/indexzero/nodejs-intro">GitHub</a>.   

</p>
<p>This article will walk through the code that I presented to build a simple RESTful bookmarking API using node.js and:
<br><br>

</p>
<ul>
<li><a href="http://github.com/cloudhead/journey">Journey</a>: A liberal JSON-only HTTP request router for node.js</li>
<li><a href="http://github.com/cloudhead/cradle">Cradle</a>: A high-level, caching, CouchDB library for Node.js</li>
<li><a href="http://github.com/indexzero/winston">Winston</a>: A multi-transport async logging library for node.js</li>
<li><a href="http://github.com/substack/node-optimist">Optimist</a>: Light-weight option parsing for node.js </li>
</ul>
<p><br>

</p>
<h2> </h2>
<h1>Getting Started</h1>
<p>The first step to doing anything with node.js is creating a server to accept incoming <a href="http://nodejs.org/docs/v0.3.7/api/http.html">HTTP requests</a>. You can also create a <a href="http://nodejs.org/docs/v0.3.7/api/net.html">TCP server</a> or <a href="http://nodejs.org/docs/v0.3.7/api/dgram.html">work with UDP</a>, but I won't be going into that here. So what does such a server look like? 

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> http = require(<span class="string">'http'</span>),
    winston = require(<span class="string">'winston'</span>);

<span class="comment">/**
 * Creates the server for the pinpoint web service
 * @param {int} port: Port for the server to run on
 */</span>
exports.createServer = <span class="function"><span class="keyword">function</span> <span class="params">(port)</span> {</span>
  <span class="keyword">var</span> server = http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(request, response)</span> {</span>
    <span class="keyword">var</span> data = <span class="string">''</span>;
    
    winston.info(<span class="string">'Incoming Request'</span>, { url: request.url });
    
    request.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(chunk)</span> {</span>
      data += chunk;
    });
    
    response.writeHead(<span class="number">501</span>, { <span class="string">'Content-Type'</span>: <span class="string">'application/json'</span> });
    response.end(JSON.stringify({ message: <span class="string">'not implemented'</span> }));
  });
  
  <span class="keyword">if</span> (port) {
    server.listen(port);
  }
  
  <span class="keyword">return</span> server;
};</code></pre></div>

</p>
<p>The above example is simple (almost trivial): it exports a server that reads the request body, logs the request using <a href="http://github.com/indexzero/winston">winston</a>, and responds with the appropriate HTTP response code (501 - Not Implemented). Not very exciting but enough to get us started.
<br><br>

</p>
<h1>Running the development server</h1>
<p>The development server lives in  <code>bin\server</code>  and has been configured so that we can run the development server at the various stages of development outlined in this tutorial. Running it is simple, just remember to pass the <code>-t</code> argument which specifies which directory under /lib to use for the server:

</p>
<ul>
<li><a href="https://github.com/indexzero/nodejs-intro/tree/master/lib/00getting-started">00getting-started</a>: The full source code from 'Getting Started'</li>
<li><a href="https://github.com/indexzero/nodejs-intro/tree/master/lib/01routing">01routing</a>: The full source code from 'Adding some Routes'</li>
<li><a href="https://github.com/indexzero/nodejs-intro/tree/master/lib/02couchdb">02couchdb</a>: The full source code from 'Interacting with CouchDB'</li>
<li><a href="https://github.com/indexzero/nodejs-intro/tree/master/lib/03authentication">03authentication</a>: The full source code from 'Adding HTTP Basic Auth'</li>
</ul>
<pre>
  $ bin/server -t 00getting-started
  Pinpoint demo server listening for 00getting-started on <a href="http://127.0.0.1:8000">http://127.0.0.1:8000</a>
  4 Feb 17:59:22 - info: Incoming Request url=/
</pre>

<h1>Adding some Routes</h1>
<p>Now that we have a server that tells the world we haven't done anything it's time to think about what our application does:

</p>
<ul>
<li><em>List:</em> GET to /bookmarks should respond with a list of bookmarks</li>
<li><em>Create:</em> POST to /bookmarks should create a new bookmark</li>
<li><em>Show:</em> GET to /bookmarks/:id should respond with a specific bookmark</li>
<li><em>Update:</em> PUT to /bookmarks/:id should update a specific bookmark</li>
<li><em>Destroy:</em> DELETE to /bookmarks/:id should delete a specific bookmark</li>
</ul>
<p>Pretty simple right? Absolutely. To accomplish this routing tasks we are going to use <a href="http://github.com/cloudhead/journey">Journey</a>. Journey is a great library with a lot of features. <a href="https://github.com/cloudhead/journey/commit/3092215bfd9c4b564f3569a42950c08d917e6648">0.3.1</a> was just released, which we will be taking advantage of in this post.

</p>
<p><div class="snippet"><pre><code>exports.createRouter = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">new</span> (journey.Router)(<span class="function"><span class="keyword">function</span> <span class="params">(map)</span> {</span>
    map.path(<span class="regexp">/\/bookmarks/</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
      <span class="comment">//</span>
      <span class="comment">// LIST: GET to /bookmarks lists all bookmarks</span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.get().bind(<span class="function"><span class="keyword">function</span> <span class="params">(res)</span> {</span>
        res.send(<span class="number">501</span>, {}, { action: <span class="string">'list'</span> });
      });
      
      <span class="comment">//</span>
      <span class="comment">// SHOW: GET to /bookmarks/:id shows the details of a specific bookmark </span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.get(<span class="regexp">/\/([\w|\d|\-|\_]+)/</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res, id)</span> {</span>
        res.send(<span class="number">501</span>, {}, { action: <span class="string">'show'</span> });
      });
      
      <span class="comment">//</span>
      <span class="comment">// CREATE: POST to /bookmarks creates a new bookmark</span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.post().bind(<span class="function"><span class="keyword">function</span> <span class="params">(res, bookmark)</span> {</span>
        res.send(<span class="number">501</span>, {}, { action: <span class="string">'create'</span> });
      });
      
      <span class="comment">//</span>
      <span class="comment">// UPDATE: PUT to /bookmarks updates an existing bookmark</span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.put(<span class="regexp">/\/([\w|\d|\-|\_]+)/</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res, bookmark)</span> {</span>
        res.send(<span class="number">501</span>, {}, { action: <span class="string">'update'</span> });
      });
      
      <span class="comment">//</span>
      <span class="comment">// DELETE: DELETE to /bookmarks/:id deletes a specific bookmark</span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.del(<span class="regexp">/\/([\w|\d|\-|\_]+)/</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res, id)</span> {</span>
        res.send(<span class="number">501</span>, {}, { action: <span class="string">'delete'</span> });
      });
    });
  }, { strict: <span class="literal">false</span> });
};</code></pre></div>

</p>
<p>The above code generates a Journey router that matches the routes we outlined using regular expressions. In each route, we respond with <code>501 Not Implemented</code> and the corresponding action so that we can be sure we've hit the correct route.

</p>
<p>We use the <code><span class="identifier"><span class="keymethods">map</span></span>.<span class="identifier">path</span></code> syntax to scope the subsequent routes behind <code>/bookmarks</code>. The changes that need to be made to our development server are minimal. We just need to add code to create our router and later it to route our request with the associated request body within our HTTP server:<br><br>

</p>
<p><div class="snippet"><pre><code>request.on(<span class="string">'end'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="comment">//</span>
  <span class="comment">// Dispatch the request to the router</span>
  <span class="comment">//</span>
  router.route(request, body, <span class="function"><span class="keyword">function</span> <span class="params">(route)</span> {</span>
    response.writeHead(route.status, route.headers);
    response.end(route.body);
  });
});</code></pre></div>

</p>
<p>You can view the entire file on GitHub <a href="https://github.com/indexzero/nodejs-intro/blob/master/lib/01routing/pinpoint.js">here</a>.
<br><br>
</p>
<h1>Testing Routes using http-console</h1>
<p>One of the things I did differently in this demo than I do in my own projects is that <strong>there are no <a href="http://vowsjs.org">vowsjs</a> tests.</strong> I choose not to include tests in this demo because the additional overhead of understanding how a particular test framework works seemed a little high for the complete beginner. 

</p>
<p>The alternative was to use <a href="https://github.com/cloudhead/http-console">http-console</a>: a simple, intuitive HTTP REPL. Getting http-console is easy to install using <a href="http://npmjs.org">npm</a>:

</p>
<pre>
  [sudo] npm install http-console
</pre> 

<p>So lets fire-up http-console for an interactive session a couple of our newly minted routes:

</p>
<pre>
  $ http-console <a href="http://127.0.0.1:8000">http://127.0.0.1:8000</a>
  &gt; http-console 0.5.1
  &gt; Welcome, enter \help if you're lost.
  &gt; Connecting to 127.0.0.1 on port 8000.

  <a href="http://127.0.0.1:8000/&gt;">http://127.0.0.1:8000/&gt;</a> GET /bookmarks
  HTTP/1.1 501 Not Implemented
  Date: Sat, 05 Feb 2011 02:57:46 GMT
  Server: journey/0.3.0
  Content-Type: application/json
  Content-Length: 17
  Connection: close

  { action: 'list' }
  <a href="http://127.0.0.1:8000/&gt;">http://127.0.0.1:8000/&gt;</a> GET /bookmarks/foobar
  HTTP/1.1 501 Not Implemented
  Date: Sat, 05 Feb 2011 02:57:52 GMT
  Server: journey/0.3.0
  Content-Type: application/json
  Content-Length: 17
  Connection: close

  { action: 'show' }
  <a href="http://127.0.0.1:8000/&gt;">http://127.0.0.1:8000/&gt;</a><br></pre>

<p>We made two request to <code>/bookmarks</code> and <code>/bookmarks/foobar</code> respectively and got back 501 in both cases with valid JSON representing the specified action that is not yet implemented. We also got back the <code>application/json</code> header which was automatically set for us by Journey.<br><br>

</p>
<h1>Interacting with CouchDB</h1>
<p>Interacting with a persistent data store is a must have for any webservice or web application. At <a href="http://nodejitsu.com">Nodejitsu</a> we use <a href="http://blog.couchone.com/post/2314470878/nodejitsu-couchone-couchdb">CouchDB</a> and our library of choice is <a href="http://github.com/cloudhead/cradle">cradle</a>. We will define a Bookmark resource with a couple of methods for performing basic CRUD on our bookmark object. Before we get to that we need to configure our Couch with a Design Document for Bookmark resources. If you want to learn more about Design Doucments see <a href="http://guide.couchdb.org/draft/design.html">CouchDB: The Definitive Guide</a>.

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> cradle = require(<span class="string">'cradle'</span>);
 
<span class="keyword">var</span> setup = exports.setup = <span class="function"><span class="keyword">function</span> <span class="params">(options, callback)</span> {</span>
  <span class="comment">// Set connection configuration</span>
  cradle.setup({
    host: options.host || <span class="string">'127.0.0.1'</span>,
    port: <span class="number">5984</span>,
    options: options.options,
  });
  
  <span class="comment">// Connect to cradle</span>
  <span class="keyword">var</span> conn = <span class="keyword">new</span> (cradle.Connection)({ auth: options.auth }),
      db = conn.database(options.database || <span class="string">'pinpoint-dev'</span>);
      
  <span class="keyword">if</span> (options.setup) {
    initViews(db, callback);
  }
  <span class="keyword">else</span> {
    callback(<span class="literal">null</span>, db); 
  }
};

<span class="keyword">var</span> initViews = exports.initViews = <span class="function"><span class="keyword">function</span> <span class="params">(db, callback)</span> {</span>
  <span class="keyword">var</span> designs = [
    {
      <span class="string">'_id'</span>: <span class="string">'_design/Bookmark'</span>,
      views: {
        all: {
          map: <span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span> <span class="keyword">if</span> (doc.resource === <span class="string">'Bookmark'</span>) emit(doc._id, doc) }
        },
        byUrl: {
          map: <span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span> <span class="keyword">if</span> (doc.resource === <span class="string">'Bookmark'</span>) { emit(doc.url, doc); } }
        },
        byDate: {
          map: <span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span> <span class="keyword">if</span> (doc.resource === <span class="string">'Bookmark'</span>) { emit(doc.date, doc); } }
        }
      }
    }
  ];
  
  db.save(designs, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> callback(err);
    callback(<span class="literal">null</span>, db);    
  });
};</code></pre></div>

</p>
<p>The above code requires cradle, configures it with the remote host, port and authentication (if required). If <code>options.setup</code> is set then it asynchronously creates the Design Document in CouchDB and later responds with the database connection <code>db</code>.

</p>
<p>Now that we have a connection to CouchDB for our application, we can go ahead and create a Bookmark resource that consumes the connection. Within this resource we want to define functions for each of the CRUD operations we've outlined: <code>create</code>, <code>show</code>, <code>list</code>, <code><span class="identifier"><span class="keymethods">update</span></span></code> and <code>destroy</code>.

</p>
<p><div class="snippet"><pre><code><span class="comment">/**
* Constructor function for the Bookmark object..
* @constructor
* @param {connection} database: Connection to CouchDB
*/</span>
<span class="keyword">var</span> Bookmark = exports.Bookmark = <span class="function"><span class="keyword">function</span> <span class="params">(database)</span> {</span>
  <span class="keyword">this</span>.database = database;
};

<span class="comment">/**
* Lists all Bookmarks in the database
* @param {function} callback: Callback function
*/</span>
Bookmark.prototype.list = <span class="function"><span class="keyword">function</span> <span class="params">(callback)</span> {</span>
  <span class="keyword">this</span>.database.view(<span class="string">'Bookmark/all'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, result)</span> {</span>
    <span class="keyword">if</span> (err) {
      <span class="keyword">return</span> callback(err);
    }
    
    callback(<span class="literal">null</span>, result.rows.map(<span class="function"><span class="keyword">function</span> <span class="params">(row)</span> {</span> <span class="keyword">return</span> row.value }));
  })
};

<span class="comment">/**
* Shows details of a particular bookmark
* @param {string} id: ID of the bookmark
* @param {function} callback: Callback function
*/</span>
Bookmark.prototype.show = <span class="function"><span class="keyword">function</span> <span class="params">(id, callback)</span> {</span>
  <span class="keyword">this</span>.database.get(id, <span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
    <span class="keyword">if</span> (err) {
      <span class="keyword">return</span> callback(err);
    }
    
    callback(<span class="literal">null</span>, doc);
  });
};

<span class="comment">/**
* Creates a new bookmark with the specified properties
* @param {object} bookmark: Properties to use for the bookmark
* @param {function} callback: Callback function
*/</span>
Bookmark.prototype.create = <span class="function"><span class="keyword">function</span> <span class="params">(bookmark, callback)</span> {</span>
  bookmark._id = helpers.randomString(<span class="number">32</span>);
  bookmark.resource = <span class="string">"Bookmark"</span>;
  
  <span class="keyword">this</span>.database.save(bookmark._id, bookmark, <span class="function"><span class="keyword">function</span> <span class="params">(err, res)</span> {</span>
    <span class="keyword">if</span> (err) {
      <span class="keyword">return</span> callback(err);
    }
    
    callback(<span class="literal">null</span>, bookmark);
  })
};

<span class="comment">/**
* Updates a new bookmark with the specified id and properties
* @param {object} bookmark: Properties to update the bookmark with
* @param {function} callback: Callback function
*/</span>
Bookmark.prototype.update = <span class="function"><span class="keyword">function</span> <span class="params">(id, bookmark, callback)</span> {</span>
  <span class="keyword">this</span>.database.merge(id, bookmark, <span class="function"><span class="keyword">function</span> <span class="params">(err, res)</span> {</span>
    <span class="keyword">if</span> (err) {
      <span class="keyword">return</span> callback(err);
    }
    
    callback(<span class="literal">null</span>, <span class="literal">true</span>);
  });
};

<span class="comment">/**
* Destroys a bookmark with the specified ID
* @param {string} id: ID of the bookmark to destroy
* @param {function} callback: Callback function
*/</span>
Bookmark.prototype.destroy = <span class="function"><span class="keyword">function</span> <span class="params">(id, callback)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  <span class="keyword">this</span>.show(id, <span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
    <span class="keyword">if</span> (err) {
      <span class="keyword">return</span> callback(err);
    }
    
    self.database.remove(id, doc._rev, <span class="function"><span class="keyword">function</span> <span class="params">(err, res)</span> {</span>
      <span class="keyword">if</span> (err) {
        <span class="keyword">return</span> callback(err);
      }

      callback(<span class="literal">null</span>, <span class="literal">true</span>);
    });
  });
};</code></pre></div>

</p>
<p>I won't go into the details of how each of these methods work, but rest assured that they do. It's all very basic usage for <a href="http://github.com/cloudhead/cradle">cradle</a>, so if you're interested in the specifics I invite you to read the documentation on the <a href="http://github.com/cloudhead/cradle">cradle GitHub page</a>.

</p>
<p>So now that we've configured CouchDB and we have a Bookmark resource, we need to connect our resource to the Journey router that we defined earlier. 

</p>
<p><div class="snippet"><pre><code>exports.createRouter = <span class="function"><span class="keyword">function</span> <span class="params">(resource)</span> {</span>
  <span class="keyword">return</span> <span class="keyword">new</span> (journey.Router)(<span class="function"><span class="keyword">function</span> <span class="params">(map)</span> {</span>
    map.path(<span class="regexp">/\/bookmarks/</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
      <span class="comment">//</span>
      <span class="comment">// LIST: GET to /bookmarks lists all bookmarks</span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.get().bind(<span class="function"><span class="keyword">function</span> <span class="params">(res)</span> {</span>
        resource.list(<span class="function"><span class="keyword">function</span> <span class="params">(err, bookmarks)</span> {</span>
          <span class="keyword">if</span> (err) {
            <span class="keyword">return</span> res.send(<span class="number">500</span>, {}, { error: err.error });
          }
          
          res.send(<span class="number">200</span>, {}, { bookmarks: bookmarks });
        });
      });
      
      <span class="comment">//</span>
      <span class="comment">// SHOW: GET to /bookmarks/:id shows the details of a specific bookmark </span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.get(<span class="regexp">/\/([\w|\d|\-|\_]+)/</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res, id)</span> {</span>
        resource.show(id, <span class="function"><span class="keyword">function</span> <span class="params">(err, bookmark)</span> {</span>
          <span class="keyword">if</span> (err) {
            <span class="keyword">return</span> res.send(<span class="number">500</span>, {}, { error: err.error });
          }
          
          res.send(<span class="number">200</span>, {}, { bookmark: bookmark });
        });
      });
      
      <span class="comment">//</span>
      <span class="comment">// CREATE: POST to /bookmarks creates a new bookmark</span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.post().bind(<span class="function"><span class="keyword">function</span> <span class="params">(res, bookmark)</span> {</span>
        resource.create(bookmark, <span class="function"><span class="keyword">function</span> <span class="params">(err, result)</span> {</span>
          <span class="keyword">if</span> (err) {
            <span class="keyword">return</span> res.send(<span class="number">500</span>, {}, { error: err.error });
          }
          
          res.send(<span class="number">200</span>, {}, { bookmark: result });
        });
      });
      
      <span class="comment">//</span>
      <span class="comment">// UPDATE: PUT to /bookmarks updates an existing bookmark</span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.put(<span class="regexp">/\/([\w|\d|\-|\_]+)/</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res, id, bookmark)</span> {</span>
        resource.update(id, bookmark, <span class="function"><span class="keyword">function</span> <span class="params">(err, updated)</span> {</span>
          <span class="keyword">if</span> (err) {
            <span class="keyword">return</span> res.send(<span class="number">500</span>, {}, { error: err.error });
          }
          
          res.send(<span class="number">200</span>, {}, { updated: updated });
        });
      });
      
      <span class="comment">//</span>
      <span class="comment">// DELETE: DELETE to /bookmarks/:id deletes a specific bookmark</span>
      <span class="comment">//</span>
      <span class="keyword">this</span>.del(<span class="regexp">/\/([\w|\d|\-|\_]+)/</span>).bind(<span class="function"><span class="keyword">function</span> <span class="params">(res, id)</span> {</span>
        resource.destroy(id, <span class="function"><span class="keyword">function</span> <span class="params">(err, destroyed)</span> {</span>
          <span class="keyword">if</span> (err) {
            <span class="keyword">return</span> res.send(<span class="number">500</span>, {}, { error: err.error });
          }
          
          res.send(<span class="number">200</span>, {}, { destroyed: destroyed });
        });
      });
    });
  }, { strict: <span class="literal">false</span> });
};</code></pre></div>

</p>
<p>In each of the new routes, we send the appropriate request data to the Bookmark resource, and asynchronously respond with the appropriate HTTP response code when complete. In the event of an error, we always send <code>500 Internal Server Error</code> with the error message.
<br><br>

</p>
<h1>Adding HTTP Basic Auth</h1>
<p>The main focus of Journey 0.3.0 was to add a feature where the programmer could specify a filter function that takes the request and body. This filter function will intercept requests before they are passed to any route handler. If the filter function returns a pre-defined Journey error, the router will short-circuit and respond with the status code. We will use this feature to define a filter function that performs <a href="http://www.ietf.org/rfc/rfc2617.txt">HTTP Basic Auth</a>.

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> auth = exports.auth = {
  username: <span class="string">'admin'</span>,
  password: <span class="string">'password'</span>,
  basicAuth: <span class="function"><span class="keyword">function</span> <span class="params">(request, body, callback)</span> {</span>
    <span class="keyword">var</span> realm = <span class="string">"Authorization Required"</span>,
        authorization = request.headers.authorization;
    
    <span class="keyword">if</span> (!authorization) {
      <span class="keyword">return</span> callback(<span class="keyword">new</span> journey.NotAuthorized(<span class="string">"Authorization header is required."</span>));
    }

    <span class="keyword">var</span> parts       = authorization.split(<span class="string">" "</span>),           <span class="comment">// Basic salkd787&amp;u34n=</span>
        scheme      = parts[<span class="number">0</span>],                           <span class="comment">// Basic</span>
        credentials = base64.decode(parts[<span class="number">1</span>]).split(<span class="string">":"</span>); <span class="comment">// admin:password</span>

    <span class="keyword">if</span> (scheme !== <span class="string">"Basic"</span>) {
      <span class="keyword">return</span> callback(<span class="keyword">new</span> journey.NotAuthorized(<span class="string">"Authorization scheme must be 'Basic'"</span>));
    }
    <span class="keyword">else</span> <span class="keyword">if</span>(!credentials[<span class="number">0</span>] &amp;&amp; !credentials[<span class="number">1</span>]){
      <span class="keyword">return</span> callback(<span class="keyword">new</span> journey.NotAuthorized(<span class="string">"Both username and password are required"</span>));
    }
    <span class="keyword">else</span> <span class="keyword">if</span>(credentials[<span class="number">0</span>] !== auth.username || credentials[<span class="number">1</span>] !== auth.password) {
      <span class="keyword">return</span> callback(<span class="keyword">new</span> journey.NotAuthorized(<span class="string">"Invalid username or password"</span>));
    }
    
    <span class="comment">// Respond with no error if username and password match</span>
    callback(<span class="literal">null</span>);
  }
};</code></pre></div>

</p>
<p>We can set this method on the Journey router by passing it in the options hash. Any routes that we wish to be behind the authentication filter need to be wrapped in a call to <code>map.filter(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span> ... })</code>

</p>
<p><div class="snippet"><pre><code>exports.createRouter = <span class="function"><span class="keyword">function</span> <span class="params">(resource)</span> {</span>
  <span class="keyword">return</span> <span class="keyword">new</span> (journey.Router)(<span class="function"><span class="keyword">function</span> <span class="params">(map)</span> {</span>
    <span class="comment">//</span>
    <span class="comment">// Resource: Bookmarks</span>
    <span class="comment">//</span>
    map.path(<span class="regexp">/\/bookmarks/</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
      <span class="comment">//</span>
      <span class="comment">// Authentication: Add a filter() method to perform HTTP Basic Auth</span>
      <span class="comment">//</span>
      map.filter(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
        <span class="comment">//</span>
        <span class="comment">// All of the previous routes we had go in here, but they</span>
        <span class="comment">// are now behind HTTP Basic Auth</span>
        <span class="comment">//</span>
      });
    });
  }, { 
    strict: <span class="literal">false</span>,
    filter: helpers.auth.basicAuth 
  });
};</code></pre></div>

</p>
<h1>Wrapping up</h1>
<p>Now that we have completed our web service, lets fire up http-console for an interactive session with our Bookmark resource.

</p>
<pre>
  $ http-console <a href="http://127.0.0.1:8000">http://127.0.0.1:8000</a>
  &gt; http-console 0.5.1
  &gt; Welcome, enter \help if you're lost.
  &gt; Connecting to 127.0.0.1 on port 8000.

  <a href="http://127.0.0.1:8000/&gt;">http://127.0.0.1:8000/&gt;</a> Authorization: Basic YWRtaW46cGFzc3dvcmQ
  <a href="http://127.0.0.1:8000/&gt;">http://127.0.0.1:8000/&gt;</a> \json
  <a href="http://127.0.0.1:8000/&gt;">http://127.0.0.1:8000/&gt;</a> \headers
  Accept: <em>/</em>
  Authorization: Basic YWRtaW46cGFzc3dvcmQ
  Content-Type: application/json
  <a href="http://127.0.0.1:8000/&gt;">http://127.0.0.1:8000/&gt;</a> POST /bookmarks
  ... { "url": "<a href="http://nodejs.org">http://nodejs.org</a>" }
  HTTP/1.1 200 OK
  Date: Sat, 05 Feb 2011 05:38:47 GMT
  Server: journey/0.3.0
  Content-Type: application/json
  Content-Length: 77
  Connection: close

  {
      bookmark: {
          url: '<a href="http://nodejs.org">http://nodejs.org</a>',
          _id: 'xnIgT8',
          resource: 'Bookmark'
      }
  }
  <a href="http://127.0.0.1:8000/&gt;">http://127.0.0.1:8000/&gt;</a> GET /bookmarks/xnIgT8
  HTTP/1.1 200 OK
  Date: Sat, 05 Feb 2011 05:39:01 GMT
  Server: journey/0.3.0
  Content-Type: application/json
  Content-Length: 121
  Connection: close

  {
      bookmark: {
          url: '<a href="http://nodejs.org">http://nodejs.org</a>',
          _id: 'xnIgT8',
          resource: 'Bookmark',
          _rev: '1-cfced13a45a068e95daa04beff562360'
      }
  }
  <a href="http://127.0.0.1:8000/&gt;">http://127.0.0.1:8000/&gt;</a> GET /bookmarks
  HTTP/1.1 200 OK
  Date: Sat, 05 Feb 2011 05:39:05 GMT
  Server: journey/0.3.0
  Content-Type: application/json
  Content-Length: 369
  Connection: close

  {
      bookmarks: [
          {
              _id: 'xnIgT8',
              _rev: '1-cfced13a45a068e95daa04beff562360',
              url: '<a href="http://nodejs.org">http://nodejs.org</a>',
              resource: 'Bookmark'
          }
      ]
  }
</pre>

<p>I hope this has been helpful for those of you looking to get started with <a href="http://nodejs.org">node.js</a>. Check out the rest of our blog for more advanced libraries and tutorials. Come back soon for more on the <a href="http://nodejitsu.com">Art of Nodejitsu</a>.
<br><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/a-simple-webservice-in-nodejs</link><guid isPermaLink="true">http://blog.nodejitsu.com/a-simple-webservice-in-nodejs</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Thu, 03 Feb 2011 17:22:52 GMT</pubDate></item><item><title><![CDATA[<a href="./most-active-nodejs-users">Most Active #node.js Users</a>]]></title><description><![CDATA[<p>Before trying any new technology, the first thing I do is try and find it's IRC room. If you don't know what IRC is, consider it a chat room for weird computer programmers. My first day trying node.js was also my first day in #node.js on irc.freenode.net. I was greeted by several friendly node enthusiasts and got lots of help getting my first node code working. Coincidentally, also on my first day, November 23, 2009, <a href="http://nodejs.debuggable.com/">Debuggable</a> starting running logs for #node.js. 

</p>
<p>In this article, I will dive into the #node.js log files, find out who the most active users are, and then follow their online handles to reveal who they are.

</p>
<h2> </h2>
<p><br>

</p>
<p><strong>Disclaimer: These stats should not be used for anything important. All data-sources and tools used to make this are available <a href="https://github.com/marak/node-stats">here</a>. <a href="#jump">Jump to the end</a>  of the article to learn how to crunch the numbers yourself.</strong>

</p>
<p><br>
<br>

</p>
<h1>Top 25 Most Active Users</h1>
<p>Here is a raw dump of the most active users in #node.js by line count

</p>
<style>
  .pisg {width:300px;}
  .pisg td{ padding-left:5px;padding-right:5px;padding-top:5px;padding-bottom:5px;}
</style>

<table class="pisg" border="0" width="200" style="background-color: #ccc;">
    <tbody>
        <tr>
            <td>
                &nbsp;</td>
            <td class="tdtop">
                <b>Nick</b></td>
            <td class="tdtop">
                <b>Number of lines</b></td>
        </tr>
        <tr>
            <td align="left" class="hirankc">
                1</td>
            <td style="background-color: rgb(186, 186, 220);">
                <span>JimBastard</span></td>
            <td style="background-color: rgb(186, 186, 220);">
                18011</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                2</td>
            <td style="background-color: rgb(187, 187, 219);">
                <span>isaacs</span></td>
            <td style="background-color: rgb(187, 187, 219);">
                17160</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                3</td>
            <td style="background-color: rgb(188, 188, 218);">
                <span>creationix</span></td>
            <td style="background-color: rgb(188, 188, 218);">
                15018</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                4</td>
            <td style="background-color: rgb(188, 188, 218);">
                <span>Micheil</span></td>
            <td style="background-color: rgb(188, 188, 218);">
                12119</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                5</td>
            <td style="background-color: rgb(189, 189, 217);">
                <span>mape</span></td>
            <td style="background-color: rgb(189, 189, 217);">
                9359</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                6</td>
            <td style="background-color: rgb(190, 190, 216);">
                <span>ryah</span></td>
            <td style="background-color: rgb(190, 190, 216);">
                9051</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                7</td>
            <td style="background-color: rgb(191, 191, 216);">
                <span>mikeal</span></td>
            <td style="background-color: rgb(191, 191, 216);">
                8884</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                8</td>
            <td style="background-color: rgb(191, 191, 215);">
                <span><em>ry</em></span></td>
            <td style="background-color: rgb(191, 191, 215);">
                7798</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                9</td>
            <td style="background-color: rgb(192, 192, 214);">
                <span>mscdex</span></td>
            <td style="background-color: rgb(192, 192, 214);">
                6752</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                10</td>
            <td style="background-color: rgb(193, 193, 214);">
                <span>inimino</span></td>
            <td style="background-color: rgb(193, 193, 214);">
                6146</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                11</td>
            <td style="background-color: rgb(193, 193, 213);">
                <span>felixge</span></td>
            <td style="background-color: rgb(193, 193, 213);">
                5540</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                12</td>
            <td style="background-color: rgb(194, 194, 212);">
                <span>mjr</span></td>
            <td style="background-color: rgb(194, 194, 212);">
                5202</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                13</td>
            <td style="background-color: rgb(195, 195, 212);">
                <span>sechrist</span></td>
            <td style="background-color: rgb(195, 195, 212);">
                4923</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                14</td>
            <td style="background-color: rgb(196, 196, 211);">
                <span>tmpvar</span></td>
            <td style="background-color: rgb(196, 196, 211);">
                4865</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                15</td>
            <td style="background-color: rgb(196, 196, 210);">
                <span><em>announcer</em></span></td>
            <td style="background-color: rgb(196, 196, 210);">
                4759</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                16</td>
            <td style="background-color: rgb(197, 197, 210);">
                <span>tjholowaychuk</span></td>
            <td style="background-color: rgb(197, 197, 210);">
                4737</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                17</td>
            <td style="background-color: rgb(198, 198, 209);">
                <span>elliottcable</span></td>
            <td style="background-color: rgb(198, 198, 209);">
                4710</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                18</td>
            <td style="background-color: rgb(198, 198, 208);">
                <span>maushu</span></td>
            <td style="background-color: rgb(198, 198, 208);">
                4493</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                19</td>
            <td style="background-color: rgb(199, 199, 208);">
                <span>Tim_Smart</span></td>
            <td style="background-color: rgb(199, 199, 208);">
                4332</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                20</td>
            <td style="background-color: rgb(200, 200, 207);">
                <span>JimBastard</span></td>
            <td style="background-color: rgb(200, 200, 207);">
                3479</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                21</td>
            <td style="background-color: rgb(201, 201, 206);">
                <span>polotek</span></td>
            <td style="background-color: rgb(201, 201, 206);">
                3459</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                22</td>
            <td style="background-color: rgb(201, 201, 206);">
                <span>hassox</span></td>
            <td style="background-color: rgb(201, 201, 206);">
                2455</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                23</td>
            <td style="background-color: rgb(202, 202, 205);">
                <span>cloudhead</span></td>
            <td style="background-color: rgb(202, 202, 205);">
                2402</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                24</td>
            <td style="background-color: rgb(203, 203, 204);">
                <span>technoweenie</span></td>
            <td style="background-color: rgb(203, 203, 204);">
                2394</td>
        </tr>
        <tr>
            <td align="left" class="rankc">
                25</td>
            <td style="background-color: rgb(204, 204, 204);">
                <span>ashb</span></td>
            <td style="background-color: rgb(204, 204, 204);">
                2331</td>
        </tr>
    </tbody>
</table>
<em>sexy colors courtesy of <a href="http://pisg.sourceforge.net/">pisg</a></em>

<br>


# Notable Top 25 Most Active Users

Part of what makes node.js great is it's community. The most active people in the #node.js IRC room are some of the most talented and prolific contributors to the project. I've taken the liberty to match up some of the most active online IRC handles to their real-life equivalents. The results are pretty amazing. 


<style>
  .stats{ width:600px;  border: 1px solid; padding:5px; border-width:1px;}
  .stats .header {background-color:#444444; color:white;}
  .stats td {padding-top:10px;padding-left:10px;padding-right:10px;padding-bottom:5px;}
  .even {background-color:#ccc;}
  .odd {background-color:#fff;}

</style>

<table class="stats">
  <tr class="header">
    <td width="150">Nick</td>
    <td width="120">Lines</td>
    <td width="200">Github</td>

  </tr>

  <tr>
    <td><strong>JimBastard</strong></td>
    <td>18011</td>
    <td><a href="http://github.com/marak"><a href="http://github.com/marak&lt;/a&gt;&lt;/td&gt;">http://github.com/marak&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Err...Marak Squires takes the #1 spot...that's me! I should talk less.
    </td>
  </tr>

  <tr class="even">
    <td><strong>isaacs</strong></td>
    <td>17160</td>
    <td> <a href="http://github.com/isaacs"><a href="http://github.com/isaacs&lt;/a&gt;&lt;/td&gt;">http://github.com/isaacs&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      Isaac Z. Schlueter. Author of <a href="http://npmjs.org">npm</a>, <a href="http://joyent.com">Joyent</a> Employee, Awesome Dude. Helped me on my first day in #node.js
    </td>
  </tr>

  <tr>
    <td><strong>creationix</strong></td>
    <td>15018</td>
    <td><a href="http://github.com/creationix"><a href="http://github.com/creationix&lt;/a&gt;&lt;/td&gt;">http://github.com/creationix&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Tim Caswell. Author of <a href="http://github.com/senchalabs/Connect">Connect</a>, owner of <a href="http://howtonode.org">howtonode.org</a>, prolific node.js developer. 
    </td>
  </tr>

  <tr class="even">
    <td><strong>Micheil</strong></td>
    <td>12119</td>
    <td> <a href="http://github.com/miksago"><a href="http://github.com/miksago&lt;/a&gt;&lt;/td&gt;">http://github.com/miksago&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      Micheil Smith. <a href="http://thechangelog.com">Changelog<a></a> contributor and module developer hailing from Australia. Super friendly and helpful. 
    </a></td>
  </tr>

  <tr>

    <td><strong>mape</strong></td>
    <td>9359</td>
    <td><a href="http://github.com/mape"><a href="http://github.com/mape&lt;/a&gt;&lt;/td&gt;">http://github.com/mape&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Mathias Pettersson, the unstoppable Swede. Winner of NodeKnockout ( several times over ). Author of several node.js modules.
    </td>
  </tr>

  <tr class="even">

    <td><strong>ryah</strong></td>
    <td>9051</td>
    <td> <a href="http://github.com/ry"><a href="http://github.com/ry&lt;/a&gt;&lt;/td&gt;">http://github.com/ry&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      Ryan Dahl. God-father of node. <a href="http://joyent.com">Joyent</a> employee. Created node.js and double rainbows. 
    </td>
  </tr>

  <tr>

    <td><strong>mikeal</strong></td>
    <td>8884</td>
    <td><a href="http://github.com/mikeal"><a href="http://github.com/mikeal&lt;/a&gt;&lt;/td&gt;">http://github.com/mikeal&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Mikeal Rodgers. <a href="http://couchone.com">CouchOne</a> employee. Apache developer. Old-school JavaScript Guru.
    </td>
  </tr>

  <tr class="even">

    <td><strong><em>ry</em></strong></td>
    <td>7798</td>
    <td> <a href="http://github.com/ry"><a href="http://github.com/ry&lt;/a&gt;&lt;/td&gt;">http://github.com/ry&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      Alternate handle for ryah
    </td>
  </tr>


  <tr>

    <td><strong>mscdex</strong></td>
    <td>6752</td>
    <td><a href="http://github.com/mscdex"><a href="http://github.com/mscdex&lt;/a&gt;&lt;/td&gt;">http://github.com/mscdex&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Brian White. Mysterious man. Builds really slick node.js libraries such as <a href="https://github.com/mscdex/node-ncurses">ncurses</a>  and <a href="https://github.com/mscdex/node-asterisk">asterix</a>. 
    </td>
  </tr>

  <tr class="even">

    <td><strong>inimino</strong></td>
    <td>6146</td>
    <td> <a href="http://inimino.org/~inimino/blog/"><a href="http://inimino.org/~inimino/blog/&lt;/a&gt;&lt;/td&gt;">http://inimino.org/~inimino/blog/&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      Expert JavaScript developer, wishes to remain anonymous.
    </td>
  </tr>

  <tr>

    <td><strong>felixge</strong></td>
    <td>5540</td>
    <td><a href="http://github.com/felixge"><a href="http://github.com/felixge&lt;/a&gt;&lt;/td&gt;">http://github.com/felixge&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Felix Geisendorfer. Owner of <a href="http://Debuggable.com">Debuggable</a>. Author of several node.js modules. Maintains the #node.js logs
    </td>
  </tr>

  <tr class="even">

    <td><strong>mjr</strong></td>
    <td>5202</td>
    <td> <a href="https://github.com/mranney"><a href="https://github.com/mranney&lt;/a&gt;&lt;/td&gt;">https://github.com/mranney&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      Matt Raney. Very tall, author of <a href="https://github.com/mranney/node_redis">node<em>redis.</em></a> 
    </td>
  </tr>

  <tr>

    <td><strong>tmpvar</strong></td>
    <td>4865</td>
    <td><a href="http://github.com/tmpvar"><a href="http://github.com/tmpvar&lt;/a&gt;&lt;/td&gt;">http://github.com/tmpvar&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Elijah Insua. <a href="http://nodejitsu.com">Nodejitsu</a> contributor. Author of <a href="http://jsdom.org">JSDOM</a> and several other node.js modules.
    </td>
  </tr>

  <tr class="even">

    <td><strong>tjholowaychuk</strong></td>
    <td>4737</td>
    <td> <a href="https://github.com/visionmedia"><a href="https://github.com/visionmedia&lt;/a&gt;&lt;/td&gt;">https://github.com/visionmedia&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      TJ Holowaychuk. Author of <a href="http://expressjs.com">ExpressJS</a> and <a href="http://github.com/senchalabs/Connect">Connect</a>. LearnBoost employee.
    </td>
  </tr>

  <tr>

    <td><strong>JimBastard</strong></td>
    <td>3479</td>
    <td><a href="http://github.com/marak"><a href="http://github.com/marak&lt;/a&gt;&lt;/td&gt;">http://github.com/marak&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Alternate account for JimBastard. 
    </td>
  </tr>

  <tr class="even">

    <td><strong>cloudhead</strong></td>
    <td>2402</td>
    <td> <a href="https://github.com/cloudhead"><a href="https://github.com/cloudhead&lt;/a&gt;&lt;/td&gt;">https://github.com/cloudhead&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      Alexis Sellier - Prolific node.js contributor. Author of <a href="http://VowsJS.org">VowsJS</a> and Cradle.
    </td>
  </tr>

  <tr>
    <td><strong>technoweenie</strong></td>
    <td>2394</td>
    <td><a href="http://github.com/technoweenie"><a href="http://github.com/technoweenie&lt;/a&gt;&lt;/td&gt;">http://github.com/technoweenie&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="4">
      Rick Olson - <a href="http://github.com">Github</a> Employee. Legendary Ruby on Rails developer. Possible super hero.
    </td>
  </tr>

</table>

<p><br>

</p>
<h1>Very Honorable Mentions</h1>
<p>There are a few irc room users who came very close to making the top 25 most active and definitely should be mentioned. Their contributions to node.js have been amazing and they didn't have to talk a lot about it. :-)

</p>
<p><br>


</p>
<table class="stats">
  <tr class="header">
    <td width="150">Nick</td>
    <td width="200">Line Count</td>
    <td>Github</td>

  </tr>

  <tr class="even">
    <td><strong>mde</strong></td>
    <td>1729</td>
    <td><a href="http://github.com/mde"><a href="http://github.com/mde&lt;/a&gt;&lt;/td&gt;">http://github.com/mde&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      Matthew Eernisse. Yammer employee. Author of geddy.
    </td>
  </tr>
  <tr>
    <td><strong>kriszyp</strong></td>
    <td>1571</td>
    <td><a href="http://github.com/kriszyp"><a href="http://github.com/kriszyp&lt;/a&gt;&lt;/td&gt;">http://github.com/kriszyp&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Kris Zyp. Uber JavaScript developer. Author of Persevere.
    </td>
  </tr>
  <tr class="even">
    <td><strong>sh1mmer</strong></td>
    <td>1481</td>
    <td><a href="http://github.com/sh1mmer"><a href="http://github.com/sh1mmer&lt;/a&gt;&lt;/td&gt;">http://github.com/sh1mmer&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
      Tom Hughes-Croucher. Community leader, author of several node.js modules.
    </td>
  </tr>
  <tr>
    <td><strong>pgriess</strong></td>
    <td>1397</td>
    <td><a href="http://github.com/pgriess"><a href="http://github.com/pgriess&lt;/a&gt;&lt;/td&gt;">http://github.com/pgriess&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
      Peter Griess. Facebook employee. Coder of hard-core node.js C stuff.
    </td>
  </tr>


  <tr class="even">
    <td><strong>SubStack &amp; pkrumins</strong></td>
    <td>1395 &amp; 1379</td>
    <td><a href="http://github.com/substack"><a href="http://github.com/substack&lt;/a&gt;&lt;br/&gt;&lt;a">http://github.com/substack&lt;/a&gt;&lt;br/&gt;&lt;a</a> href="<a href="http://github.com/pkrumins&quot;&gt;http://github.com/pkrumins&lt;/a&gt;&lt;/td&gt;">http://github.com/pkrumins"&gt;http://github.com/pkrumins&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr class="even">
    <td colspan="3">
       James Halliday &amp; Peteris Krumins.The <a href="http://stackvm.com/">StackVM</a> guys. They release a lot of software, a lot.
    </td>
  </tr>


  <tr>
    <td><strong>jashkenas</strong></td>
    <td>1299</td>
    <td><a href="http://github.com/jashkenas"><a href="http://github.com/jashkenas&lt;/a&gt;&lt;/td&gt;">http://github.com/jashkenas&lt;/a&gt;&lt;/td&gt;</a>
  </a></td></tr>
  <tr>
    <td colspan="3">
       Jeremy Ashkenas, JavaScript Zen Master. All lists must contain at least one instance of jashkenas. Author of <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a>, Backbone, and underscore to name a few.
    </td>
  </tr>

</table>

<p><br>

</p>
<h1>Crunching the numbers</h1>
<p><a name="jump"></a>
For those who are interested where these numbers came from...

</p>
<h2>Getting the logs</h2>
<p>To pull a copy of the #node.js logs from from <a href="http://nodejs.debuggable.com/">debuggable</a>, you can try this quick script I wrote <a href="https://github.com/marak/node-stats">here</a>. There are also copies of the log files in this repo.

</p>
<h2>Cleaning the logs</h2>
<p>I couldn't figure out what logging format was being used, so I wrote a quick script to convert the custom logging format into standard mIRC format ( which <a href="http://pisg.sourceforge.net/">pisg</a> can understand ). The clean log files are included in the <a href="https://github.com/marak/node-stats">node-stats repo</a>

</p>
<h2>Running PISG</h2>
<p>Use <a href="http://pisg.sourceforge.net/">Perl IRC Statistics Generator</a>. pisg is available for download here: <a href="http://pisg.sourceforge.net/index.php?page=download"><a href="http://pisg.sourceforge.net/index.php?page=download&lt;/a&gt;">http://pisg.sourceforge.net/index.php?page=download&lt;/a&gt;</a> Once you have pisg downloaded, you simply run the pisg command and specify the log file or path you want to use. 


</a></p>
<p><br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/most-active-nodejs-users</link><guid isPermaLink="true">http://blog.nodejitsu.com/most-active-nodejs-users</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Tue, 18 Jan 2011 10:24:36 GMT</pubDate></item><item><title><![CDATA[<a href="./put-your-logs-anywhere-with-winston">Put Your Logs Anywhere with Winston</a>]]></title><description><![CDATA[<p><strong>This is Part Two of a two part post on logging in node.js</strong> — In any language there are a lot of options when it comes to logging. The issue that we saw at Nodejitsu, was that all of these libraries coupled their storage mechanism of choice (files, databases, etc.) to the API that was exposed to the programmer. 

</p>
<p>This was the motivation behind <a href="http://github.com/indexzero/winston">winston</a>: a multi-transport logging library for node.js. A transport is essentially a storage device for your logs. Each instance of a winston logger can have multiple transports configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file.
<br><br>
</p>
<h2> </h2>
<h1>Getting Started with winston</h1>
<p>There is a robust amount of documentation for winston on the <a href="http://github.com/indexzero/winston">GitHub project page</a>. To get started you want to install winston using npm: 

</p>
<pre>
  npm install winston
</pre>

<p>Here is a quick summary of basic logging with winston. We'll require winston, configure it with two transports, and log some test data:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> winston = require(<span class="string">'winston'</span>);

winston.add(winston.transports.Riak, { level: <span class="string">'warn'</span> });

winston.add(winston.transports.File, { filename: <span class="string">'mylogfile.log'</span>, level: <span class="string">'silly'</span> });

<span class="comment">//</span>
<span class="comment">// Logging with no callback ('fire and forget')</span>
<span class="comment">//</span>
winston.log(<span class="string">'info'</span>, <span class="string">'127.0.0.1 - Theres no place like home'</span>);

<span class="comment">//</span>
<span class="comment">// Logging with a callback</span>
<span class="comment">//</span>
winston.log(<span class="string">'info'</span>, <span class="string">'127.0.0.1 - Theres no place like home'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, level, msg)</span> {</span>
  <span class="comment">// Do something once you've to all your transports</span>
});

<span class="comment">//</span>
<span class="comment">// Logging with level (info) specific methods</span>
<span class="comment">//</span>
winston.info(<span class="string">'127.0.0.1 - Theres no place like home'</span>);</code></pre></div>

</p>
<p><br>
</p>
<h1>"CHILL WINSTON! ... I put it in the logs"</h1>
<p>If you're curious about where the name 'winston' comes from, it's an homage to <a href="http://www.imdb.com/title/tt0120735/">Lock, Stock, and Two Smoking Barrels</a>. Really curious? <a href="http://www.youtube.com/watch?v=sGWEI390Pe8">Check out the video clip</a> (Definitely safe for work). 
<br><br>

</p>
<h1>Get to the Point Already!</h1>
<p>Winston boasts several important features:

</p>
<ol>
<li>Multiple transports configurable by level (console, file, riak, loggly)</li>
<li><em>[Coming Soon]</em> Configurable Logging Levels. Currently based loosely off <a href="https://github.com/isaacs/npm/blob/master/lib/utils/log.js#L27">npm</a> levels</li>
<li>Optional Logging of Metadata </li>
<li>Easy-to-use profiling of your node.js code</li>
<li>Extensible with Custom Transports</li>
<li>Evented logging with optional callbacks</li>
</ol>
<p>If any of this has perked your interest, check out the <a href="http://github.com/indexzero/winston">Github Project</a> for more documentation and sample usage. 
<br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/put-your-logs-anywhere-with-winston</link><guid isPermaLink="true">http://blog.nodejitsu.com/put-your-logs-anywhere-with-winston</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Mon, 17 Jan 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./logging-logs-and-loggly-in-nodejs">Logging, Logs, and Loggly in Node.js</a>]]></title><description><![CDATA[<p><strong>This is Part One of a two part post on logging in node.js</strong> — I think every developer has a love/hate relationship with their log files. They love them when they have to debug, optimize or fix a problem, but they hate setting them up and later distributing, aggregating and searching log files. There are a lot of utilities out there for managing your logs, but one caught our eye at Nodejitsu: <a href="http://loggly.com">Loggly</a>. That's why we're happy to announce the release of <a href="https://github.com/nodejitsu/node-loggly">node-loggly</a>: A library for interacting with the <a href="http://wiki.loggly.com/apidocumentation">Loggly API</a>. 
<br><br>
</p>
<h2> </h2>
<h1>Using node-loggly</h1>
<p>There is a robust amount of documentation for node-loggly on the <a href="https://github.com/nodejitsu/node-loggly">GitHub project page</a>. To get started you want to install node-loggly using npm: 

</p>
<pre>
  npm install loggly
</pre>

<p>Here is a quick summary of basic logging with node-loggly. We'll require loggly, configure it with an account, and log some test data:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> loggly = require(<span class="string">'loggly'</span>);
<span class="keyword">var</span> config = {
  subdomain: <span class="string">"your-subdomain"</span>,
  auth: {
    username: <span class="string">"your-username"</span>,
    password: <span class="string">"your-password"</span>
  }
};

<span class="keyword">var</span> client = loggly.createClient(config);

<span class="comment">//</span>
<span class="comment">// Logging with no callback ('fire and forget')</span>
<span class="comment">//</span>
client.log(<span class="string">'your-really-long-input-token'</span>, <span class="string">'127.0.0.1 - Theres no place like home'</span>);

<span class="comment">//</span>
<span class="comment">// Logging with a callback</span>
<span class="comment">//</span>
client.log(<span class="string">'your-really-long-input-token'</span>, <span class="string">'127.0.0.1 - Theres no place like home'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, result)</span> {</span>
  <span class="comment">// Do something once you've logged</span>
});
</code></pre></div>

</p>
<h1>Logging and Nodejitsu</h1>
<p>Last month Heroku announced <a href="http://blog.heroku.com/archives/2010/12/13/logging/">"Sweet Logging"</a> which perplexed me as to how their customers functioned before this feature. I wonder how they were able to manage their own log files without such a feature. Regardless, you can be sure that given our Loggly-backed infrastructure Nodejitsu users will be able to see logs for all applications and servers with ease from the start. 
<br><br>
</p>
<h1>What's next?</h1>
<p><strong>So why is this a two part post?</strong> Well we've been working on more than just the Loggly API. After taking a survey of the logging libraries available for node.js it was clear there was a missing link. Our interpretation of this missing link is a new multi-transport logging library: winston. A transport is essentially a storage device for your logs. Each instance of the winston logger can have multiple transports configured at different levels.We will be releasing winston in the next few days, so check back soon.
<br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/logging-logs-and-loggly-in-nodejs</link><guid isPermaLink="true">http://blog.nodejitsu.com/logging-logs-and-loggly-in-nodejs</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Thu, 13 Jan 2011 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./development-branding-and-4am-deli-sandwiches">Development, branding &amp; 4am deli sandwiches</a>]]></title><description><![CDATA[<p>Building Nodejitsu has been a lot like building a house, or a spaceship, or maybe even a synthetic super human. But let's use an analogy that everyone understands: it was kind of like building a house. The first step was to lay a solid foundation. In the same analogy, branding could be thought of as house paint, and house paint was the last thing on our minds.
<br><br>

</p>
<h2> </h2>
<h1>The Pledge</h1>
<p>We were focused on developing a tool-chain that addresses the problem space. Out of the first few dozen of 4am nights we spent developing none of it was spent on visual treatments. We did, however, have a great photo of Keanu Reaves:
<br><br>
</p>
<p><div class="center">
  <img src="development-branding-and-4am-deli-sandwiches/matrix-i-know-kung-fu.jpg">
  <div>i know nodejitsu.</div>
</div>
<br>
</p>
<h1>The Turn</h1>
<p>By about August when we competed in <a href="http://nodeknockout.com/teams/the-nyc-nodejitsu-ninjas">Node Knockout</a> we realized that our humorous splash page needed an update. We also realized that a lot of people were using <a href="http://github.com/nodejitsu/node-http-proxy">things</a> <a href="http://github.com/nodejitsu/node-cloudservers">we</a> <a href="http://github.com/indexzero/forever">had</a> <a href="http://nodejitsu.com">built</a> and we had done almost nothing to build on that branding opportunity. So with what limited bandwidth we had, we wrote a little bit of CSS and had a friend (and super talented cartoonist/designer <a href="http://chopsaki.com">James Novy</a>) draw a little ninja for us. We were so rushed that we didn't even have time to let James polish his sketch in Illustrator:
<br><br>
</p>
<p><div class="center">
  <img src="development-branding-and-4am-deli-sandwiches/nodejitsu-sketch.png">
</div>
<br>

</p>
<p>Things looked raw, it wasn't sexy, but it was a step towards something. This was also before we launched our private beta officially and we really just needed something that positioned text and spaced form elements properly. Eventually, we began to realize that we had a working product in our hands, and it needed to look presentable to the consumer. So with James' polished ninja character in hand we revised our design once more: 
<br><br>
</p>
<p><div class="center">
  <img src="commit-deploy-test-invite-release/nodejitsu-demo-1.png">
</div>
<br>
There are things that the above design did well: it was cleaner and more consistent. It was, however, also overly playful, loud, unfinished and lacked both depth and texture. For a company that offers first class scalable, fault tolerant cloud hosting for everyone from individuals and enterprises, loud and playful were not the most appropriate vocabulary to emphasize in the language of our brand.
<br><br>

</p>
<h1>The Prestige</h1>
<p><br>
</p>
<p><div class="center">
  <img src="development-branding-and-4am-deli-sandwiches/prestige-homepage.png">
  <div>The new Nodejitsu homepage</div>
  <br><br>
  <img src="development-branding-and-4am-deli-sandwiches/prestige-blog.png">
  <div>The new Nodejitsu blog</div>
</div>
<br>
When we went back to the drawing we thought a lot about what it means to write quality software and we came back one theme: that great code is craft (or even art). So our choice of the bonsai tree made sense: it represents a malleable, growing platform that can be crafted and to some could be considered <a href="http://www.artofbonsai.org/">art</a>. The typography and colors in the new design are more subtle, and the overall dark tone gives it a more professional look-and-feel. We also added more depth and texture to offset the flat finish of the graphics and type. This new design set the stage for an iconic brand that we are going to grow. For those of you concerned about the future of our ninja, he'll be around but in a less central capacity.
<br><br>

</p>
<h1>Wrapping up</h1>
<p>Branding and design in general is a topic far too large for a blog post (or even for one point of view), but we hope our journey at Nodejitsu will give some insight to you out there building your own brands. We're all developers here at Nodejitsu, so it's ironic that the biggest take away for us was something we already knew: just like good software, good design and branding is an iterative process. There will be iterations as we evolve, but they will be more about refinement than re-invention.
<br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/development-branding-and-4am-deli-sandwiches</link><guid isPermaLink="true">http://blog.nodejitsu.com/development-branding-and-4am-deli-sandwiches</guid><dc:creator><![CDATA[Paolo Fragomeni]]></dc:creator><pubDate>Wed, 05 Jan 2011 17:26:36 GMT</pubDate></item><item><title><![CDATA[<a href="./merry-christmas-heres-some-code">Merry Christmas: here's some code</a>]]></title><description><![CDATA[<p>Well it's that time of the year again and as the gifts are being given out I thought that it was time to give a gift of our own: a slew of updates to a few of our open source node.js libraries. There are some breaking changes in these updates, so check out the changelogs <a href="https://github.com/indexzero/forever/blob/master/CHANGELOG.md">here</a>, <a href="https://github.com/nodejitsu/node-cloudservers/blob/master/CHANGELOG.md">here</a>, and <a href="https://github.com/nodejitsu/node-cloudfiles/blob/master/CHANGELOG.md">here</a>. Also, you can read the rest of this post for a quick summary of what's new. <br><br>

</p>
<h2> </h2>
<h1>forever v0.3.1</h1>
<p>Forever has been getting a lot of attention since I wrote about it last month. With over half a dozen issues logged in Github, I felt it was time for some updating. Some of the big changes were to internals, but there are some notable changes for the cli, mangaging log files, and spawning non-node processes (thanks substack!):

</p>
<h2>Working with Logs</h2>
<p>'forever list' now displays the location of the logfile for that process:
</p>
<pre>
  $ forever start myscript.js
  $ forever start -l mylog.log myscript.js
  $ forever list
    <a href="https://github.com/indexzero/forever/blob/master/CHANGELOG.md">0</a> myscript.js  [24485, 24484] /tmp/forever/foreverYs3.log
    <a href="https://github.com/nodejitsu/node-cloudservers/blob/master/CHANGELOG.md">1</a> myscript.js  [24517, 24516] /tmp/forever/mylog.log
</pre>

<p>You can also cleanup old logfiles by using the 'cleanlogs' command, but be careful there is no going back from this:
</p>
<pre>
  $ forever cleanlogs
</pre>

<h2>Spawning Non-Node processes</h2>
<p>Thanks to a contribution from <a href="http://substack.net">substack</a> it is now possible to spawn non-node processes with forever via nodejs code, but not from the command line. Here's a simple example from the <a href="https://github.com/indexzero/forever/blob/master/test/forever-test.js#L64">tests</a>:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> child = forever.start([ <span class="string">'perl'</span>, <span class="string">'-le'</span>, <span class="string">'print "moo"'</span> ], {
  max: <span class="number">1</span>,
  silent: <span class="literal">true</span>,
});</code></pre></div>

</p>
<p>Here we are spawning a Perl process to print 'moo' with a maximum of one restart.

</p>
<h2>Stopping processes by script name from the CLI</h2>
<p>This has been a request since the day that I released forever v0.3.0 in that when I improved the CLI to allow for starting and stopping from the command-line, I decided to go with an index based system. This was because I couldn't decide on a good behavior for the following scenario:

</p>
<pre>
  $ forever start myapp.js
  $ forever start myapp.js
  $ forever list
    <a href="https://github.com/indexzero/forever/blob/master/CHANGELOG.md">0</a> myapp.js  [24485, 24484] /tmp/forever/foreverX2Y.log
    <a href="https://github.com/nodejitsu/node-cloudservers/blob/master/CHANGELOG.md">1</a> myapp.js  [24517, 24516] /tmp/forever/forever1e4.log
  $ forever stop myapp.js
</pre>

<p>Clearly in this scenario there are multiple instances of myapp.js running on the target system. What this will do no is stop <em>ALL</em> instances of myapp.js on the system so use with caution:

</p>
<pre>
  $ forever stop myapp.js
  Forever stopped processes:
    <a href="https://github.com/indexzero/forever/blob/master/CHANGELOG.md">0</a> myapp.js  [24485, 24484] /tmp/forever/foreverX2Y.log
    <a href="https://github.com/nodejitsu/node-cloudservers/blob/master/CHANGELOG.md">1</a> myapp.js  [24517, 24516] /tmp/forever/forever1e4.log<br></pre>

<h1>node-cloudfiles and node-cloudservers v0.2.0</h1>
<p>The changes to both of our <a href="http://rackspacecloud.com">Rackspace Cloud</a> libraries centered around a by-design issue <a href="https://github.com/nodejitsu/node-cloudfiles/issues/2">opened about 2 months ago</a>. That is previously by-design both libraries were designed to work with a single account at a time. This was just fine for our usage at Nodejitsu since we only run against either our test, dev, staging, or production environments in any given deployment, but didn't support for other scenarios. Here's a quick before and after for usage since these are breaking changes:
<br><br>
</p>
<h3>Before (0.1.x)</h3>
<pre>
  var cloudfiles = require('cloudfiles');
  var example = {
    auth : {
      username: 'your-username',
      apiKey: 'your-api-key'
    }
  };
  cloudfiles.setAuth(example.auth, function () {
    // Work with Rackspace Cloudfiles from here
  });
</pre>

<h3>After (0.2.x)</h3>
<pre>
  var cloudfiles = require('cloudfiles');
  var config = {
    auth : {
      username: 'your-username',
      apiKey: 'your-api-key'
    }
  };

  var client = cloudfiles.createClient(config);
  // Work with Rackspace Cloudfiles from here<br></pre>

<p>The above usage pattern is also the same in node-cloudservers 0.2.x as well as node-cloudfiles 0.2.x. Wanted to make sure that there was some consistency in our releases. So that's it for today, keep checking back: we'll be opening our beta up more in January 2011. 
<br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/merry-christmas-heres-some-code</link><guid isPermaLink="true">http://blog.nodejitsu.com/merry-christmas-heres-some-code</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Sat, 25 Dec 2010 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./keep-a-nodejs-server-up-with-forever">Keep a node.js server up with Forever</a>]]></title><description><![CDATA[<p>One of the great benefits of using node.js is the reduction in dependencies needed to run a production web application. By using the 'http' module we can run a stand-alone web server in node.js without the need for a separate server like Apache or nginx. The caveat of not having to use these servers is that their concerns are now the concerns of the node.js application developer. The concern that we will discuss in this article is that of fault tolerance, or how to automatically restart your server when it crashes or enters an invalid state. <br><br>

</p>
<h2> </h2>
<p>Before we dive into how to use Forever, lets setup the 'hello world' web server that we will later run with Forever. 

</p>
<p><div class="snippet"><pre><code><span class="identifier">var</span> <span class="identifier">util</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'util'</span>),    
    <span class="identifier">http</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'http'</span>);

<span class="identifier">http</span>.<span class="constant">createServer</span>(<span class="identifier">function</span> (<span class="identifier">req</span>, <span class="identifier">res</span>) {
  <span class="identifier">res</span>.<span class="constant">writeHead</span>(<span class="number">200</span>, {<span class="string">'Content-Type'</span><span class="symbol">:</span> <span class="string">'text/plain'</span>});
  <span class="identifier">res</span>.<span class="identifier"><span class="keymethods">write</span></span>(<span class="string">'hello, i know nodejitsu.'</span>)
  <span class="identifier">res</span>.<span class="identifier"><span class="keyword">end</span></span>();
}).<span class="identifier">listen</span>(<span class="number">8000</span>);

<span class="regexp">/* server started */</span>  
<span class="identifier">util</span>.<span class="identifier"><span class="keymethods">puts</span></span>(<span class="string">'&gt; hello world running on port 8000'</span>);</code></pre></div>

</p>
<p>The above code starts a web server that will respond to all requests with 'hello, i know nodejitsu'. Starting this server is easy:

</p>
<pre>
$ node simple-server.js
&gt; hello world running on port 8000
</pre>

<h1>Running in the background</h1>
<p>By simply running our server script with the 'node' command the server will start as a long running process (i.e. it will block the current shell until it crashes or is forced to exit with Ctrl-C). But what if we want to run this server in the background? The traditional approach is to run the command using nohup: 

</p>
<pre>
$ nohup node simple-server.js &gt; output.log &amp;
<a href="https://github.com/indexzero/forever">1</a> 23909
</pre>

<p>This will start our server process in the background and append all output to 'output.log'. Another approach is to start the script as a daemon using a library like <a href="https://github.com/indexzero/daemon.node">daemon.node</a>. I won't go into the details of using daemon.node, but the documentation on the <a href="https://github.com/indexzero/daemon.node">Github project page</a>. These two approaches solve the background problem, but what if we have a buggy server like the one below:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> util = require(<span class="string">'util'</span>),
    http = require(<span class="string">'http'</span>);

http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(req, res)</span> {</span>
  res.writeHead(<span class="number">200</span>, {<span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span>});
  res.write(<span class="string">'hello, i know nodejitsu.'</span>)
  res.end();
}).listen(<span class="number">8000</span>);

<span class="comment">/* server started */</span>  
util.puts(<span class="string">'&gt; hello world running on port 8000'</span>);

setTimeout(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  util.puts(<span class="string">'Throwing error now.'</span>);
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'User generated fault.'</span>);
}, <span class="number">5000</span>);</code></pre></div>

</p>
<p>This is a contrived example that will start a web server, then throw an unhandled exception after five seconds. If we were to run this script, either in the background or a long running process, it will not automatically restart when it crashes. 
<br><br>

</p>
<h1>Keeping it running with Forever</h1>
<p>The purpose of <a href="https://github.com/indexzero/forever">Forever</a> is to keep a child process (such as your node.js web server) running continuously and automatically restart it when it exits unexpectedly. It's worth mentioning that there are other tools written to accomplish this task in a more generic way for any program or programming language:
<br><br>

</p>
<ol>
<li>Monit: <a href="http://mmonit.com/monit/"><a href="http://mmonit.com/monit/">http://mmonit.com/monit/</a></a></li>
<li>Upstart: <a href="http://upstart.ubuntu.com/"><a href="http://upstart.ubuntu.com/">http://upstart.ubuntu.com/</a></a></li>
<li>Daemontools: <a href="http://cr.yp.to/daemontools.html"><a href="http://cr.yp.to/daemontools.html">http://cr.yp.to/daemontools.html</a></a></li>
<li>Launchtool: <a href="http://people.debian.org/~enrico/launchtool.html"><a href="http://people.debian.org/~enrico/launchtool.html">http://people.debian.org/~enrico/launchtool.html</a></a></li>
</ol>
<p><br>
Currently Forever is for running node.js scripts only, but this is something that may be changed in the future. Honestly, it's a one line fix <a href="https://github.com/indexzero/forever/blob/master/lib/forever.js#L356">here</a>, but I'm not sure if users want to put 'node' in-front of every command. Forever is used in production at <a href="http://nodejitsu.com">Nodejitsu</a> and we can confirm that since we deployed it on our servers a month ago, we have not needed to touch it at all. Forever exposes its functionality via a command line interface available after installation via <a href="http://github.com/isaacs/npm">npm</a>:

</p>
<pre>
[sudo] npm install forever
</pre>

<p>The usage options for Forever expose four simple command line tasks: start, stop, stopall, list:

</p>
<pre>
usage: forever [start | stop | stopall | list] [options] SCRIPT [script options]

options:
  start          start SCRIPT as a daemon
  stop           stop the daemon SCRIPT
  stopall        stop all running forever scripts
  list           list all running forever scripts
</pre>

<p>You can also use Forever as a long running process by omitting the 'start' option. With these tasks available, starting a nodejs script with Forever is simple:

</p>
<pre>
$ forever start simple-server.js
$ forever list
  <a href="https://github.com/indexzero/daemon.node">0</a> simple-server.js [ 24597, 24596 ]
</pre>

<p>The first command starts the 'simple-server.js' script in the background using <a href="https://github.com/indexzero/daemon.node">daemon.node</a> and returns control to the current shell process. The second command lists all processes running with Forever. The IDs after the script name are the process IDs of the target script and the forever daemon watching that script respectively. We can confirm this by looking at the process list ourselves:

</p>
<pre>
$ ps axl | grep node
  501 24596     1   0  31  0  Ss     ??    0:00.03 node /usr/local/bin/forever start simple-server.js
  501 24597 24412   0  31  0  S      ??    0:00.07 node simple-server.js
</pre>
<br>

# Stopping and restarting with Forever
To illustrate that Forever will automatically restart a child process that exits, lets kill the process ourselves:

<pre>
$ kill 24597
$ forever list
  <a href="https://github.com/indexzero/daemon.node">0</a> simple-server.js [ 24611, 24596 ]
</pre>

<p>As you can see the process ID of the target script 'simple-server.js' has changed from 24597 to 24611 indicating that a new process has been started by Forever. So our target script will run continuously, but how do we stop it? Stopping a process with Forever is simple from the command line. We simply need to pass the index for that process show from 'forever list':

</p>
<p><pre>
$ forever stop 0
Forever stopped process:
  <a href="https://github.com/indexzero/daemon.node">0</a> simple-server.js [ 24611, 24596 ]
</pre>
<br>

</p>
<h1>Additional Forever options</h1>
<p>There are some default options and configuration conventions that you should be aware of when using Forever:

</p>
<ol>
<li>Forever keeps track of running processes in *.fvr files that are placed in /tmp/forever/pids</li>
<li>Each Forever process will generate a unique log file placed in /tmp/forever/*.log</li>
<li>Unless otherwise specified, the output of the child process' stdout and stderr will be written to the above log file.</li>
</ol>
<p>More about these options are available from the <a href="https://github.com/indexzero/forever">Forever usage and documentation on Github</a>. Pull requests, suggestions and bug reports are welcome. 
<br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/keep-a-nodejs-server-up-with-forever</link><guid isPermaLink="true">http://blog.nodejitsu.com/keep-a-nodejs-server-up-with-forever</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Tue, 30 Nov 2010 17:22:52 GMT</pubDate></item><item><title><![CDATA[<a href="./sessions-and-cookies-in-node">sessions and cookies in node</a>]]></title><description><![CDATA[<p>Session management is a major piece of any serious web application. When building a site, it is likely you will want the ability to persist a user's identity over multiple requests without having to have them re-login again and again. A common method for persisting a user's login over multiple http requests, is called setting a "<a href="http://en.wikipedia.org/wiki/HTTP_cookie">cookie</a>". Now almost all web developers have some idea of what a cookie is, but in this article we will dive into the specifics of actually implementing a cookie / session persistence system from scratch in node.js through exploring the <a href="https://github.com/marak/session.js">session.js</a> library and the <a href="https://github.com/marak/response">response</a> library.

</p>
<h2> </h2>
<p><br>

</p>
<h1>Getting Started</h1>
<p>First, we are going to need some logic for implementing session management. Crack JavaScript developer <a href="http://inimino.org/">inimino</a>  was nice enough to release the following <a href="https://github.com/Marak/session.js/blob/master/lib/session.js">module</a>, so we will build on that. In this module, only one method is exported: "lookupOrCreate". If we dive into this method a little bit, we can see it takes two options, a request object and an options hash. 

</p>
<p>This "lookupOrCreate" method will inspect the headers of the incoming request object and determine if there is any value set for the cookie field ( note: the actual header name is "Set-Cookie", but node refers to this header as "cookie"). If lookupOrCreate finds a cookie, it will retrieve the session object from memory, else it will create a new session for that request. 

</p>
<p>Now, the tricky part here is that if we've created a new session, we need to set the cookie in the response header so the client knows it has a session. Unless we explicitly set a cookie in the response header, "lookupOrCreate" will never find your session cookie.

</p>
<p>To set the cookie in the http response you can do something like:

</p>
<pre><code> <span class="keyword">var</span> session = sessions.lookupOrCreate(request,{
   lifetime:<span class="number">604800</span>
 });

 response.writeHead(<span class="number">200</span>, {
   <span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span>, 
   <span class="string">'Set-Cookie'</span>, session.getSetCookieHeaderValue()
 });</code></pre>
<p>Even better then using response.write though, is using response.setHeader. This will not close the response, and allow for further manipulation down the request/response processing chain...kinda like a proper middle-ware!

</p>
<pre><code> response.setHeader('Set-Cookie', session.getSetCookieHeaderValue());</code></pre>
<h3>Note: You will need the <a href="https://github.com/marak/response">response</a> module for this to work, it should be pulled into core eventually.</h3>
<p><br>

</p>
<h1>Creating a super simple session middle-ware</h1>
<p>In node.js, an accepted standard for building middleware is the following:

</p>
<pre><code> <span class="function"><span class="keyword">function</span><span class="params">( request, response, callback)</span> {</span>

   <span class="comment">// perform some logic on the request or response objects</span>
   console.log(request.url);


   <span class="comment">// then fire our callback, and pass the request </span>
   <span class="comment">// and response objects down the chain</span>
   callback(request, response, <span class="function"><span class="keyword">function</span><span class="params">()</span>{</span>

   });

 }</code></pre>
<p>Following this standard, a "middle-ware" for node.js's httpServer is nothing but a function that accepts three arguments: a request object, a response object, and a callback. Building on this very simple convention, we can implement de-coupled layers of middleware, each with its own responsibility. In our case, our middleware will be responsible for establishing sessions!

</p>
<p><br>
</p>
<h1><a href="https://github.com/marak/session.js">get session.js!</a></h1>
<p><br>


</p>
<h1>Using session.js as a middle-ware</h1>
<p><div class="snippet"><pre><code><span class="keyword">var</span> http = require(<span class="string">'http'</span>), 
    session = require(<span class="string">'./lib/core'</span>).session;

<span class="comment">// let's create a basic http server!</span>
http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(request, response)</span> {</span>

  <span class="comment">// before we process any part of the request, let's use the session middle-ware!</span>
  session(request, response, <span class="function"><span class="keyword">function</span><span class="params">(request, response)</span>{</span>

    <span class="comment">// now we can access request.session</span>

    <span class="comment">// after the session middleware has executed, let's finish processing the request</span>
    response.writeHead(<span class="number">200</span>, {<span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span>});
    response.write(<span class="string">'request.session: \n'</span> + JSON.stringify(request.session, <span class="number">2</span>, <span class="literal">true</span>));
    response.end();

  });

}).listen(<span class="number">8080</span>);

<span class="comment">/* server started */</span>  
console.log(<span class="string">'&gt; hello world running on port 8080'</span>);</code></pre></div>

</p>
<p><br>

</p>
<h1>Magic Monkey Punched Middle-ware Sessions (automatically patches httpServer)</h1>
<sessions-and-cookies-in-node>

<p><br>

</p>
<h1>Creating a super simple login / logout feature</h1>
<p>One of the best things about having a persistent session object per user, is having the ability to create user logins. The actual way you want to implement your login is somewhat arbitrary. Here is a basic pattern to follow. Please, remember this method is just an example:

</p>
<p><div class="snippet"><pre><code>    <span class="keyword">var</span> http = require(<span class="string">'http'</span>),
        session = require(<span class="string">'./lib/core'</span>).magicSession();

    <span class="comment">// let's create a basic http server!</span>
    http.createServer(<span class="function"><span class="keyword">function</span> <span class="params">(request, response)</span> {</span>

      <span class="comment">// please note: this is just an example of how to hook auth into session.js, its not ideal at all</span>

      <span class="comment">// super basic logout</span>
      <span class="keyword">if</span>(request.url === <span class="string">'/logout'</span>){
        request.session.data.user = <span class="string">"Guest"</span>;
        response.writeHead(<span class="number">200</span>, {<span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span>});
        response.write(<span class="string">'You\'ve been logged out'</span>);
        response.end();
        <span class="keyword">return</span>;
      }

      <span class="comment">// let's hardcode a username and password variable into the url</span>
      <span class="keyword">var</span> urlParams = require(<span class="string">'url'</span>).parse(request.url, <span class="literal">true</span>).query || {};

      <span class="keyword">if</span>(<span class="keyword">typeof</span> urlParams.name != <span class="string">'undefined'</span>){
        <span class="comment">// if the "name" parameter has been sent, lets log in as that user</span>
        request.session.data.user = urlParams.name;
      }
  
      <span class="comment">// request.session.data.user always defaults to "Guest"</span>
      <span class="keyword">if</span>(request.session.data.user == <span class="string">"Guest"</span>){
        response.writeHead(<span class="number">200</span>, {<span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span>});
        response.write(<span class="string">'Hello, you are the Guest user'</span>);
        response.end();
      }
      <span class="keyword">else</span>{
        response.writeHead(<span class="number">200</span>, {<span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span>});
        response.write(<span class="string">'Hello, you are '</span> + request.session.data.user);
        response.end();
      }


    }).listen(<span class="number">8080</span>);

    <span class="comment">/* server started */</span>  
    console.log(<span class="string">'&gt; hello world running on port 8080'</span>);</code></pre></div>


</p>
<p>Once you have this running you can do the following:

</p>
<pre><code>GET http:<span class="comment">//l</span>ocalhost:<span class="number">8080</span>/
<span class="comment">// </span>returns: Hello, you are the Guest user

GET http:<span class="comment">//l</span>ocalhost:<span class="number">8080</span>/?name=Marak
<span class="comment">// </span>returns: Hello, you are Marak

GET http:<span class="comment">//l</span>ocalhost:<span class="number">8080</span>/
<span class="comment">// </span>returns: Hello, you are Marak

GET http:<span class="comment">//l</span>ocalhost:<span class="number">8080</span>/logout
<span class="comment">// </span>returns: You've been logged out

GET http:<span class="comment">//l</span>ocalhost:<span class="number">8080</span> 
<span class="comment">// </span>returns: Hello, you are the Guest user</code></pre>
<p>Huzaah! There you go! <a href="https://github.com/marak/session.js">session.js</a> is open-source, so lets get hacking!


</p>
</sessions-and-cookies-in-node>]]></description><link>http://blog.nodejitsu.com/sessions-and-cookies-in-node</link><guid isPermaLink="true">http://blog.nodejitsu.com/sessions-and-cookies-in-node</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Fri, 26 Nov 2010 06:12:00 GMT</pubDate></item><item><title><![CDATA[<a href="./commit-deploy-test-invite-release">Commit, Deploy, Test, Invite, Release</a>]]></title><description><![CDATA[<p>After countless test servers, long nights of coding and a <a href="https://github.com/nodejitsu/node-http-proxy">laundry</a> <a href="https://github.com/nodejitsu/node-cloudservers">list</a> of <a href="https://github.com/nodejitsu/node-cloudfiles">open</a> <a href="https://github.com/nodejitsu/kyuri">source</a> <a href="https://github.com/nodejitsu/prenup">projects</a> the Nodejitsu private beta is officially live. It is a welcome coincidence that today is the 20th anniversary of the World Wide Web because we believe that node.js is the future of the web and web development. We are excited to share this initial look into our product.
<br>
</p>
<h2> </h2>
<p>Here's a few screenshot(s) of what it's like to deploy an application with Nodejitsu:

</p>
<p><img src="commit-deploy-test-invite-release/nodejitsu-demo-1.png" alt="">

</p>
<p><em>Selecting where to get source code</em>


</p>
<p><img src="commit-deploy-test-invite-release/nodejitsu-demo-2.png" alt="">

</p>
<p><em>Configuring a node.js application</em>


</p>
<p><img src="commit-deploy-test-invite-release/nodejitsu-demo-3.png" alt="">

</p>
<p><em>Starting, stopping, and restarting like woah</em>


</p>
<p>I'm sure a lot of people reading this article are thinking to themselves: "boo, another private beta for node.js hosting!" Trust us, we feel the same way! For now, however, we need time to test the platform with a manageable number of beta users so we can get it ready for prime time. There's a lot on our roadmap, but keep your eyes peeled for:

</p>
<ol>
<li>Heuristic-based elastic process scaling</li>
<li>Simple git based workflow</li>
<li>A bigger and better marketplace of open source node.js applications </li>
<li>Command-line interface for working with our API(s)</li>
<li>More awesome features we haven't thought of yet!</li>
</ol>
<p>Looking for a way to get to the top of the private beta invite list? We believe in rewards for <em>merit based contributions to the node.js community</em>. So do something awesome, then send us an email or find us on Twitter.

</p>
<p>Check back soon for more Nodejitsu announcements. This is only the beginning!

</p>
]]></description><link>http://blog.nodejitsu.com/commit-deploy-test-invite-release</link><guid isPermaLink="true">http://blog.nodejitsu.com/commit-deploy-test-invite-release</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Thu, 11 Nov 2010 10:24:36 GMT</pubDate></item><item><title><![CDATA[<a href="./sending-emails-in-node">sending emails in node</a>]]></title><description><![CDATA[<p>Sending emails is a classic software development problem. At some point, your application will need to send an email to someone. node.js has the ability to open arbitrary tcp sockets, so with <a href="https://github.com/marak/node_mailer">node_mailer</a>, we can easily connect to an existing <a href="http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol">SMTP</a> server and start sending out emails.

</p>
<p><br>

</p>
<h2> </h2>
<p>First, you need to install the <a href="https://github.com/marak/node_mailer">node_mailer</a>. You can find the installation instructions here: <a href="https://github.com/marak/node_mailer"><a href="https://github.com/Marak/node\_">https://github.com/Marak/node\_</a> mailer</a>. Once you have node_mailer installed it's really easy to start blasting emails from your node.js scripts.


</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> email = require(<span class="string">'mailer'</span>);

email.send({
  host : <span class="string">"localhost"</span>,              <span class="comment">// smtp server hostname</span>
  port : <span class="string">"25"</span>,                     <span class="comment">// smtp server port</span>
  domain : <span class="string">"localhost"</span>,            <span class="comment">// domain used by client to identify itself to server</span>
  to : <span class="string">"marak.squires@gmail.com"</span>,
  from : <span class="string">"obama@whitehouse.gov"</span>,
  subject : <span class="string">"node_mailer test email"</span>,
  body: <span class="string">"Hello! This is a test of the node_mailer."</span>,
  authentication : <span class="string">"login"</span>,        <span class="comment">// auth login is supported; anything else is no auth</span>
  username : <span class="string">"dXNlcm5hbWU="</span>,       <span class="comment">// Base64 encoded username</span>
  password : <span class="string">"cGFzc3dvcmQ="</span>        <span class="comment">// Base64 encoded password</span>
},
<span class="function"><span class="keyword">function</span><span class="params">(err, result)</span>{</span>
  <span class="keyword">if</span>(err){ console.log(err); }
});</code></pre></div>

</p>
<p>This snippet assumes you have a locally running <a href="http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol">SMTP</a> server. <a href="http://www.sendmail.com/sm/open_source/download/">sendmail</a> is a decent choice for a local <a href="http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol">SMTP</a> server, but you can't exactly just start firing off emails from any server or machine and expect it not to go straight into your user's spam box. 

</p>
<p>Modern email providers such as Gmail or Yahoo Mail have spam filters which will flag any sketchy looking emails. If you try to send email from a random home connection or Virtual Private Server, it will probably go straight into the spam box. Setting up a proper SMTP server with things such as <a href="http://en.wikipedia.org/wiki/Sender_Policy_Framework">SPF</a> records is not exactly trivial. 

</p>
<p><br>
</p>
<h3>You want to build an application, not manage an email server!</h3>
<p>Fortunately, there are services which provide trusted SMTP servers, such as <a href="http://sendgrid.com">sendgrid</a>. Using sendgrid we can easily connect to a remote SMTP server and begin pumping out emails. Once you are using a SMTP that is not on your localhost, you will most likely need to use some sort of authorization. luckily, node_mailer supports basic authentication!

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> email = require(<span class="string">'mailer'</span>);

email.send({
  host: <span class="string">"smtp.sendgrid.net"</span>,
  port : <span class="string">"25"</span>,
  domain: <span class="string">"smtp.sendgrid.net"</span>,
  authentication: <span class="string">"login"</span>,
  username: (<span class="keyword">new</span> Buffer(<span class="string">"myAccountName"</span>)).toString(<span class="string">"base64"</span>),
  password: (<span class="keyword">new</span> Buffer(<span class="string">"myPassword"</span>)).toString(<span class="string">"base64"</span>),
  to : <span class="string">"marak.squires@gmail.com"</span>,
  from : <span class="string">"test@mydomain.com"</span>,
  subject : <span class="string">"node_mailer test email"</span>,
  body : <span class="string">"hello this a test email from the node_mailer"</span>,
  <span class="function"><span class="keyword">function</span><span class="params">(err, result)</span>{</span>
    <span class="keyword">if</span>(err){ console.log(err); }
  });
</code></pre></div>

</p>
<h1>But wait! Let's do some templating!</h1>
<p>If you want to start sending more then a simple body for the email, you are going to start collecting some gnarly string concatenation statements in your email.send() code. Fortunately, as of version 0.4.0, node_mailer supports basic JSON replacement Mustache templating!

</p>
<h2>First, create your sampleTemplate.txt</h2>
<p><div class="snippet"><pre><code><span class="constant">Hello</span> {{<span class="identifier">username</span>}}, 

<span class="constant">This</span> <span class="identifier">is</span> <span class="identifier">a</span> <span class="identifier">sample</span> <span class="identifier">template</span> <span class="identifier">of</span> <span class="identifier">the</span> <span class="identifier">node</span> <span class="identifier">mailer</span>.

<span class="constant">It</span> <span class="identifier">uses</span> <span class="identifier">mustache</span> <span class="identifier">templating</span> <span class="identifier">to</span> <span class="identifier"><span class="keyword">do</span></span> <span class="identifier">basic</span> <span class="identifier">search</span> <span class="identifier"><span class="keyword">and</span></span> <span class="identifier">replaces</span>. 

<span class="constant">The</span> {{<span class="identifier">color</span>}} {{<span class="identifier">animal</span>}} {{<span class="identifier">adjective</span>}} <span class="identifier">ran</span> <span class="identifier">over</span> <span class="identifier">the</span> {{<span class="identifier">noun</span>}}.</code></pre></div>

</p>
<h2>Then, call email.send() using the following syntax:</h2>
<p><div class="snippet"><pre><code><span class="keyword">var</span> email = require(<span class="string">"./lib/node_mailer"</span>);

email.send({
  host : <span class="string">"localhost"</span>,              <span class="comment">// smtp server hostname</span>
  port : <span class="string">"25"</span>,                     <span class="comment">// smtp server port</span>
  domain : <span class="string">"localhost"</span>,            <span class="comment">// domain used by client to identify itself to server</span>
  to : <span class="string">"marak.squires@gmail.com"</span>,
  from : <span class="string">"obama@whitehouse.gov"</span>,
  subject : <span class="string">"node_mailer test email"</span>,
  template : <span class="string">"sampleTemplate.txt"</span>,   <span class="comment">// path to template name</span>
  data : {
    <span class="string">"username"</span>: <span class="string">"Billy Bob"</span>,
    <span class="string">"color"</span>: <span class="function"><span class="keyword">function</span><span class="params">()</span>{</span>
      <span class="keyword">var</span> arr = [<span class="string">"purple"</span>, <span class="string">"red"</span>, <span class="string">"green"</span>, <span class="string">"yello"</span>];
      <span class="keyword">return</span> arr[Math.floor(Math.random()*<span class="number">3</span>)];
    },
    <span class="string">"animal"</span>: <span class="string">"monkey"</span>,
    <span class="string">"adjective"</span>: <span class="string">"quickly"</span>,
    <span class="string">"noun"</span>: <span class="string">"hot lava"</span>
  },

  authentication : <span class="string">"login"</span>,        <span class="comment">// auth login is supported; anything else is no auth</span>
  username : <span class="string">"dXNlcm5hbWU="</span>,       <span class="comment">// Base64 encoded username</span>
  password : <span class="string">"cGFzc3dvcmQ="</span>       <span class="comment">// Base64 encoded password</span>
},
<span class="function"><span class="keyword">function</span><span class="params">(err, result)</span>{</span>
  <span class="keyword">if</span>(err){ console.log(err); }
});

</code></pre></div>

</p>
<h2>Your email body will now look something like this:</h2>
<p><div class="snippet"><pre><code><span class="constant">Hello</span> <span class="constant">Billy</span> <span class="constant">Bob</span>, 
<span class="constant">This</span> <span class="identifier">is</span> <span class="identifier">a</span> <span class="identifier">sample</span> <span class="identifier">template</span> <span class="identifier">of</span> <span class="identifier">the</span> <span class="identifier">node</span> <span class="identifier">mailer</span>.
<span class="constant">It</span> <span class="identifier">uses</span> <span class="identifier">mustache</span> <span class="identifier">templating</span> <span class="identifier">to</span> <span class="identifier"><span class="keyword">do</span></span> <span class="identifier">basic</span> <span class="identifier">search</span> <span class="identifier"><span class="keyword">and</span></span> <span class="identifier">replaces</span>. 
<span class="constant">The</span> <span class="identifier">red</span> <span class="identifier">monkey</span> <span class="identifier">quickly</span> <span class="identifier">ran</span> <span class="identifier">over</span> <span class="identifier">the</span> <span class="identifier">hot</span> <span class="identifier">lava</span>.
</code></pre></div>

</p>
<p>Huzaah! There you go! <a href="https://github.com/marak/node_mailer">node_mailer</a> is open-source, so lets get hacking!


</p>
]]></description><link>http://blog.nodejitsu.com/sending-emails-in-node</link><guid isPermaLink="true">http://blog.nodejitsu.com/sending-emails-in-node</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Sat, 06 Nov 2010 06:12:00 GMT</pubDate></item><item><title><![CDATA[<a href="./most-influential-github-users-by-location">most influential github users by location</a>]]></title><description><![CDATA[<p>With over a million members, there is an amazing pool of open-source developers on <a href="http://github.com/">Github</a> across a wide range of projects. More amazing is how Github has changed the technical recruiting game. The day's of resumes and references for developers are slowly dying. All the work I've gotten in the past year has been a direct result of my github account. I send potential employers my Github account first. They can see a history of the work I have done, the influence that work has had (followers / forks), and my coding style and abilities. Github introduces a transparency that has never been available before.  

</p>
<p>In my ongoing obsession of finding top tier developers I came across <a href="http://www.hackdiary.com/2010/02/10/algorithmic-recruitment-with-github/">an article</a> by Matt Biddulph called "algorithmic recruitment with github". He released some basic code for calculating the social influence of a user based on a geo-graphical location. I immediately was hooked. I got the code running with a few minor modifications and ran: <b>"New York"</b>

</p>
<h3>the top 5...</h3>
<ol>
<li><a href="http://github.com/thoughtbot">thoughtbot</a></li>
<li><a href="http://github.com/nakajima">nakajima</a></li>
<li><a href="http://github.com/webiest">webiest</a></li>
<li><a href="http://github.com/marak">marak</a></li>
<li><a href="http://github.com/enormego">enormego</a></li>
</ol>
<p>Awesome! I placed 4th, but I noticed <a href="http://github.com/jashkenas">jashkenas</a> was missing from the list. I had figured he would have placed in the top five as well...

</p>
<p>I decided further research was required and ran the script against the following locations: Chicago, Boston, California, San Francisco, Los Angeles, San Diego, San Jose, Palo Alto, Portland, Oakland, Seattle, Florida, Alaska, Montreal, Toronto, Canada, Russia, Moscow, Ukraine, Uruguay, Chile, Japan, Taiwan, Korea, India, China, Israel, Argentina, Brazil, England, London, Germany, Spain, France, Switzerland, Sweden, Australia, New Zealand

</p>
<h2> </h2>
<p>The results were interesting. I cross referenced as many of the regions that I could with various irc people and saw somewhat consistent results. The issue with not seeing jashkenas in "New York" is simple. His location is listed as "NYC", so the "New York" query didn't find him. The same normalization issue occurs for many regions and winds up excluding potentially influential developers from the graph. I also saw what I could consider "artificial" influence by accounts who were simply following large amounts of people (such as <a href="http://github.com/webiest">webiest</a>). 

</p>
<p>The solutions to fix these issues are relatively straight forward.

</p>
<p>To fix the normalization issues there are two options. We could ask Github to change the location field on profiles so it could be geo-coded (unlikely to happen anytime soon) or we could manually setup aliases for each region and then change the script to perform an OR operation on these aliases. For instance to calculate the graph for New York we could query "New York, NYC, New York City, Brooklyn, Queens, Manhattan, Staten Island". I suppose we could also just try to take the current location string and geocode it. The point is there is room for improvement.

</p>
<p>To fix the results being skewed by people who just happen to follow a lot of projects, we could change the script to take other information into account such as: number of projects, number of watchers on projects, following to followers ratio, fork to ownership ratio, commit history. There is also an issue of legacy organizations and organizations having followers...but that one is a bit tricky. 

</p>
<p>The current code is written in Ruby and I'm thinking the next version will try to use <a href="http://rubyeventmachine.com/">event-machine</a> to speed up the synchronous net requests or maybe just try and port the whole thing to node. Once there are more accurate results I'll publish the entire list for each region. If you want to try this on your own, you can try <a href="http://github.com/mattb/flotsam/tree/master/github-recruitment/">here</a> or <a href="http://gist.github.com/608869">here</a>

</p>
<h1>The Results</h1>
<p>New York

</p>
<ol>
<li><a href="http://github.com/thoughtbot">thoughtbot</a></li>
<li><a href="http://github.com/nakajima">nakajima</a></li>
<li><a href="http://github.com/webiest">webiest</a></li>
<li><a href="http://github.com/marak">marak</a></li>
<li><a href="http://github.com/enormego">enormego</a></li>
</ol>
<p>Chicago

</p>
<ol>
<li><a href="http://github.com/dhh">dhh</a></li>
<li><a href="http://github.com/alex">alex</a></li>
<li><a href="http://github.com/josh">josh</a></li>
<li><a href="http://github.com/dchelimsky">dchelimsky</a></li>
<li><a href="http://github.com/sstephenson">sstephenson</a></li>
</ol>
<p>Boston

</p>
<ol>
<li><a href="http://github.com/jeresig">jeresig</a></li>
<li><a href="http://github.com/qrush">qrush</a></li>
<li><a href="http://github.com/migueldeicaza">migueldeicaza</a></li>
<li><a href="http://github.com/pluginaweek">pluginaweek</a></li>
<li><a href="http://github.com/bestpractical">bestpractical</a></li>
</ol>
<p>California 

</p>
<ol>
<li><a href="http://github.com/yahoo">yahoo</a></li>
<li><a href="http://github.com/brandonkelly">brandonkelly</a></li>
<li><a href="http://github.com/kohsuke">kohsuke</a></li>
<li><a href="http://github.com/nesquena">nesquena</a></li>
<li><a href="http://github.com/mde">mde</a></li>
</ol>
<p>San Francisco

</p>
<ol>
<li><a href="http://github.com/wycats">wycats</a></li>
<li><a href="http://github.com/tmm1">tmm1</a></li>
<li><a href="http://github.com/280north">280north</a></li>
<li><a href="http://github.com/fauna">fauna</a></li>
<li><a href="http://github.com/bradfitz">bradfitz</a></li>
</ol>
<p>Los Angeles 

</p>
<ol>
<li><a href="http://github.com/courtenay">courtenay</a></li>
<li><a href="http://github.com/jashmenn">jashmenn</a></li>
<li><a href="http://github.com/citrusbyte">citrusbyte</a></li>
<li><a href="http://github.com/deadprogrammer">deadprogrammer</a></li>
<li><a href="http://github.com/chergert">chergert</a></li>
</ol>
<p>San Diego

</p>
<ol>
<li><a href="http://github.com/sdboyer">sdboyer</a></li>
<li><a href="http://github.com/svanzoest">svanzoest</a></li>
<li><a href="http://github.com/mgutz">mgutz</a></li>
<li><a href="http://github.com/TheCodeBoutique">TheCodeBoutique</a></li>
<li><a href="http://github.com/nclark">nclark</a></li>
</ol>
<p>San Jose

</p>
<ol>
<li><a href="http://github.com/chriseppstein">chriseppstein</a></li>
<li><a href="http://github.com/rhomobile">rhomobile</a></li>
<li><a href="http://github.com/kohsuke">kohsuke</a></li>
<li><a href="http://github.com/hasimo">hasimo</a></li>
<li><a href="http://github.com/neror">neror</a></li>
</ol>
<p>Palo Alto

</p>
<ol>
<li><a href="http://github.com/creationix">creationix</a></li>
<li><a href="http://github.com/extjs">extjs</a></li>
<li><a href="http://github.com/enormego">enormego</a></li>
<li><a href="http://github.com/charlenopires">charlenopires</a></li>
<li><a href="http://github.com/romac">romac</a></li>
</ol>
<p>Oakland

</p>
<ol>
<li><a href="http://github.com/isaacs">isaacs</a></li>
<li><a href="http://github.com/byrnereese">byrnereese</a></li>
<li><a href="http://github.com/jayallen">jayallen</a></li>
<li><a href="http://github.com/mikeal">mikeal</a></li>
<li><a href="http://github.com/substack">substack</a></li>
</ol>
<p>Portland

</p>
<ol>
<li><a href="http://github.com/Caged">Caged</a></li>
<li><a href="http://github.com/leto">leto</a></li>
<li><a href="http://github.com/schwern">schwern</a></li>
<li><a href="http://github.com/webiest">webiest</a></li>
<li><a href="http://github.com/courtenay">courtenay</a></li>
</ol>
<p>Seattle

</p>
<ol>
<li><a href="http://github.com/opscode">opscode</a></li>
<li><a href="http://github.com/jbarnette">jbarnette</a></li>
<li><a href="http://github.com/entangledstate">entangledstate</a></li>
<li><a href="http://github.com/zenspider">zenspider</a></li>
<li><a href="http://github.com/elliottcable">elliottcable</a></li>
</ol>
<p>Florida

</p>
<ol>
<li><a href="http://github.com/igorgue">igorgue</a></li>
<li><a href="http://github.com/ptony82">ptony82</a></li>
<li><a href="http://github.com/RayRacine">RayRacine</a></li>
<li><a href="http://github.com/mobileAgent">mobileAgent</a></li>
<li><a href="http://github.com/dennis2008">dennis2008</a></li>
</ol>
<p>Alaska

</p>
<ol>
<li><a href="http://github.com/elliottcable">elliottcable</a></li>
<li><a href="http://github.com/substack">substack</a></li>
<li><a href="http://github.com/camflan">camflan</a></li>
<li><a href="http://github.com/mcroydon">mcroydon</a></li>
<li><a href="http://github.com/dayne">dayne</a></li>
</ol>
<p>Montreal

</p>
<ol>
<li><a href="http://github.com/cloudhead">cloudhead</a></li>
<li><a href="http://github.com/garyharan">garyharan</a></li>
<li><a href="http://github.com/marcandre">marcandre</a></li>
<li><a href="http://github.com/plank">plank</a></li>
<li><a href="http://github.com/stinie">stinie</a></li>
</ol>
<p>Toronto

</p>
<ol>
<li><a href="http://github.com/pauldowman">pauldowman</a></li>
<li><a href="http://github.com/camwest">camwest</a></li>
<li><a href="http://github.com/scottboms">scottboms</a></li>
<li><a href="http://github.com/joshbuddy">joshbuddy</a></li>
<li><a href="http://github.com/heycarsten">heycarsten</a></li>
</ol>
<p>Canada

</p>
<ol>
<li><a href="http://github.com/igrigorik">igrigorik</a></li>
<li><a href="http://github.com/visionmedia">visionmedia</a></li>
<li><a href="http://github.com/ujihisa">ujihisa</a></li>
<li><a href="http://github.com/johnboxall">johnboxall</a></li>
<li><a href="http://github.com/lestrrat">lestrrat</a></li>
</ol>
<p>Russia

</p>
<ol>
<li><a href="http://github.com/yaroslav">yaroslav</a></li>
<li><a href="http://github.com/svetlyak40wt">svetlyak40wt</a></li>
<li><a href="http://github.com/isagalaev">isagalaev</a></li>
<li><a href="http://github.com/superfeedr">superfeedr</a></li>
<li><a href="http://github.com/shergin">shergin</a></li>
</ol>
<p>Moscow

</p>
<ol>
<li><a href="http://github.com/svetlyak40wt">svetlyak40wt</a></li>
<li><a href="http://github.com/yaroslav">yaroslav</a></li>
<li><a href="http://github.com/sergeche">sergeche</a></li>
<li><a href="http://github.com/NV">NV</a></li>
<li><a href="http://github.com/isagalaev">isagalaev</a></li>
</ol>
<p>Ukraine

</p>
<ol>
<li><a href="http://github.com/kpumuk">kpumuk</a></li>
<li><a href="http://github.com/piranha">piranha</a></li>
<li><a href="http://github.com/webiest">webiest</a></li>
<li><a href="http://github.com/playpauseandstop">playpauseandstop</a></li>
<li><a href="http://github.com/svetlyak40wt">svetlyak40wt</a></li>
</ol>
<p>Uruguay

</p>
<ol>
<li><a href="http://github.com/foca">foca</a></li>
<li><a href="http://github.com/rfletcher">rfletcher</a></li>
<li><a href="http://github.com/cacciaresi">cacciaresi</a></li>
<li><a href="http://github.com/myabc">myabc</a></li>
<li><a href="http://github.com/mtodd">mtodd</a></li>
</ol>
<p>Chile

</p>
<ol>
<li><a href="http://github.com/sagmor">sagmor</a></li>
<li><a href="http://github.com/narwen">narwen</a></li>
<li><a href="http://github.com/pvalencia">pvalencia</a></li>
<li><a href="http://github.com/michelson">michelson</a></li>
<li><a href="http://github.com/cadcc">cadcc</a></li>
</ol>
<p>Japan

</p>
<ol>
<li><a href="http://github.com/kakutani">kakutani</a></li>
<li><a href="http://github.com/darashi">darashi</a></li>
<li><a href="http://github.com/fujimoto">fujimoto</a></li>
<li><a href="http://github.com/k1LoW">k1LoW</a></li>
<li><a href="http://github.com/hsbt">hsbt</a></li>
</ol>
<p>Taiwan

</p>
<ol>
<li><a href="http://github.com/xdite">xdite</a></li>
<li><a href="http://github.com/lukhnos">lukhnos</a></li>
<li><a href="http://github.com/itszero">itszero</a></li>
<li><a href="http://github.com/ericsk">ericsk</a></li>
<li><a href="http://github.com/rainly">rainly</a></li>
</ol>
<p>Korea

</p>
<ol>
<li><a href="http://github.com/JEEN">JEEN</a></li>
<li><a href="http://github.com/ToePeu">ToePeu</a></li>
<li><a href="http://github.com/saillinux">saillinux</a></li>
<li><a href="http://github.com/xover">xover</a></li>
<li><a href="http://github.com/kleinweby">kleinweby</a></li>
</ol>
<p>India

</p>
<ol>
<li><a href="http://github.com/piyush">piyush</a></li>
<li><a href="http://github.com/binnyva">binnyva</a></li>
<li><a href="http://github.com/swaroopch">swaroopch</a></li>
<li><a href="http://github.com/nileshtrivedi">nileshtrivedi</a></li>
<li><a href="http://github.com/becomingGuru">becomingGuru</a></li>
</ol>
<p>China

</p>
<ol>
<li><a href="http://github.com/agentzh">agentzh</a></li>
<li><a href="http://github.com/huacnlee">huacnlee</a></li>
<li><a href="http://github.com/lonre">lonre</a></li>
<li><a href="http://github.com/samx2">samx2</a></li>
<li><a href="http://github.com/yongsun">yongsun</a></li>
</ol>
<p>Israel

</p>
<ol>
<li><a href="http://github.com/shevron">shevron</a></li>
<li><a href="http://github.com/dibaunaumh">dibaunaumh</a></li>
<li><a href="http://github.com/DominikGuzei">DominikGuzei</a></li>
<li><a href="http://github.com/ido50">ido50</a></li>
<li><a href="http://github.com/jbaruch">jbaruch</a></li>
</ol>
<p>Argentina

</p>
<ol>
<li><a href="http://github.com/miloops">miloops</a></li>
<li><a href="http://github.com/abecciu">abecciu</a></li>
<li><a href="http://github.com/apillet">apillet</a></li>
<li><a href="http://github.com/kragen">kragen</a></li>
<li><a href="http://github.com/Gazer">Gazer</a></li>
</ol>
<p>Brazil

</p>
<ol>
<li><a href="http://github.com/peleteiro">peleteiro</a></li>
<li><a href="http://github.com/claus">claus</a></li>
<li><a href="http://github.com/rafaelss">rafaelss</a></li>
<li><a href="http://github.com/loiane">loiane</a></li>
<li><a href="http://github.com/charlenopires">charlenopires</a></li>
</ol>
<p>England

</p>
<ol>
<li><a href="http://github.com/SteveMarshall">SteveMarshall</a></li>
<li><a href="http://github.com/mmower">mmower</a></li>
<li><a href="http://github.com/simonmaddox">simonmaddox</a></li>
<li><a href="http://github.com/atl">atl</a></li>
<li><a href="http://github.com/myelin">myelin</a></li>
</ol>
<p>London

</p>
<ol>
<li><a href="http://github.com/mrdoob">mrdoob</a></li>
<li><a href="http://github.com/maccman">maccman</a></li>
<li><a href="http://github.com/codepo8">codepo8</a></li>
<li><a href="http://github.com/mxcl">mxcl</a></li>
<li><a href="http://github.com/mattb">mattb</a></li>
</ol>
<p>Germany

</p>
<ol>
<li><a href="http://github.com/jezdez">jezdez</a></li>
<li><a href="http://github.com/dbloete">dbloete</a></li>
<li><a href="http://github.com/webiest">webiest</a></li>
<li><a href="http://github.com/beberlei">beberlei</a></li>
<li><a href="http://github.com/schorsch">schorsch</a></li>
</ol>
<p>Spain

</p>
<ol>
<li><a href="http://github.com/javier">javier</a></li>
<li><a href="http://github.com/AD7six">AD7six</a></li>
<li><a href="http://github.com/tyru">tyru</a></li>
<li><a href="http://github.com/antoniogarrote">antoniogarrote</a></li>
<li><a href="http://github.com/christkv">christkv</a></li>
</ol>
<p>France

</p>
<ol>
<li><a href="http://github.com/n1k0">n1k0</a></li>
<li><a href="http://github.com/penso">penso</a></li>
<li><a href="http://github.com/fdv">fdv</a></li>
<li><a href="http://github.com/philogb">philogb</a></li>
<li><a href="http://github.com/oz">oz</a></li>
</ol>
<p>Switzerland

</p>
<ol>
<li><a href="http://github.com/greut">greut</a></li>
<li><a href="http://github.com/0xced">0xced</a></li>
<li><a href="http://github.com/camptocamp">camptocamp</a></li>
<li><a href="http://github.com/cosimo">cosimo</a></li>
<li><a href="http://github.com/lsmith77">lsmith77</a></li>
</ol>
<p>Sweden

</p>
<ol>
<li><a href="http://github.com/joearms">joearms</a></li>
<li><a href="http://github.com/henrik">henrik</a></li>
<li><a href="http://github.com/tinymce">tinymce</a></li>
<li><a href="http://github.com/voxpelli">voxpelli</a></li>
<li><a href="http://github.com/charlenopires">charlenopires</a></li>
</ol>
<p>Australia 

</p>
<ol>
<li><a href="http://github.com/toolmantim">toolmantim</a></li>
<li><a href="http://github.com/newism">newism</a></li>
<li><a href="http://github.com/mnot">mnot</a></li>
<li><a href="http://github.com/xaviershay">xaviershay</a></li>
<li><a href="http://github.com/anthonyshort">anthonyshort</a></li>
</ol>
<p>New Zealand

</p>
<ol>
<li><a href="http://github.com/parndt">parndt</a></li>
<li><a href="http://github.com/KieranP">KieranP</a></li>
<li><a href="http://github.com/jhulten">jhulten</a></li>
<li><a href="http://github.com/fujin">fujin</a></li>
<li><a href="http://github.com/nzjrs">nzjrs</a></li>
</ol>
]]></description><link>http://blog.nodejitsu.com/most-influential-github-users-by-location</link><guid isPermaLink="true">http://blog.nodejitsu.com/most-influential-github-users-by-location</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Sun, 03 Oct 2010 09:27:00 GMT</pubDate></item><item><title><![CDATA[<a href="./create-nodejs-web-services-in-one-line">create node.js web-services in one line</a>]]></title><description><![CDATA[<p><strong>UPDATE: Due to high demand, webservice.js is now under active development. You should also visit the <a href="http://github.com/marak/webservice.js">Github</a> to get the latest documentation code</strong>

</p>
<p>Creating easy to consume <a href="http://en.wikipedia.org/wiki/Web_service">web-services</a> is a common problem in modern day computer science. Many web developers have had some experience either creating a web-service or building a client to consume a web-service (such as the <a href="http://apiwiki.twitter.com/">Twitter API</a>). 

</p>
<p>Using a <a href="http://nodejs.org">node.js</a> router like <a href="http://github.com/cloudhead/journey">Journey</a>, we can easily define maps for a basic JSON web-service. We can hard-code a few routes, assign each one a different request handler, and then write integration tests between our new Journey router and our business logic.  The problem with this approach, is that it requires writing a lot of code, which requires a lot of development time.

</p>
<p>If we enforce some very reasonable conventions and draw on a concept from <a href="http://en.wikipedia.org/wiki/ColdFusion">Coldfusion</a>, we can start creating robust web-services with one line of code.

</p>
<h2> </h2>
<h1>Coldfusion?!?!</h1>
<p>Yes, <em>sigh</em> <a href="http://en.wikipedia.org/wiki/ColdFusion">Coldfusion</a>. Before my days as a JavaScript developer I spent a lot of time in this wonderfully simple scripting language for the <a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine">JVM</a>,  called Coldfusion. Coldfusion had "Coldfusion Components", or CFCs. A CFC was a simple way to encapsulate methods into an object. One of the more interesting properties of a CFC was it's ability to expose <a href="http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_f_21.html">methods</a> inside any CFC as "remote". This would allow the CFC method to be viewed directly over HTTP as a web-service. CFC's were exposed with nice auto-generate documentation and could work using multiple formats like XML, JSON, and WDDX.

</p>
<p><br>

</p>
<h1>Bringing the old and busted into the node and js</h1>
<p>Building on the idea of exposing objects as turn-key web-services... 

</p>
<p><strong>We make the following assumptions...</strong>

</p>
<ul>
<li>every node.js module has a name</li>
<li>node.js modules export methods</li>
<li>exported methods take an options hash as the first argument</li>
<li>exported methods take a callback as the last argument</li>
</ul>
<p>Based on these assumptions, we can start turning node.js modules into web-services in seconds.

</p>
<p><br>

</p>
<h1>webservice.js</h1>
<p><a href="http://github.com/marak/webservice.js">webservice.js</a> is a node.js module that creates RESTFul web-services based on other node.js modules. 

</p>
<p>First, install webservice.js from npm.

</p>
<pre><code> npm install webservice</code></pre>
<p>Creating a web-service is very simple. In a previous version of this article, I showed how to expose the native fs module as an unprotected web-service. It was a neat proof of concept, but I've taken it down since no one should actually directly expose any of the native node modules. 

</p>
<p><br>
Instead, here is a server that uses a demo module:

</p>
<create-nodejs-web-services-in-one-line>

<p>Now that we have created a basic web-service, let's start it up.

</p>
<pre><code> node server.js </code></pre>
<p>Now there is a web-service running on port 8080. One of the nice things webservice.js does for you, is create its own documentation. 

</p>
<p>If we go to:  <a href="http://localhost:8080/docs"><a href="http://localhost:8080/docs">http://localhost:8080/docs</a></a>, we will see a description of our web-service

</p>
<p><img src="create-nodejs-web-services-in-one-line/htmlView.png" style="float: none;">

</p>
<p>Another great feature is that we can return any documentation page as JSON by appending .json to the end of the request. 

</p>
<p>If we visit <a href="http://localhost:8080/docs.json"><a href="http://localhost:8080/docs.json">http://localhost:8080/docs.json</a></a> we will see a listing of all our web-service methods as JSON (photo cropped).

</p>
<p><img src="create-nodejs-web-services-in-one-line/jsonView.png" style="float: none;">

</p>
<p><br>
</p>
<h1>Invoking web-service methods</h1>
<p>Now that our web-service is running and we have an idea of how it's structured, we can invoke a simple method that will echo a msg.

</p>
<pre><code>curl -X GET http:<span class="comment">//l</span>ocalhost:<span class="number">8080</span>/<span class="keyword">echo</span>?msg=hello</code></pre>
<p>Since HTTP verbs are relaxed, we can also do this:

</p>
<pre><code>curl -X POST -d <span class="string">"msg=hello"</span> http:<span class="comment">//l</span>ocalhost:<span class="number">8080</span>/<span class="keyword">echo</span></code></pre>
<p><br>
<a name="custom"></a>
</p>
<h1>creating custom web-services</h1>
<p>Creating custom web-services is very simple. There is more documentation available <a href="http://github.com/marak/webservice.js">on github</a>, but the basic design strategy is as follows:

</p>
<p><div class="snippet"><pre><code><span class="comment">// demo module</span>
<span class="keyword">this</span>.title = <span class="string">"Welcome to your webservice!"</span>;
<span class="keyword">this</span>.name = <span class="string">"demo api module"</span>;
<span class="keyword">this</span>.version = <span class="string">"0.1.0"</span>;
<span class="keyword">this</span>.endpoint = <span class="string">"http://localhost:8080"</span>;

exports.echo = <span class="function"><span class="keyword">function</span><span class="params">(options, callback)</span>{</span>
  callback(<span class="literal">null</span>, options.msg);
};
exports.echo.description = <span class="string">"this is the echo method, it echos back your msg"</span>;
exports.echo.schema = {
  msg: { 
    type: <span class="string">'string'</span>,
    optional: <span class="literal">false</span> 
  }
};

exports.ping = <span class="function"><span class="keyword">function</span><span class="params">(options, callback)</span>{</span>
  setTimeout(<span class="function"><span class="keyword">function</span><span class="params">()</span>{</span>
    callback(<span class="literal">null</span>, <span class="string">'pong'</span>);
  }, <span class="number">2000</span>);
}
exports.ping.description = <span class="string">"this is the ping method, it pongs back after a 2 second delay"</span>;

</code></pre></div>

</p>
<p>Now we make a simple server file that will create the web-service for our custom module. Notice I left in the FS module. This is to illustrate how to use multiple modules in one web-service. You can specify as many modules as you'd like, granted they all have unique labels.

</p>
<p><div class="snippet"><pre><code><span class="identifier">var</span> <span class="identifier">webservice</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'./lib/webservice'</span>),
    <span class="constant">demoModule</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'./examples/demoModule'</span>);

<span class="identifier">webservice</span>.<span class="constant">createServer</span>(<span class="constant">demoModule</span>).<span class="identifier">listen</span>(<span class="number">8080</span>);
<span class="identifier">console</span>.<span class="identifier">log</span>(<span class="string">' &gt; json webservice started on port 8080'</span>);  
</code></pre></div>

</p>
<p>and to invoke methods over HTTP...

</p>
<pre><code> <span class="identifier">curl</span> <span class="identifier">http</span><span class="symbol">:</span>/<span class="regexp">/localhost:8080/demo</span><span class="regexp">/echo/hello</span>
 <span class="string">"hello"</span>

 <span class="identifier">curl</span> <span class="identifier">http</span><span class="symbol">:</span>/<span class="regexp">/localhost:8080/demo</span><span class="regexp">/ping/async</span>
 (<span class="identifier">waits</span> <span class="number">3</span> <span class="identifier">seconds</span>)
 <span class="string">"pong"</span></code></pre>
<h1>summary</h1>
<p>There are a lot of interesting options to explore when building node.js services. Having the ability to seamlessly expose modules as web-services seems like a powerful concept and I look forward to trying to build on it in the future. <a href="http://github.com/marak/webservice.js">pull requests</a> are always welcome.

</p>
<p><strong> ninja out! </strong>

</p>
</create-nodejs-web-services-in-one-line>]]></description><link>http://blog.nodejitsu.com/create-nodejs-web-services-in-one-line</link><guid isPermaLink="true">http://blog.nodejitsu.com/create-nodejs-web-services-in-one-line</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Fri, 24 Sep 2010 15:24:36 GMT</pubDate></item><item><title><![CDATA[<a href="./using-sys-inherits-in-node-js">Using sys.inherits in node.js</a>]]></title><description><![CDATA[<p>Whatever your opinion of prototypical inheritance in javascript, from a marco level it is clearly important when one  considers DRY throughout a given codebase. The node.js 'sys' module exposes a simple way of accomplishing inheritance through sys.inherits. In this article we will explore how this method works and how you can use it to create more robust and modular code in nodejs. 

</p>
<h2> </h2>
<p>Let's take a look at the code from <a href="http://github.com/ry/node/blob/master/lib/sys.js#L386">core</a>:

</p>
<p><div class="snippet"><pre><code>exports.inherits = <span class="function"><span class="keyword">function</span> <span class="params">(ctor, superCtor)</span> {</span>
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
            value: ctor,
            enumerable: <span class="literal">false</span>
        }
    });
};</code></pre></div>

</p>
<p>At a high level, what this method does is set the prototype of the subclass ('ctor') to a new instance of the prototype of the super class ('superCtor'). 

</p>
<p><br>
</p>
<h1>Developing with sys.inherits</h1>
<p>Using sys.inherits in your own code is relatively simple. Let's explore this using a simple node example:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> sys = require(<span class="string">'sys'</span>),
    events = require(<span class="string">'events'</span>);

<span class="keyword">var</span> MyClass = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  events.EventEmitter.call(<span class="keyword">this</span>);
  <span class="comment">// Put your constructor logic here</span>
};

sys.inherits(MyClass, events.EventEmitter);

exports.MyClass = MyClass;</code></pre></div>

</p>
<p>What the above code does is create a new object 'MyClass' that inherits from the node.js core EventEmitter prototype. What this means is that anytime we require 'my-module' we can create a new instance of MyClass and use it just as we would use an EventEmitter instance. Here's a quick sample:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> sys = require(<span class="string">'sys'</span>),
    myModule = require(<span class="string">'./my-module'</span>);

<span class="keyword">var</span> emitter = <span class="keyword">new</span> myModule.MyClass();
emitter.on(<span class="string">'myevent'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  sys.puts(<span class="string">'myevent was raised'</span>);
});

emitter.emit(<span class="string">'myevent'</span>);</code></pre></div>

</p>
<p><br>
</p>
<h1>Gotchas for sys.inherits</h1>
<p>When declaring object prototypes in javascript, there are two distinct approaches: set the prototype as a single JSON object, or set the properties of the prototype individually. While I personally view the former as more stylistically pleasing when reading code, the latter is the approach that must be employed when using sys.inherits. This is because sys.inherits sets the entire prototype of the 'subclass'. Here's an illustrative example:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> sys = require(<span class="string">'sys'</span>),
    events = require(<span class="string">'events'</span>);

<span class="keyword">var</span> MyClass = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  events.EventEmitter.call(<span class="keyword">this</span>);
  <span class="comment">// Put your constructor logic here</span>
};

sys.inherits(MyClass, events.EventEmitter);

MyClass.prototype = {
  myMethod: <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    sys.puts(<span class="string">"Calling myMethod..."</span>);
  }
};

exports.MyClass = MyClass;</code></pre></div>

</p>
<p>In the above code the lines 'MyClass.prototype = { (...) }' overrides the prototype that is set by the preceding call to sys.inherits. The preferred implementation would be: 

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> sys = require(<span class="string">'sys'</span>),
    events = require(<span class="string">'events'</span>);

<span class="keyword">var</span> MyClass = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  events.EventEmitter.call(<span class="keyword">this</span>);
  <span class="comment">// Put your constructor logic here</span>
};

sys.inherits(MyClass, events.EventEmitter);

MyClass.prototype.myMethod = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  sys.puts(<span class="string">"Calling myMethod..."</span>);
}

exports.MyClass = MyClass;</code></pre></div>

</p>
<p>In the latter example you can see that we set the property 'myMethod' of the 'MyClass' prototype explicitly, there by avoiding overriding the prototype that is set by the call to sys.inherits.
<br><br>

</p>
<h1>Wrapping up</h1>
<p>There has been some discussion on the <a href="http://groups.google.com/group/nodejs/browse_thread/thread/1bea235c53df8289/dec3ebcdc171cba5?#dec3ebcdc171cba5">node.js mailing list</a> regarding deprecating or removing sys.inherits, but the consensus has been that it will remain since it is used throughout node.js core, mostly to inherit from events.EventEmitter (see <a href="http://github.com/ry/node/blob/master/lib/child_process.js#L158">here</a>, <a href="http://github.com/ry/node/blob/master/lib/http.js#L727">here</a>, and <a href="http://github.com/ry/node/blob/master/lib/net.js#L545">here</a> for some examples). I hope that this has been helpful for you and your development efforts using <a href="http://nodejs.org">node.js</a>.

</p>
<p><br>
<em>UPDATE:</em> The 'sys' module has been renamed to 'util' in node versions above 0.3.0
<br>
<br>

</p>
]]></description><link>http://blog.nodejitsu.com/using-sys-inherits-in-node-js</link><guid isPermaLink="true">http://blog.nodejitsu.com/using-sys-inherits-in-node-js</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Tue, 21 Sep 2010 17:22:52 GMT</pubDate></item><item><title><![CDATA[<a href="./nodejs-cloud-server-in-three-minutes">node.js cloud server in three minutes</a>]]></title><description><![CDATA[<p>A question that often comes up to me is: 'How do I get started with Node.js?' The first step is to setup your local developer environment, which is a little different depending on your platform of choice:

</p>
<ul>
<li>Linux: <a href="http://www.codediesel.com/linux/installing-node-js-on-ubuntu-10-04/">Installing Node.js on Ubuntu 10.04</a></li>
<li>Mac OS X: <a href="http://www.devpatch.com/2010/02/installing-node-js-on-os-x-10-6/">Installing Node.js on OS X 10.6</a></li>
<li>Windows: <a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2010/09/07/getting-started-with-node-js-on-windows.aspx">How I got started with Node.js on Windows</a>
<br>
<br></li>
</ul>
<h2> </h2>
<h1>Installing npm and node-cloudservers</h1>
<p>Once you've got that going it would be a good idea to install <a href="http://github.com/isaacs/npm">npm</a> (the node package manager). I'm currently running a mix of OS X and Ubuntu; so if you're using Windows, just checkout the <a href="http://github.com/isaacs/npm">npm GitHub repository</a> for more detailed install instructions.

</p>
<pre>
  curl <a href="http://npmjs.org/install.sh">http://npmjs.org/install.sh</a> | sudo sh
</pre>

<p>To work with the <a href="http://www.rackspacecloud.com/1469-0-3-13.html">Rackspace CloudServers</a> <a href="http://docs.rackspacecloud.com/servers/api/cs-devguide-latest.pdf">API</a> we will be using a library that I've recently completed called <a href="http://github.com/nodejitsu/node-cloudservers">node-cloudservers</a>. Installing node-cloudservers is easy using npm:

</p>
<pre>
  sudo npm install cloudservers
</pre>

<h1>Creating a server with node-cloudservers</h1>
<p>Ok, it's time to create our first server. If you haven't already done so, now would be a good time to create your <a href="http://www.rackspacecloud.com/1469-0-3-13.html">Rackspace</a>, account and get your username and api key.

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> cloudservers = require(<span class="string">'cloudservers'</span>),
    sys = require(<span class="string">'sys'</span>);

<span class="function"><span class="keyword">function</span> <span class="title">createServer</span><span class="params">(serverName, username, apiKey)</span> {</span>
  <span class="keyword">var</span> options = {
    name: serverName,
    image: <span class="number">49</span>, <span class="comment">// Ubuntu 10.04 (Lucid Lynx)</span>
    flavor: <span class="number">1</span>, <span class="comment">// 256 server</span>
  };

  cloudservers.setAuth({ username: username, apiKey: apiKey }, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    cloudservers.createServer(options, <span class="function"><span class="keyword">function</span> <span class="params">(err, server)</span> {</span>
      server.setWait({ status: <span class="string">'ACTIVE'</span> }, <span class="number">5000</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
        <span class="comment">// Our server is now built and active, so we can install node.js on it</span>
        sys.puts(<span class="string">'Your server '</span> + serverName + <span class="string">' is now ready.'</span>);
        sys.puts(<span class="string">'  IP Address: '</span> + server.addresses.public);
        sys.puts(<span class="string">'  Root password: '</span> + server.adminPass);
      });
    });
  });
};

<span class="keyword">var</span> args = process.argv.slice(<span class="number">2</span>);
<span class="keyword">var</span> serverName = args[<span class="number">0</span>];
<span class="keyword">var</span> username = args[<span class="number">1</span>] || <span class="string">'your-username'</span>;
<span class="keyword">var</span> apiKey = args[<span class="number">2</span>] || <span class="string">'your-api-key'</span>;

createServer(serverName, username, apiKey);</code></pre></div>


</p>
<p>The above code sample authenticates with <a href="http://www.rackspacecloud.com/1469-0-3-13.html">Rackspace CloudServers</a>, creates a server with the specified options, and then waits for that server to become active and then outputs the servers public IP address and root password to the console. If you're looking for more documentation about all of the api calls available through node-cloudservers, check out our <a href="http://github.com/nodejitsu/node-cloudservers">GitHub repository</a>. You can either update the file with your username / API key pair or enter it from the command line:

</p>
<pre>
  $ node create-server.js my-server my-username my-api-key
  Your server test-server is now ready.
    IP Address: 1.2.3.4
    Root password: my-server12345
</pre>

<h1>Installing Node.js programmatically</h1>
<p>We will be installing node.js on a Ubuntu 10.04 (Lucid Lynx) server that we just programmatically created. Now that the server is active we will execute the following shell script programmatically to get node installed along with npm and startup a 'hello node' server on that instance using <a href="http://en.wikipedia.org/wiki/Nohup">nohup</a>:

</p>
<p><div class="snippet"><pre><code>apt-get update
apt-get install git-core build-essential libssl-dev
cd /usr/src
git clone http:<span class="comment">//g</span>ithub.com/ry/node.git
cd node
./configure
make
make install
curl http:<span class="comment">//n</span>pmjs.org/install.sh | sh
cd /usr/src
git clone git:<span class="comment">//g</span>ithub.com/Marak/hellonode.git
cd hellonode
nohup node server.js
</code></pre></div>

</p>
<p>The easiest way to do this is to just spawn the ssh process using node. Here is some rudimentary code to do this using the <a href="http://nodejs.org/api.html#child-processes-89">node.js Child Process API</a>.

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> spawn = require(<span class="string">'child_process'</span>).spawn,
     fs = require(<span class="string">'fs'</span>),
     sys = require(<span class="string">'sys'</span>);

 <span class="function"><span class="keyword">function</span> <span class="title">ssh</span><span class="params">(username, host, file)</span> {</span>
   fs.readFile(file, <span class="function"><span class="keyword">function</span> <span class="params">(err, data)</span> {</span>
     <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;

     <span class="keyword">var</span> hasPassword = <span class="literal">false</span>;
     <span class="keyword">var</span> commands = data.toString().split(<span class="string">'\n'</span>).join(<span class="string">' &amp;&amp; '</span>);
     <span class="keyword">var</span> ssh = spawn(<span class="string">'ssh'</span>, [<span class="string">'-l'</span> + username, host, commands]);

     ssh.on(<span class="string">'exit'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(code, signal)</span> {</span>
       process.exit();
     });

     ssh.stdout.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(out)</span> {</span>
       process.stdout.write(out);
       <span class="keyword">if</span> (!hasPassword) {
         <span class="keyword">var</span> stdin = process.openStdin();
         stdin.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(chunk)</span> {</span>
           ssh.stdin.write(chunk);
         });
       }

       hasPassword = <span class="literal">true</span>;
     });

     ssh.stderr.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
       process.stdout.write(err);
     });  
   });
 };

 <span class="keyword">var</span> args = process.argv.slice(<span class="number">2</span>);
 sys.puts(<span class="string">'Running commands from '</span> + args[<span class="number">1</span>] + <span class="string">' as root@'</span> + args[<span class="number">0</span>]);
 ssh(<span class="string">'root'</span>, args[<span class="number">0</span>], args[<span class="number">1</span>]);
</code></pre></div>

</p>
<p>We will run the script passing the IP address and commands.sh file as command line arguments. Unfortunately, password prompts are not managed by stdin, so we cannot pipe the password to our child ssh process through node directly. What that means is that you will have to manually copy-and-paste your root password from the command line when prompted. The node script will behave just like the terminal, so if you get any interactive prompts, just respond to them. Here's a sample:

</p>
<pre>
  $ node create-server.js
  Your server is now ready:
    IP Address: 1.2.3.4
    Root password: what-a-password
  $ node ssh.js 1.2.3.4 commands.sh
  Running commands from commands.sh as root@1.2.3.4
  (...)
  root@1.2.3.4's password: 
  (...)
  &gt; hello world running on port 80
</pre>

<h1>Verifying your server is running</h1>
<p>Now that we've installed node on the server we've created and started up the 'hello node' server we need to verify that this server is running. This can be accomplished by visiting the IP address in the browser or simply curling it:

</p>
<pre>
  curl <a href="http://1.2.3.4/">http://1.2.3.4/</a>
  hello, i know nodejitsu.
</pre>

<p>From here it might be prudent to shut-down your node server through a more traditional ssh client and get hacking with node!

</p>
<pre>
  killall -9 node
</pre>

]]></description><link>http://blog.nodejitsu.com/nodejs-cloud-server-in-three-minutes</link><guid isPermaLink="true">http://blog.nodejitsu.com/nodejs-cloud-server-in-three-minutes</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Fri, 10 Sep 2010 09:20:00 GMT</pubDate></item><item><title><![CDATA[<a href="./jsdom-jquery-in-5-lines-on-nodejs">jsdom + jQuery in 5 lines with node.js</a>]]></title><description><![CDATA[<p>Screen scraping has been a focus of engineering for quite some time. Every major language out there has their own library of choice for performing these tasks:

</p>
<ul>
<li>Ruby <a href="http://hpricot.com">hpricot</a>, <a href="http://nokogiri.org/">nokogiri</a></li>
<li>Python <a href="http://www.crummy.com/software/BeautifulSoup">beautiful-soup</a>, <a href="http://scrapy.org/">scrapy</a></li>
<li>Perl <a href="http://search.cpan.org/~ingy/pQuery-0.07/lib/pQuery.pm">pQuery</a></li>
<li>PHP <a href="http://us.php.net/dom">PHP DOM</a></li>
</ul>
<p>The challenge with using these libraries is that they all have their own quirks that can make working with HTML, CSS and Javascript challenging. 

</p>
<h2> </h2>
<h1>The Javascript difference</h1>
<p>By working with server-side Javascript (in this case <a href="http://nodejs.org">node.js</a>) developers don't need to worry about these issues because we can use widely accepted and battle-hardened libraries such as jQuery on the server thanks to <a href="http://github.com/tmpvar/jsdom">jsdom</a>, a server-side implementation of the DOM apis developed by nodejitsu's own <a href="http://github.com/tmpvar">Elijah Insua</a>. Adding jQuery to any page with jsdom is easy:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> jsdom = require(<span class="string">'jsdom'</span>);

jsdom.env({
  html: <span class="string">"&lt;html&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;"</span>,
  scripts: [
    <span class="string">'http://code.jquery.com/jquery-1.5.min.js'</span>
  ]
}, <span class="function"><span class="keyword">function</span> <span class="params">(err, window)</span> {</span>
  <span class="keyword">var</span> $ = window.jQuery;

  $(<span class="string">'body'</span>).append(<span class="string">"&lt;div class='testing'&gt;Hello World&lt;/div&gt;"</span>);
  console.log($(<span class="string">".testing"</span>).text()); <span class="comment">// outputs Hello World</span>
});
</code></pre></div>

</p>
<p>The above code creates a new jsdom window and adds jQuery to the document via a script element. Although it is just an illustrative example it is easy to modify it to work with real pages retrieved from the Internet.
<br>

</p>
<h1>Working with live pages</h1>
<p>Node.js makes it easy to retrieve pages online. The low-level <a href="http://nodejs.org/docs/v0.4.7/api/http.html#http.Agent">http.Agent</a> apis are somewhat verbose, but thankfully there are two libraries out there that make it easier: <a href="http://github.com/mikeal/node-utils/tree/master/request">request</a> and <a href="http://github.com/indexzero/http-agent">http-agent</a>. You can install these libraries through the node package manager, <a href="http://npmjs.org">npm</a>. All of the samples in the blog post are packaged up into a <a href="https://gist.github.com/1009644">gist</a> for easy use: 

</p>
<p><div class="snippet"><pre><code><span class="identifier">curl</span> -<span class="identifier">o</span> <span class="identifier">jsdom</span>-<span class="identifier">jquery</span>.<span class="identifier">tar</span>.<span class="identifier">gz</span> <span class="identifier">https</span><span class="symbol">:</span>/<span class="regexp">/gist.github.com/gists</span><span class="regexp">/1009644/download</span>
<span class="identifier">tar</span> -<span class="identifier">xvf</span> <span class="identifier">jsdom</span>-<span class="identifier">jquery</span>.<span class="identifier">tar</span>.<span class="identifier">gz</span>
<span class="identifier">cd</span> <span class="identifier">gist1009644</span>*
<span class="identifier">npm</span> <span class="identifier">install</span>
<span class="identifier">node</span> <span class="identifier">request</span>.<span class="identifier">js</span>
<span class="identifier">node</span> <span class="identifier">jsdom</span>-<span class="identifier">jquery</span>.<span class="identifier">js</span>
<span class="identifier">node</span> <span class="identifier">jquery</span>-<span class="identifier">request</span>.<span class="identifier">js</span>
<span class="identifier">node</span> <span class="identifier">jquery</span>-<span class="identifier">http</span>-<span class="identifier">agent</span>.<span class="identifier">js</span>
<span class="identifier">node</span> <span class="identifier">http</span>-<span class="identifier">agent</span>.<span class="identifier">js</span></code></pre></div>

</p>
<p>Request is best suited for making requests for individual webpages:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> request = require(<span class="string">'request'</span>),
    sys = require(<span class="string">'sys'</span>);

request({ uri:<span class="string">'http://www.google.com'</span> }, <span class="function"><span class="keyword">function</span> <span class="params">(error, response, body)</span> {</span>
  <span class="keyword">if</span> (error &amp;&amp; response.statusCode !== <span class="number">200</span>) {
    console.log(<span class="string">'Error when contacting google.com'</span>)
  }
  
  <span class="comment">// Print the google web page.</span>
  sys.puts(body);
});</code></pre></div>

</p>
<p>While http-agent is designed for scenarios where you need to iterate over a sequence of webpages.  to retrieve after any page is returned:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> httpAgent = require(<span class="string">'http-agent'</span>),
    util = require(<span class="string">'util'</span>);

<span class="keyword">var</span> agent = httpAgent.create(<span class="string">'www.google.com'</span>, [<span class="string">'finance'</span>, <span class="string">'news'</span>, <span class="string">'images'</span>]);

agent.addListener(<span class="string">'next'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, agent)</span> {</span>
  console.log(<span class="string">'Body of the current page: '</span> + agent.body);
  console.log(<span class="string">'Response we saw for this page: '</span> + util.inspect(agent.response));

  <span class="comment">// Go to the next page in the sequence</span>
  agent.next();
});

agent.addListener(<span class="string">'stop'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, agent)</span> {</span>
  console.log(<span class="string">'the agent has stopped'</span>);
});

agent.start();</code></pre></div>


</p>
<h1>Real-life scraping tasks</h1>
<p>The above examples can be combined into robust and easy-to-use code for scraping live pages. We simply need to make a new jsdom window for each page we get back, then add jQuery to the page. Here's an example using request: 

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> request = require(<span class="string">'request'</span>),
    jsdom = require(<span class="string">'jsdom'</span>);

request({ uri:<span class="string">'http://www.google.com'</span> }, <span class="function"><span class="keyword">function</span> <span class="params">(error, response, body)</span> {</span>
  <span class="keyword">if</span> (error &amp;&amp; response.statusCode !== <span class="number">200</span>) {
    console.log(<span class="string">'Error when contacting google.com'</span>)
  }
  
  jsdom.env({
    html: body,
    scripts: [
      <span class="string">'http://code.jquery.com/jquery-1.5.min.js'</span>
    ]
  }, <span class="function"><span class="keyword">function</span> <span class="params">(err, window)</span> {</span>
    <span class="keyword">var</span> $ = window.jQuery;

    <span class="comment">// jQuery is now loaded on the jsdom window created from 'agent.body'</span>
    console.log($(<span class="string">'body'</span>).html());
  });
});</code></pre></div>

</p>
<p>where as with http-agent the code would be: 

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> httpAgent = require(<span class="string">'http-agent'</span>),
    jsdom = require(<span class="string">'jsdom'</span>);

<span class="keyword">var</span> agent = httpAgent.create(<span class="string">'www.google.com'</span>, [<span class="string">'finance'</span>, <span class="string">'news'</span>, <span class="string">'images'</span>]);

agent.addListener(<span class="string">'next'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, agent)</span> {</span>
  jsdom.env({
    html: agent.body,
    scripts: [
      <span class="string">'http://code.jquery.com/jquery-1.5.min.js'</span>
    ]
  }, <span class="function"><span class="keyword">function</span> <span class="params">(err, window)</span> {</span>
    <span class="keyword">var</span> $ = window.jQuery;
    
    <span class="comment">// jQuery is now loaded on the jsdom window created from 'agent.body'</span>
    console.log($(<span class="string">'body'</span>).html());
    
    agent.next();
  });
});

agent.addListener(<span class="string">'stop'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(agent)</span> {</span>
  console.log(<span class="string">'the agent has stopped'</span>);
});

agent.start();</code></pre></div>


</p>
<h1>Wrapping up</h1>
<p>So to sum up here, there are some key benefits that doing your screen scraping with node.js, and jsdom provide: 

</p>
<ul>
<li>Works with the same battle-hardened DOM libraries used in production every day.</li>
<li>Node.js is blazing fast and designed for exactly these kind of highly asynchronous coding tasks.</li>
<li>Easy to use and deploy with new tools like <a href="http://nodejitsu.com">nodejitsu</a>.</li>
</ul>
<p>Happy scraping!
<br><br>

</p>
]]></description><link>http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs</link><guid isPermaLink="true">http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Sun, 05 Sep 2010 17:22:52 GMT</pubDate></item><item><title><![CDATA[<a href="./kyuri-and-prenup-our-node-knockout-entries">kyuri and prenup</a>]]></title><description><![CDATA[<p>We got the chance to compete in a 48 hour node.js programming competition last week called "<a href="http://nodeknockout.com" title="nodeknockout">node knockout</a>" and it was amazing! we've launched two open-source projects <a href="http://github.com/nodejitsu/kyuri" title="kyuri">kyuri</a> and <a href="http://github.com/nodejitsu/prenup" title="prenup">prenup</a>, which were very well received by the community.

</p>
<h2> </h2>
<p>there is a lot more information in the github repos for these projects, but to give a quick summary:
</p>
<p><hr>
<img src="kyuri-and-prenup-our-node-knockout-entries/kyuri.png" style="float: none;">

</p>
<h1>a node.js Cucumber implementation with a few extra asynchronous keywords. it supports 160+ languages and currently can generate VowsJS stubs</h1>

<p> <a href="http://github.com/nodejitsu/kyuri" title="kyuri"><a href="http://github.com/nodejitsu/kyuri">http://github.com/nodejitsu/kyuri</a></a>

</p>
<p><hr>
<img src="kyuri-and-prenup-our-node-knockout-entries/prenup.png" style="float: none;">

</p>
<h1>a real-time collaborative project planning application that allows you to easily create Milestones, Features, Scenarios, Steps, and assign points.</h1>

<p><a href="http://github.com/nodejitsu/prenup" title="prenup"><a href="http://github.com/nodejitsu/prenup">http://github.com/nodejitsu/prenup</a></a>
</p>
<hr>

<p>Ultimately we only got 2nd place in the category we were competing in. I think a vast majority of the people judging didn't really understand we did two entries, and what the purpose of those entries actually did. We probably should have focused more on presentation and trying to win the contest, but we were focused on producing two long lasting open-source projects. 

</p>
<p>We did however, get a lot of really great feedback from those who took to the time to actually dive into the madness that was our node knockout entry.

</p>
<div align="center" style="font-size: 18px; padding-left: 90px; text-align: center; width: 770px;">

<blockquote>
<i>"This is probably the most useful entry I've seen. Having used cuke from ruby I can see it's value. Also real-time project planning sounds really useful for distributed teams."</i> - <strong>Tim Caswell, co-author of Connect</strong>
</blockquote>

<blockquote>
  <i>"This is my favorite Node.js entry, because it's not a damn game and does something I might use"</i> - <strong>Zed Shaw</strong>
</blockquote>

<blockquote>
  <i>"Very cool to see more Cucumber/Javascript action. The kyuri project is very interesting. It would be interesting to run some of gherkin's own Cucumber features against it to see how compliant the parser is. If it's good I would be interested in merging kyuri into the gherkin project."</i> - <strong>Aslak Hellesoy, creator of Cucumber and Gherkin</strong>
</blockquote>

<blockquote>
  <i>"Useful, well executed, complete and tries to solve a real problem."</i> - <strong>Guillermo Rauch, creator of Socket.io</strong>
</blockquote>

<blockquote>
  <i>"Awesome utility for developers and specification builders (which could be developers as well). Very interested to see where you take it from here! Great Job!"</i> - <strong>Chris Williams, Curator of JSConf, 6th Degree Javascript Blackbelt</strong>
</blockquote>

<blockquote>
  <i>"kyuri is an awesome and important contribution to the community."</i> - <strong>Malte Ubl, XING Technical Director </strong>
</blockquote>

<blockquote>
<i>"Considering they wrote a Gherkin parser for the project, and this app has real value, hats off! I can see myself using this when it's completed."</i> - <strong>Alexis Sellier (cloudhead), creator of VowsJS</strong>
</blockquote>

</div>

<p>With the help of these inspiring comments, we'll be hard at work iterating on these projects in the upcoming months. 

</p>
<p>Expect good things.

</p>
]]></description><link>http://blog.nodejitsu.com/kyuri-and-prenup-our-node-knockout-entries</link><guid isPermaLink="true">http://blog.nodejitsu.com/kyuri-and-prenup-our-node-knockout-entries</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Sat, 04 Sep 2010 17:22:52 GMT</pubDate></item><item><title><![CDATA[<a href="./vows-custom-test-runner">Vows custom test runner</a>]]></title><description><![CDATA[<p>I recently ported <a href="http://github.com/justinlilly/imb0t/tree/master/js/">an IRC bot</a> that I wrote from Python to node.js and took the opportunity to try BDD for the first time. My results were very positive. BDD seems to play out a lot like a unittest, but with much more readability.

</p>
<h2> </h2>
<p>I used <a href="http://vowsjs.org/">vows</a>, a very well documented BDD library for node.js that has an amazing website and a helpful developer. The principle is that in a given test case, you have a topic. This topic is a specific facet of your program that you'd like to test.

</p>
<p>In my example, I test two objects: the pattern, and the pattern list. In prose, its easy to say that "The pattern list is an array that contains objects. You can add something to it by registering something." The tests follow that almost exactly. The topic is the noun, a pattern list. For each clause describing it, you create a new test. There's a test to validate its an array, another to ensure it contains objects, and a third to check that when you register something, the list grows. All fairly straight forward.

</p>
<p>The product of this is a very simple list of dots followed by the time it took to run and how many tests passed. You can pass some arguments, if you're using the <code>vows</code> command, and you'll get nice RSpec output. Very fancy.

</p>
<p>What if we wanted something different? Perhaps a bit retro? Look no further than <a href="http://asciimo.com/">asciimo</a>, which makes it quite easy to get ascii art with little effort. You can even throw in some color for fun.

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> asciimo = require(<span class="string">'/path/to/asciimo'</span>).Figlet,
    colors = require(<span class="string">'/path/to/colors'</span>);
    
asciimo.write(<span class="string">'Test'</span>, <span class="string">'drpepper'</span>, <span class="function"><span class="keyword">function</span><span class="params">(art)</span> {</span>
  console.log(art.blue);
});</code></pre></div>

</p>
<p>Tying this into vows turns out not to be terribly difficult either. After some initial trouble getting custom test reporters registered, I was pointed the right way by cloudhead on #node.js, the author of vows. Turns out I was using an non-public API along with not exporting my test suite into a form that vows understood. Custom reporters only need to implement a report method which takes two arguments. From what I could tell, the second method wasn't used (at least not for standard test running), but the first argument provides a wealth of information about the test suite.

</p>
<p>The first argument is a list whose first element is a string which is followed by an optional second item. The string seems to represent which portion of BDD's tree based structure you're on. The second element in the array is some structure describing the first argument. In the example of an actual test, it shows the test name and whether it passed (was honored) or failed, among other things. Some examples include:

</p>
<p><div class="snippet"><pre><code>[ <span class="string">'subject'</span>, <span class="string">'imbot patterns'</span> ]
[ <span class="string">'context'</span>, <span class="string">'The pattern list'</span> ]
[ <span class="string">'vow'</span>
   , { title: <span class="string">'is an array'</span>
     , context: <span class="string">'The pattern list'</span>
     , status: <span class="string">'honored'</span>
     , exception: <span class="literal">null</span>
     }]
[ <span class="string">'end'</span> ]
[ <span class="string">'finish'</span>
   , { honored: <span class="number">6</span>
     , broken: <span class="number">0</span>
     , errored: <span class="number">0</span>
     , pending: <span class="number">0</span>
     , total: <span class="number">6</span>
     , time: <span class="number">0.007</span>
     }]
</code></pre></div>

</p>
<p>Based on this, we really only need to pay attention for the 'finish' message to be passed. For instance, a simple custom reporter might look like:

</p>
<p><div class="snippet"><pre><code><span class="keyword">var</span> sys = require(<span class="string">'sys'</span>);
<span class="keyword">var</span> colors = require(<span class="string">'../../colors.js/colors'</span>);
<span class="keyword">var</span> asciimo = require(<span class="string">'../../asciimo/lib/asciimo'</span>).Figlet;
<span class="keyword">var</span> report_font = <span class="string">'drpepper'</span>;

<span class="keyword">this</span>.report = <span class="function"><span class="keyword">function</span> <span class="params">(data, s)</span> {</span>
  <span class="keyword">if</span> (data[<span class="number">0</span>] == <span class="string">'vow'</span>) {
    sys.print(<span class="string">'.'</span>);
  }
  <span class="keyword">if</span> (data[<span class="number">0</span>] == <span class="string">'finish'</span>) {
    sys.print(<span class="string">'\n'</span>); <span class="comment">// clear a newline</span>
    <span class="keyword">var</span> result = <span class="string">'failed'</span>;
    <span class="keyword">if</span> (data[<span class="number">1</span>].broken == <span class="number">0</span> &amp;&amp; data[<span class="number">1</span>].errored == <span class="number">0</span>) {
      result = <span class="string">'passed'</span>;
    }
    asciimo.write(result, report_font, <span class="function"><span class="keyword">function</span> <span class="params">(art)</span> {</span>
        <span class="keyword">if</span> (result  == <span class="string">'passed'</span>)
          sys.puts(art.green);
        <span class="keyword">else</span>
          sys.puts(art.red);
        <span class="keyword">var</span> output = <span class="string">''</span>;
        output += <span class="string">'Passed: '</span> + data[<span class="number">1</span>].honored + <span class="string">' \n'</span>;
        output += <span class="string">'Failed: '</span> + data[<span class="number">1</span>].broken + <span class="string">' \n'</span>;
        output += <span class="string">'Errored: '</span> + data[<span class="number">1</span>].errored + <span class="string">' \n'</span>;
        output += <span class="string">'in '</span> + data[<span class="number">1</span>].time + <span class="string">'sec'</span>;
        sys.puts(output);
    });
  }
};
</code></pre></div>

</p>
<p>And the result of that is an ascii art of the words passed or failed in green or red respectively, followed by how many things passed and failed and the total execution time. Not too shabby for under 30 lines of code. For the sake of another example, below is another simple example using the <a href="http://github.com/Marak/say.js">say.js</a> and <a href="http://github.com/Marak/play.js">play.js</a> libraries.

</p>
<p><div class="snippet"><pre><code><span class="comment">// using say.js</span>
<span class="keyword">var</span> say = require(<span class="string">'say'</span>);

<span class="keyword">this</span>.report = <span class="function"><span class="keyword">function</span> <span class="params">(data, s)</span> {</span>
  <span class="keyword">if</span> (data[<span class="number">0</span>] == <span class="string">'finish'</span>) {
      <span class="keyword">var</span> result = <span class="string">'You had '</span> + data[<span class="number">1</span>].broken +<span class="string">' broken, '</span> 
          + data[<span class="number">1</span>].errored + <span class="string">' errored, and '</span>
          + data[<span class="number">1</span>].honored + <span class="string">' passing tests.'</span>;
    say.speak(<span class="string">'Alex'</span>, result);
  }
};

<span class="comment">// using play.js</span>
<span class="keyword">var</span> play = require(<span class="string">'play'</span>);

<span class="keyword">this</span>.report = <span class="function"><span class="keyword">function</span> <span class="params">(data, s)</span> {</span>
    <span class="keyword">if</span> (data[<span class="number">0</span>] == <span class="string">'finish'</span>) {
        <span class="keyword">if</span> (data[<span class="number">1</span>].broken + data[<span class="number">1</span>].errored &gt; <span class="number">0</span>) {
            play(<span class="string">'/path/to/sad_trombone.wav'</span>);
        } <span class="keyword">else</span> {
            play(<span class="string">'/path/to/success.wav'</span>);
        }
  }
};
</code></pre></div>

</p>
]]></description><link>http://blog.nodejitsu.com/vows-custom-test-runner</link><guid isPermaLink="true">http://blog.nodejitsu.com/vows-custom-test-runner</guid><dc:creator><![CDATA[Justin Lilly]]></dc:creator><pubDate>Tue, 03 Aug 2010 17:22:52 GMT</pubDate></item></channel></rss>
