<?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>Wed, 22 May 2013 20:03:03 GMT</lastBuildDate><atom:link href="/feed.xml" rel="self" type="application/rss+xml"/><item><title><![CDATA[<a href="./iriscouch-acquisition">IrisCouch has joined the Nodejitsu Team</a>]]></title><description><![CDATA[<p>Today Nodejitsu is excited to announce that we have acquired IrisCouch along with its suite of Database-as-a-Service and npm products. This acquisition continues to enhance our toolset for our Enterprise and Public Cloud customers. There is a related press release available on <a href="https://www.nodejitsu.com/company/press/2013/05/22/iriscouch/">nodejitsu.com</a>.

</p>
<p>There are a number of reasons we are thrilled to bring IrisCouch into the Nodejitsu team:

</p>
<h2> </h2>
<p><strong>1. Importance of Database-as-a-Service</strong>: Data is everything today. It drives forward development of both a technology and a business. Tightly integrating your database with your application can mean the difference between a successful or failed product. We have already been working with IrisCouch and our other database partners (like <a href="https://mongolab.com/welcome/">MongoLab</a>) to ensure that the databases they created are co-located with <a href="https://www.nodejitsu.com/paas/datacenters/">our datacenter targets</a>, and this acquisition will only improve that effort for Redis and Apache CouchDB.

</p>
<p><strong>2. Commitment to node.js</strong>: Node.js has been in our DNA since Nodejitsu was founded three years ago. Everything we’ve created is built on Node.js, Apache CouchDB, and Redis. One of the best parts about node.js is <a href="http://npmjs.org">npm</a> (the node package manager). It makes publishing and installing node modules as fun as it is to write them. 

</p>
<p>If you’re using npm today, you’re already using IrisCouch. But don’t take our word for it, listen to what Isaac Z. Schlueter, creator of npm and leader of the Node.js project had to say:

</p>
<blockquote>
<p>"IrisCouch has been the official host of the public npm registry since they were part of CouchOne (now Couchbase). They have provided top-notch service to the Node.js and npm community since day one, even going so far as to make modifications to Apache CouchDB itself for our security needs.  I cannot recommend them highly enough."

</p>
</blockquote>
<p>Through the acquisition of IrisCouch, <strong>every node.js developer in the world will be using Nodejitsu every day.</strong> Our commitment to node.js and npm remains steadfast, you can count on us to ensure the public npm registry remains open, available, and reliable.  

</p>
<p><strong>3. The Team</strong>: As part of the acquisition, both Jeff Jackson (IrisCouch CEO) and Jason Smith (IrisCouch CTO) will be joining the leadership team at Nodejitsu. Adding this wealth of high-caliber industry expertise to Nodejitsu will ensure that we are well equipped for the road ahead as we begin hyper-growth.

</p>
<h2>What’s going to change?</h2>
<p>As part of this acquisition we will be rolling IrisCouch’s Database-as-a-Service for CouchDB and Redis <strong>directly into our public Platform-as-a-Service.</strong> This means that our users will be able to deploy their applications and databases from the same set of tools all backed by node.js. If you’re an existing IrisCouch user you will be notified and given ample time to migrate your IrisCouch account into a Nodejitsu account.

</p>
<p>In addition to tightly integrating Database-as-a-Service into the Nodejitsu Public Cloud, we will be sunsetting their IrisNpm product over the next few months. If you’re an IrisNpm user today, you will be given ample time to ensure your private npm packages can be transferred. 

</p>
<p>Sunsetting IrisNpm was a tough decision but it will allow us to focus on offering the best Enterprise npm product to node.js power users. Interested in how a private npm workflow can help your team? Get in touch with our <a href="mailto:sales@nodejitsu.com">sales team</a> today!

</p>
<h2>The road ahead</h2>
<p>IrisCouch’s collection of technology, services, and talent join our recent announcement of <a href="http://www.opsmezzo.com/">OpsMezzo</a>, fortifying the breadth of our offering to both developers and businesses.

</p>
<p>Jason Smith marked this occasion in his own words by saying simply: “this is the first step of a thousand mile journey.”

</p>
<blockquote>
<p>Apache CouchDB, CouchDB, and the project logo are trademarks of The Apache Software Foundation
</p>
</blockquote>
]]></description><link>http://blog.nodejitsu.com/iriscouch-acquisition</link><guid isPermaLink="true">http://blog.nodejitsu.com/iriscouch-acquisition</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Wed, 22 May 2013 14:15:47 GMT</pubDate></item><item><title><![CDATA[<a href="./nodestack-2">Nodestack, Round 2</a>]]></title><description><![CDATA[<p>Last October, Nodejitsu got together with our partners, <a href="http://joyent.com/">Joyent</a>, <a href="http://www.10gen.com/">10gen</a>, <a href="http://clock.co.uk/">Clock</a>, and <a href="https://mongolab.com/welcome/">MongoLab</a>, and brought you Nodestack. It was a one day online conference with the goal of examining the technology stack emerging around Node.js, and answering critical industry questions about adopting and maintaining this technology in your own company. The conference was a great success so we're back, and we're bringing you a series of smaller webinars to delve deeper into more specific technical matters.

</p>
<p><a href="http://nodestack.org/">Join us</a> on Tuesday 9:00 AM - 10:30 AM PT for Nodestack: State of the Stack, where Charlie and Nuno will be holding it down with Isaac Schleuter and Aaron Heckman:

</p>
<h2>#</h2>
<p>Charlie will be tag teaming with izs to discuss 0.10. Then Aaron from 10gen will be discussing Replica Sets &amp; Text Search in MongoDB 2.4, and finally, Nuno will close out the session with a talk about running Production Node on SmartOS.

</p>
<p>There are still a <a href="http://nodestack.org/">few tickets left</a>. See you there!</p>
]]></description><link>http://blog.nodejitsu.com/nodestack-2</link><guid isPermaLink="true">http://blog.nodejitsu.com/nodestack-2</guid><dc:creator><![CDATA[Ana Hevesi]]></dc:creator><pubDate>Fri, 17 May 2013 02:51:48 GMT</pubDate></item><item><title><![CDATA[<a href="./update-on-price-changes">An Update on Price Changes</a>]]></title><description><![CDATA[<p>In our April 30th blog post, Nodejitsu announced price increases for customers running on Individual Plans on our hosting platform. You can find the new numbers and details of additional platform changes <a href="https://blog.nodejitsu.com/changes-in-nodejitsu-public-cloud">here</a>. This post is a reminder that these changes are taking place, and a response to a few questions from our customers.

</p>
<p>Initially we gave two weeks notice, and scheduled price changes for Wednesday May 15th. Many customers have felt this was not enough time. My team and I heard your feedback, and have pushed the changes out one more week. <strong>Wednesday May 22nd is now the day that our new prices will go into effect.</strong>

</p>
<p>We also received questions regarding the ascending price of our plans. For example, some people have wondered why a Micro plan (1 drone) costs $9 whereas a Small plan (3 drones) costs $33 dollars. This is because our Micro plans (our lowest hosting tier), are being slightly subsidized. We want to continue encouraging experimentation on our PaaS, albeit at a higher price point than before. 

</p>
<p>In the same spirit of experimentation, Nodejitsu is upholding our commitment to offer a free drone, the equivalent of one Micro plan, to host an open source app to any node.js developer. You simply need to apply through <a href="http://opensource.jit.su/">opensource.jit.su</a>.

</p>
<p>Nodejitsu's success thus far is due entirely to the support of the node.js community. We understand these price changes have upset some of our customers, but these changes allow us to serve our community sustainably and continue contributing open source software to the node ecosystem. These changes also provide our small but talented team with an opportunity to improve our PaaS, dealing more quickly with production incidents and fixing underlying issues. The goal is to provide our customers with a better product. My team and I are excited to move forward towards a strong future for node, and we look forward to doing so with many members of the node community on our platform.
</p>
]]></description><link>http://blog.nodejitsu.com/update-on-price-changes</link><guid isPermaLink="true">http://blog.nodejitsu.com/update-on-price-changes</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Thu, 16 May 2013 15:26:47 GMT</pubDate></item><item><title><![CDATA[<a href="./ken-perkins-is-a-new-pkgcloud-committer">Ken Perkins is a new pkgcloud committer</a>]]></title><description><![CDATA[<p>We are extremely proud to announce that as of May 9th,
<a href="https://twitter.com/kenperkins">Ken Perkins</a> is a new <a href="https://github.com/nodejitsu/pkgcloud"><code>pkgcloud</code></a> committer.

</p>
<p>Ken has been putting great amounts of work into <code>pkgcloud</code>, including fixing
Rackspace integration and a huge internal refactor which corrects mistakes we
made when designing some of the low level APIs. We are extremely thankful for his
help and dedication, so we decided to give him push access to our repository.

</p>
<h2> </h2>
<p>Here are few words Ken has to say about himself:

</p>
<blockquote>
<p>I'm the lead Node.js Developer Advocate at Rackspace, primarily working on our node.js SDKs. Immediately before Rackspace, I was a full-stack node.js developer with Clipboard. I also spent almost 9 years at Microsoft, most recently as a Program Manager in Live Labs working on projects like Seadragon, Photosynth, and Pivot. Most of my time outside of work is spent playing with my kids and enjoying the weather whenever it's nice here in Seattle.

</p>
</blockquote>
<p>He also published few interesting blog posts about changes he wants to
introduce to <code>pkgcloud</code>:

</p>
<ul>
<li><a href="http://mylifeincode.com/post/50093103813/cleaning-up-multi-provider-compute-methods-in-pkgcloud">Cleaning up multi-provider compute methods in pkgcloud</a></li>
<li><a href="http://mylifeincode.com/post/49806798014/plans-for-the-v0-8-release-of-pkgcloud">Plans for the (v0.8?) release of pkgcloud</a></li>
</ul>
<p>You should follow Ken on <a href="https://twitter.com/kenperkins">Twitter</a> and subscribe to
his <a href="http://mylifeincode.com/">blog</a>.

</p>
<p>We'd also like to thank <a href="https://www.rackspace.com">Rackspace</a> for giving Ken
a chance to work on open source as his full time job. It's great to see
companies giving back to the community.
</p>
]]></description><link>http://blog.nodejitsu.com/ken-perkins-is-a-new-pkgcloud-committer</link><guid isPermaLink="true">http://blog.nodejitsu.com/ken-perkins-is-a-new-pkgcloud-committer</guid><dc:creator><![CDATA[Maciej Malecki]]></dc:creator><pubDate>Fri, 10 May 2013 18:09:06 GMT</pubDate></item><item><title><![CDATA[<a href="./changes-in-nodejitsu-public-cloud">Changes in Nodejitsu's Public Cloud</a>]]></title><description><![CDATA[<p><strong>As of today we are announcing a new pricing structure for our Individual Plans that will take effect on Wednesday May 15th, 2013.</strong> The Nodejitsu platform has grown significantly since we launched our Public Beta last year and even more since we launched our Paid Individual and Business Plans. This growth has put us in a position where we need to make some decisive choices in order to create a sustainable future for our Public Cloud product.

</p>
<p>Last week we announced <a href="http://blog.nodejitsu.com/announcing-opsmezzo">OpsMezzo</a>, <em>a complete solution to provisioning, orchestration and configuration management geared towards enterprise customers.</em> That annoucement reflects our commitment to <a href="https://speakerdeck.com/indexzero/all-open-source-everything">OpenSource</a> and the <a href="http://nodejs.org">node.js community</a>. In fact, more than 80% of the nodejitsu stack is now Open Source.

</p>
<p>Our prices are the lowest in the Platform-as-a-Service market. Last year when we <a href="http://blog.nodejitsu.com/on-disrupting-pricing-models">announced our pricing model</a> we thought we could make this model sustainable, but this was built on several assumptions that turned out to be wrong. With this new model we will be able to keep our Public Cloud sustainable for years to come.

</p>
<p><strong>Please note: the changes we are about to discuss apply only to customers using Individual Plans on Nodejitsu’s platform and will not affect Business Plan customers.</strong>

</p>
<h2> </h2>
<p>First, the two core assumptions that we made at Nodejitsu when we compiled our current pricing:

</p>
<ol>
<li><em>64MB of RAM</em>: Our original plan was to give drones on Individual Plans 64MB of RAM, but technical limitations combined with the high expectations of our existing Individual users led us to <strong>keep 256MB RAM as standard for all drones.</strong></li>
<li><em>The power of Node.js</em>: Node.js is an amazing technology enabling developers to do a lot with minimal resources. When we decided to only give <a href="http://blog.nodejitsu.com/business-plans">flexible drone sizes and multi-datacenter access to our Business Plan customers</a>, we assumed that this would be incentive enough to attract our customers who need to handle large volumes of traffic. Turns out <strong>node.js is even more powerful than we thought;</strong> and as of writing this <em>dozens of businesses are running on our Individual Plans.</em> While its exciting that the combination of node and our technology can deliver these results, this is ultimately hurting Nodejitsu. </li>
</ol>
<p>With all this in mind, we still realize that we made a commitment to our customers and when restructuring our Individual Plans we wanted to <em>ensure that they are still competitive.</em> With the new prices below <strong>Nodejitsu is still the most affordable Platform-as-a-Service on the market.</strong>

</p>
<ul>
<li><strong>Micro (1 drone):</strong> <em>$9 / month</em></li>
<li><strong>Small (3 drones):</strong> <em>$33 / month</em></li>
<li><strong>Regular (5 drones):</strong> <em>$50 / month</em></li>
<li><strong>Large (10 drones):</strong> <em>$90 / month</em></li>
</ul>
<p>In addition to these pricing changes we will be clarifying some additional limitations for applications running on Individual Plans:

</p>
<ul>
<li><strong>3 drone limit:</strong> If you’re on an Individual Plan, <code>jitsu apps setdrones 3</code> is the maximum number of running drones you will be able to set for a single application.   </li>
<li><strong>10 drones max:</strong> If you’re on an Individual Plan, you will be able to run a total of 10 drones maximum. If you need more than that, we reccommend you upgrade to a <a href="http://blog.nodejitsu.com/business-plans">Business Plan</a></li>
<li><strong>One-day retention for Metrics:</strong> These changes will go into effect on the same day as our new metrics for CPU, Memory, and HTTP. Customers running on an Individual Plan will have a default retention of <em>one-day.</em></li>
<li><strong>One-day retention for Logs:</strong> As we improve our logging facilities, we will be increasing the retention around our logs for Business Plans. Individual plans, however, will have <em>one-day</em> of logs retention.<ul>
<li><strong>Designated support hours:</strong> The support provided in #nodejitsu on irc.freenode.net will be staffed by Nodejitsu Support Engineers from 9am - 8pm ET, Monday - Friday. There may be staffers or community support available at other times, but the above hours are when you can rely on live help from Nodejitsu.</li>
</ul>
</li>
</ul>
<p>While these changes bring limitations in the short term, they allow us operate more responsibly long term. This new pricing and the subsequent changes to our business allow us to provide the same great hosting and to focus on making it better; not only taking the time to field incoming errors but to fix underlying issues. These changes won’t be for everyone, but we look forward to bringing you a better product, and serving many of you for a long time to come.

</p>
<p>We’re excited about the future of our Platform-as-a-Service product. By making these changes, difficult as they may be, it will make our product sustainable as we continue to grow and deliver on our promise of the <em>best Node.js Platform-as-a-Service available.</em>

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

</p>
]]></description><link>http://blog.nodejitsu.com/changes-in-nodejitsu-public-cloud</link><guid isPermaLink="true">http://blog.nodejitsu.com/changes-in-nodejitsu-public-cloud</guid><dc:creator><![CDATA[Nodejitsu]]></dc:creator><pubDate>Tue, 30 Apr 2013 18:26:47 GMT</pubDate></item><item><title><![CDATA[<a href="./announcing-opsmezzo">Announcing OpsMezzo</a>]]></title><description><![CDATA[<p>After more than 18 months of work, Nodejitsu announced the release of <strong>OpsMezzo</strong> at <a href="https://speakerdeck.com/indexzero/all-open-source-everything">TXJS</a> this week, a <em>complete solution to provisioning, orchestration and configuration management.</em>

</p>
<p>The majority of OpsMezzo is now available as <strong><a href="https://github.com/opsmezzo">Open-Source</a>.</strong> A related <a href="https://nodejitsu.com/company/press/2013/04/23/opsmezzo/">Press Release</a> can be found at <a href="https://nodejitsu.com/company/press/2013/04/23/opsmezzo/">nodejitsu.com</a>.

</p>
<p>Cloud computing has matured dramatically since Amazon Web Services launched in 2006. A dizzying number of vendors have emerged in the market to solve a wide spectrum of <em>specific</em> problems.

</p>
<p>These products have matured over the years, but they are built on a fundamentally flawed thesis: <em>the parts are more important than the whole.</em> In others words: <strong>organizations are on their own to integrate individual products into a complete system.</strong> Yes, there is a large amount of source material available through blogs, tutorials, and training, but the manual integration work remains. 

</p>
<p>At it's core, this means that organizations running in "the cloud" are dealing with <em>too many vendors to solve simple problems.</em> Vendors using multiple languages, databases, operating systems and other operational internals. While we live in a polyglot world, the operational calculus of running these multi-vendor systems is challenging to even seasoned professionals.

</p>
<p>At this point you are probably wondering: <em>"What about PaaS solutions?"</em> PaaS is great for individuals and organizations who do not have (or do not want to have) an operational competency. This concept of <em>"NoOps"</em>, while attractive to some, is also fundamentally flawed:

</p>
<ol>
<li><strong>Too simple for larger organizations</strong>: In order to present users with a set of APIs that are simple enough even for novices massive operational details are hidden. Larger organizations (especially those running their own datacenters) <em>already have an operational competency,</em> so the PaaS abstraction is just <strong>too simple.</strong></li>
<li><strong>Still too many vendors</strong>: Heroku pioneered the concept of "add -ons" and since then every PaaS company has been quick on their heels to copy that model. This leaves their customers <strong>paying too much to too many vendors with little-to-no visibility behind the scenes.</strong></li>
</ol>
<p>We saw these problems two years ago in the early days of Nodejitsu and set out to make OpsMezzo <strong>a complete solution built entirely on a single platform: <em>Node.js + CouchDB.</em></strong>

</p>
<p>Keep reading to learn more about how OpsMezzo can streamline and simplify your devops workflow. Or if you're interested in trying out OpsMezzo in your organization <strong>send an email to <a href="mailto:sales@nodejitsu.com">sales@nodejitsu</a> to get a free evaluation!</strong>

</p>
<h2> </h2>
<h3>TL;DR?</h3>
<ul>
<li><a href="#why">Why OpsMezzo?</a></li>
<li><a href="#actors">A system of actors</a></li>
<li><a href="#more">Want more about OpsMezzo?</a></li>
</ul>
<p><a name="why"></a>
</p>
<h2>Why OpsMezzo?</h2>
<p>What do we mean by a <em>complete</em> solution?

</p>
<ul>
<li><strong>Configuration management</strong> with <code>quill</code> and <code>composer</code>.</li>
<li><strong>Provisioning and orchestration</strong> with <code>baton</code> and <code>conservatory</code>.</li>
<li><strong>Monitoring and auto-scaling</strong> built on <code>godot</code>.</li>
<li><strong>Industrial Load balancing</strong> built on <code>node-http-proxy</code>.</li>
</ul>
<p>And more importantly why should you use OpsMezzo?

</p>
<ul>
<li><strong>Every line of code is battle-tested by powering the nodejitsu.com PaaS</strong></li>
<li><strong>Language, platform and cloud agnostic</strong></li>
<li><strong>Deploy anything.</strong> </li>
<li><strong>Write your deployment scripts in any language.</strong> </li>
<li><strong>Deploy to any IaaS cloud using <a href="https://github.com/opsmezzo/pkgcloud">pkgcloud</a>.</strong></li>
<li><strong>Run on any operating system using <a href="https://github.com/opsmezzo/system.json">system.json</a></strong></li>
<li><strong><code>quill</code> and the backend service it communicates with, <code>composer</code>, are <a href="https://github.com/opsmezzo/quill">Open-Source</a>.</strong></li>
</ul>
<p><a name="actors"></a>
</p>
<h2>A system of actors</h2>
<p>The name OpsMezzo comes from the musical team <em>intermezzo:</em>

</p>
<blockquote>
<p>Intermezzo: a short movement or interlude connecting the main 
parts of the composition.

</p>
</blockquote>
<p>All of the actors in the OpsMezzo system <strong>are designed to work together.</strong> In line with our <a href="https://github.com/nodejitsu">commitment</a> <a href="https://github.com/flatiron">to</a> <a href="https://github.com/opsmezzo">Open Source</a> <strong>every actor is Open Source or built directly on-top of MIT licensed Open Source software.</strong>

</p>
<p><img src="/announcing-opsmezzo/opsmezzo.png" />

</p>
<p>Examining the diagram above, OpsMezzo is composed of <strong>four actors</strong>:

</p>
<ul>
<li><em><em>Composer</em></em>: Modern configuration management backed by <a href="https://github.com/opsmezzo/system.json">system.json</a>.</li>
<li><em><em>Conservatory</em></em>: Flexible provisioning and state management for your servers on <a href="https://github.com/opsmezzo/pkgcloud">any cloud provider</a>.</li>
<li><em><em>Conductor</em></em>: <a href="https://github.com/observing/balancerbattle">Industrial grade</a> load-balancing with WebSocket support.</li>
<li><em><em>Instrument</em></em>: Powerful monitoring, metrics, and auto-scaling backed by <a href="https://github.com/opsmezzo/godot">godot</a> and compatible with <a href="http://riemann.io/concepts.html">riemann</a>.</li>
</ul>
<p>Along with <strong>two developer tools</strong>:

</p>
<ul>
<li><em><em>baton</em></em>: A provisioning and distributed SSH tool that talks to <em>conservatory</em> and your cloud provider (AWS, Rackspace, OpenStack, etc).</li>
<li><em><em>quill</em></em>: A configuration management tool that talks to <em>composer</em> and understands <a href="https://github.com/opsmezzo/system.json">system.json</a>.</li>
</ul>
<p>By developing all of these tools together OpsMezzo <strong>eliminates the months of work necessary to integrate other off-the-shelf software.</strong>

</p>
<p><a name="more"></a>
</p>
<h2>Want more about OpsMezzo?</h2>
<p>This is just the beginning for OpsMezzo. We couldn't be more excited to have released <strong>12 repositories as Open Source in a single day.</strong>

</p>
<p>Over the next few weeks we will be releasing <em>all of the documentation, even for actors that are not Open Source).</em> Right now all of the documentation for Open Source libraries (such as <code>quill</code> and <code>composer</code>) can be found at <a href="http://docs.opsmezzo.com">docs.opsmezzo.com</a>.

</p>
<p><br />
</p>
<h3>Interested in trying out OpsMezzo in your organization? Send an email to <a href="mailto:sales@nodejitsu.com">sales@nodejitsu</a> to get a free evaluation.</h3>
<p><br /><br />

</p>
]]></description><link>http://blog.nodejitsu.com/announcing-opsmezzo</link><guid isPermaLink="true">http://blog.nodejitsu.com/announcing-opsmezzo</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Tue, 23 Apr 2013 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./improved-load-balancing">Next Generation Load Balancing</a>]]></title><description><![CDATA[<p>On March 6th - March 8th, <em>Nodejitsu experienced our worst service disruption to date.</em> Following this series of outages, we immediately reallocated our Engineering and DevOps resources so as to properly assess the damage done and to fix some of our core infrastructure to ensure it never happens again. 

</p>
<p>In the time in between our outage and today we have overhauled our entire load balancing architecture, also known as Conductor. <strong>Below is a detailed look at our old load balancing system and our newly implemented solution.</strong> 

</p>
<h2>Previous implementation</h2>
<p><img style="margin-left: 125px;" src="/improved-load-balancing/old-balancer.png" />

</p>
<p>The previous implementation illustrated above suffers from several problems:

</p>
<ol>
<li><strong>Long startup time:</strong> populating the entire cache from CouchDB can take upwards of <em>several minutes.</em></li>
<li><strong>No retry on failure:</strong> incoming requests are simply killed with <code>500 ECONNREFUSED</code>.</li>
<li><strong>Lack of consistency:</strong> since each balancer maintains it's own <code>_changes</code> listener the state maintained is independent of other balancers.</li>
</ol>
<h2>New implementation</h2>
<p><img src="/improved-load-balancing/new-balancer.png" />

</p>
<p>The proposed implementation addresses the problems outlined in the <a href="#current-implementation">Current implementation</a> by:

</p>
<ol>
<li><strong>Reducing startup time:</strong> There is no cache built at startup, so balancers will be <em>immediately available to take requests.</em></li>
<li><strong>Retry on failure:</strong> requests will be retried when they fail up to a certain limit.</li>
<li><strong>Consistent central broker:</strong> the Cache Manager is now the authoritative and consistent source for host information and proactively invalidates the in-memory LRU cache on balancers as changes come in from CouchDB.</li>
</ol>
<p>Put more plainly, our new implementation of Conductor makes us <strong>less reliant on memory caching and the risks that come with it.</strong> It also moves us to a model where <strong>failure to connect with your app initiates a series of automatic retries and self-corrects.</strong> This will limit instances of ECONNREFUSED to times when the issue lies within a customers application, rather than our platform. Our team has needed to shelve some things in order to make this a reality, but our reliability is ultimately our top priority, and we believe this will bring a significant improvement to our core infrastructure.

</p>
<p>Thanks for hanging in there. We hope customers across the platform will be seeing a more reliable hosting experience. 

</p>
<p><br />
<br />
<br />
</p>
]]></description><link>http://blog.nodejitsu.com/improved-load-balancing</link><guid isPermaLink="true">http://blog.nodejitsu.com/improved-load-balancing</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Fri, 19 Apr 2013 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./nathan-zadoks-is-a-jitsuka">Nathan Zadoks is a Jitsuka!</a>]]></title><description><![CDATA[<p>Hi, earthlings! I'm Nathan Zadoks.
I live in the Netherlands, not far from Amsterdam. I'm a self-taught programmer and electronics and chemistry enthusiast. I build small things and put them together. Functions. Programs. Objects.

</p>
<p>From a young age, I've been fascinated with making systems do what I want. I fiddled with electronics and I learnt to program at age 7. I left VB for Perl, Perl for Python. I taught myself Linux, discovered the UNIX philosophy of simple, composable parts forming a powerful whole. I found node.js two years ago and loved how working with streams and composing small things was so very natural. Unfortunately, node wasn't as mature and thus I stuck with Python. About half a year ago I rediscovered node.js, the freedom of JavaScript and found the wealth of easily composable small modules in npm. This time, it stuck. (I do my best to help out with npm by triaging GitHub issues, patching small things and merging pull requests, occasionally frightening isaacs in the process.)

</p>
<h2> </h2>
<p>My other passion is RepRap, a project aiming to build self-replicating 3D printers. Perhaps our future robot overlords. Two years ago, I hopped into the RepRap IRC channel, with overly ambitious plans for cheaper RepRaps. I've been a regular ever since, helping other people the best I could with the knowledge I had acquired. My enthusiasm got me invited to the first RepRap Prusa Mendel (iteration 1) workshop to help out. I was gifted a set of RepRap parts. I've helped with a number of workshops since and helped develop the Prusa Mendel iteration 3.

</p>
<p>Trying to deploy my first serious node.js app, after checking out some of the polyglot clouds and other node.js clouds, I found Nodejitsu. <code>jitsu deploy</code>. Bam. Sensible cloud hosting. That too, stuck. I had a few issues and I was quickly helped out on IRC. I ended up staying there too, helping out people when possible. About three months ago, Maciej said I was doing a great job helping people and talking to servers and asked me if I wanted a job doing this.

</p>
<p>I just got past my three month support internship, on board, helping people kick ass on our cloud and working on getting Node 0.10 into the cloud. 
See you in #nodejitsu!

</p>
<p>\o
</p>
]]></description><link>http://blog.nodejitsu.com/nathan-zadoks-is-a-jitsuka</link><guid isPermaLink="true">http://blog.nodejitsu.com/nathan-zadoks-is-a-jitsuka</guid><dc:creator><![CDATA[Nathan Zadoks]]></dc:creator><pubDate>Fri, 29 Mar 2013 19:37:03 GMT</pubDate></item><item><title><![CDATA[<a href="./on-our-recent-downtime">On Our Recent Downtime</a>]]></title><description><![CDATA[<p>Over the course of Wednesday, March 6th through Friday, March 8th, Nodejitsu experienced its most serious service disruption to date.  A significant number of users' applications were rendered intermittently unreachable due to load balancing and routing issues.  Furthermore, a variety of circumstances combined that both increased the prevalence of the issues and prolonged the amount of time it took to reliably fix them. We consider the situation to have been completely unacceptable, and since then, the majority of our team has been working hard to ensure that it never happens again.  

</p>
<p>At this point, we'd like to take the time to explain what went wrong, and give some insight into some of the things we've been doing to make sure these issues don't repeat themselves.

</p>
<h2>Context</h2>
<p>Our unfortunate tale begins last Wednesday, March 6th.  In the early hours of the morning, our DevOps team deployed a fairly straightforward change to our load balancing layer. We use CouchDB to store app state, and the CouchDB <code>_changes</code> feed to keep our load balancers up-to-date when apps are created, destroyed, or deployed to new drone servers. We had, up until this point, been using custom code to follow the <code>_changes</code> feed with Node's HTTP API, but had decided to switch to using <a href="https://github.com/iriscouch/follow">follow</a> instead.  We made the changes, we reviewed the changes, and the changes spent time in our staging environment being tested.  Everyone, myself included, was confident that this change would both eliminate the few occasional hiccups we'd been seeing with the <code>_changes</code> feed from time to time, and would also be too straightforward to introduce new problems.  So, in the wee hours of Wednesday, we deployed it to production.

</p>
<h2>The Problems</h2>
<p>As anyone who's ever tried to write a serious benchmark of a network service can tell you, it's not easy to replicate large amounts of authentic internet traffic for testing.  It's easy to make one computer, or several, make lots and lots of requests to the same host.  The real-world experience of having millions of people all over the world making requests to your site or service, however - requests from different operating systems, different hardware, all travelling over completely different network paths - is extremely difficult to replicate accurately. Needless to say, the testing our balancers got in our staging environment did not turn out to be a reasonable facsimile of our usual production load.

</p>
<p>In and amongst all of the events which unfolded, there was required travel taking place on Thursday and Friday for two key members of our DevOps team, including my own flight for my move from San Francisco back home to New York. 

</p>
<p>Wednesday, and most of Thursday, stayed quiet.  The trouble with a subtle bug that produces an incorrect state is that it starts out as an occasional, sporadic issue - if thousands of apps are working fine, but one user is seeing a problem, simple deduction suggests that the issue, while not necessarily the user's fault, lies with some aspect of their app that sets it apart from the rest of the apps in question.  Since this looked like a few odd users seeing something strange, and not like a large systemic problem, our support engineers began investigating the apps in question rather than our infrastructure.

</p>
<p>In the meantime, they offered a simple workaround: if a user runs <code>jitsu apps start</code> on their app, the app will be deployed to a new drone, the database will be updated, and the balancers will receive the new network location for the app.  In almost all cases, this returns the app in question to a working state, and gives us time to look at what happened without giving our users serious downtime.
Sometime around dawn UTC on Friday, a few of our users who were affected by the current problems cleverly decided to make scripts for themselves, that would run <code>jitsu apps start</code> over and over and over.  While I don't fault our users for taking measures to ensure their uptime, this very quickly escalated into a situation of "deploy spam" - a significant number of users got fancy with Node's <code>child_process</code> module, and had several concurrent instances of <code>jitsu</code> in memory, all trying to start the same app over and over.

</p>
<p>If you think that sounds a lot like an accidental DDoS, you're right.

</p>
<p>By the time my flight was departing from San Francisco early Friday, it had become apparent that this was a subtle and systemic problem - it was still only affecting a very small percentage of apps, but it was affecting "too simple to fail" apps (simple tests and the like) and, most importantly, different load balancers would respond differently, indicating a more pervasive issue.  We gathered our Ops team, as best we were able, given the travel circumstances, and began investigating in earnest.

</p>
<p>By mid morning, our deployment infrastructure was under a level of load that surpassed what we saw during the last hour of Node Knockout this past year.  We were up around 20-30x normal deploy traffic from the aggressive workarounds, and our CouchDB started feeling the strain.  The balancers started to get even more out-of-sync with one another, and deploys started to fail from CouchDB timeouts and other related issues.

</p>
<p>And that brings me to the other bug.

</p>
<p>We operate with a pool of free drone servers, under normal circumstances - when it gets below a certain threshold, auto-provisioning algorithms kick in and start provisioning new VMs to add extra capacity to our cloud.  This process is sometimes manual, but it generally requires very little attention from DevOps.

</p>
<p>Under a massive sudden load spike, however, and with serious ongoing database issues, the free drone pool got very low, and the high error rate led to more inconsistent state.  This time, several attempts to <code>jitsu apps start</code> would all wind up receiving a success message, and all wind up telling the database - and therefore the balancers - that they were on the same IP address.

</p>
<p>Our standard drone VMs are small - 256MB of RAM - and we only provision one app per small VM.  They really just don't work well otherwise.

</p>
<p>The problem, then, is what happens, for example, when three or four Express apps, all using the default port 3000, all hit the same IP address.  Only one app - usually the last one to start - would be running successfully, and the other users would visit their URL, and see a completely different site.

</p>
<h2>Recovery</h2>
<p>By the time this happened, we realized it was time to admit defeat, roll back our balancer changes, and start looking into ways to lessen the load.  We put our API into a short emergency maintenance, let everything calm down a little, added a lot of new capacity to our drone pool, and reverted to the pre-Wednesday version of our load balancers, prior to the switch to <code>follow</code>.

</p>
<p>While this was going on, Maciej Malecki, our self-styled Hotfixer-in-Chief, attacked our provisioning service head-on, and successfully found and fixed the edge case that allowed apps to incorrectly be deployed to already-used drones when the pool was empty.  With the balancers reverted, and this edge case fixed, the cloud rapidly returned to normal.

</p>
<h2>Where We Go From Here</h2>
<p>We're determined that these issues - or any issues of this size and scope - not happen again, and we’ve taken the following measures towards prevention:

</p>
<ul>
<li>We have initiated a complete overhaul of both our staging environment and our staging practices, and reaching for new heights of OCD-level Continuous Integration and QA.  </li>
<li>Our staging environment has been completely replaced. As of this writing, every VM in question was deleted and reprovisioned from scratch.</li>
<li>We're phasing out most of our manual QA in favor of an automatic deployment bot that will send amusing, demeaning emails to the team whenever app deploys don't work in staging.  </li>
<li>Implemented an improved approach to internal load testing in staging, seeking to better answer the complex question of how to accurately simulate real traffic from the wild internet, and avoid any more sudden surprises when new code meets production load.</li>
<li>We are greatly expanding and decentralizing our CouchDB, to prevent any database growing pains as we continue to scale.</li>
<li>In the future, scheduled deploys won’t happen if several senior members of the DevOps team aren’t available due to travel or other circumstances.</li>
</ul>
<p>In closing, I apologize profusely.  Issues like this are unacceptable in any hosting provider, and our commitment to being the best Node.js host out there won't let us let things like this slide.


</p>
]]></description><link>http://blog.nodejitsu.com/on-our-recent-downtime</link><guid isPermaLink="true">http://blog.nodejitsu.com/on-our-recent-downtime</guid><dc:creator><![CDATA[Charlie McConnell]]></dc:creator><pubDate>Mon, 18 Mar 2013 19:30:33 GMT</pubDate></item><item><title><![CDATA[<a href="./content-delivery-network-in-node-js">Versions: The Node.js Content Delivery Network</a>]]></title><description><![CDATA[<p>At Nodejitsu we focus on providing our users with the best developer
experience possible -- something we can't achieve if our sites take too long to load.
This is why we focused on front-end performance when we rebuild our new
<a href="https://www.nodejitsu.com/">front-page</a>. The best front-end performance can be achieved by loading a
minimal quantity of resources as fast as possible. So having a good static server
is vital! Unfortunately serving static files isn't something Node.js
is designed for. For example it's missing essential <code>sendfile</code>
bindings which allow you to transfer files over sockets with minimal context switching. The only way to create a high performance file server in Node is to cache aggressively.

</p>
<p>Today we're pleased to announce the release of my latest open source project, <a href="http://github.com/3rd-eden/versions">versions</a>.

</p>
<h2> </h2>
<p>Versions allows you to create a small scale content delivery network using Node.js. It
gets its performance by caching file lookups in memory and setting
aggressive caching headers. The fastest request is one that you don't have to 
make! The server comes with a wide range of features that most
public paid CDN's also support:

</p>
<ul>
<li>Origin pull, the ability to fetch resources from remote servers and cache
them on the server.</li>
<li>Cache Headers, versions will automatically configure cache headers for you.</li>
<li>Advanced &amp; automatic GZIP, It gzips your resources automatically for browsers
that support it (except IE5/6) and detects obfuscated gzip headers as
researched by the <a href="http://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/">Yahoo Performance team</a>.</li>
<li>REST API, providing a REST API to manage the server.</li>
<li>Clusters, when ran in clusters it can synchronize configuration and other
details between servers using a Redis engine.</li>
</ul>
<p>Creating the server is really simple:

</p>
<p><div class="snippet"><pre><code><span class="comment">// </span>Require the versions module
var versions = require('versions');

<span class="comment">// </span>Setup some origin servers where we want to pull the content from and tag them
<span class="comment">// </span>with an id, optionally setup some syncing to be ready to roll.
versions.<span class="keyword">set</span>('origin servers', [
    { url: 'https:<span class="comment">//w</span>ww.nodejitsu.com', id: 'home' },
    { url: 'https:<span class="comment">//w</span>ebops.nodejitsu.com', id: 'webops' },
    { url: 'https:<span class="comment">//g</span>ravatar.com/userimage/', id: 'gravatar' }
  ])
  .<span class="keyword">set</span>('sync', <span class="literal">true</span>)
  .<span class="keyword">set</span>('redis', { host: 'localhost', port: '<span class="number">6379</span>', auth: 'pass' })
  .listen(<span class="number">8080</span>);
</code></pre></div>

</p>
<p>As you can see in the snippet above, we are setting 3 origin servers where we
will pull our assets from. This allows us, for example, to fetch our base CSS from
<a href="https://www.nodejitsu.com">https://www.nodejitsu.com</a> and another CSS file from <a href="https://webops.nodejitsu.com">https://webops.nodejitsu.com</a>
and cache our Gravatar look ups:

</p>
<ul>
<li><code>http:<span class="comment">//e</span>xample.com/css/base.css</code> would only load the base.css from our home
origin as it's the only server that contains this file.</li>
<li><code>http:<span class="comment">//e</span>xample.com/css/foo.css</code> would be loaded from the WebOps origin as it
doesn't exist on the home server.</li>
<li><code><span class="identifier">http</span><span class="symbol">:</span>/<span class="regexp">/example.com/</span><span class="number">15003245</span>/<span class="number">847041</span><span class="identifier">ab43d45ec001bd9ef611f2184c</span>.<span class="identifier">jpg?</span><span class="identifier"><span class="keymethods">size</span></span>=<span class="number">40</span></code> would
load an avatar from Gravatar as both WebOps and home doesn't have this file.</li>
</ul>
<h3>Cache busting</h3>
<p>The problem with aggresive caching is that it's harder to serve your users
fresh content when you make changes to your assets. If left unattended users 
will see the cached version of their browser. The solution? Implement a cache
busting scheme. As query strings are known to cause cache issues with reverse
proxies we decided to prefix our files using a custom path instead. This would
allow us to "bust" browser cache by referencing the file from a
different path. In versions you can prefix your assets with a special
<code>/versions:&lt;cache bust string&gt;</code> string, for example
<code>http:<span class="comment">//e</span>xample.com/versions:daf3daf87Adf/base.css</code> would be internally
rewritten to <code>http:<span class="comment">//e</span>xample.com/base.css</code>

</p>
<p>This introduces consistency problems since you might have different applications 
that use the same CDN and assets. To ensure all your applications are
referencing files with identical cache busters we have created an API client.
The API can sync version strings between different connected clients.

</p>
<p><div class="snippet"><pre><code><span class="comment">// </span>Require the versions module.
var versions = require('versions');

<span class="comment">// </span>Enable syncing using the .<span class="keyword">set</span>(config, value) API and connect to your versions
<span class="comment">// </span>instance using the .connect method.
versions.<span class="keyword">set</span>('sync', <span class="literal">true</span>)
  .<span class="keyword">set</span>('redis', { host: 'localhost', port: '<span class="number">6379</span>', auth: 'pass' })
  .connect('http:<span class="comment">//e</span>xample.com');
</code></pre></div>

</p>
<p>The client will sync its configuration with the server using the provided Redis
configuration and setup a pub/sub connection for constant version changes. In
order to "tag" your assets with the synced cache buster you can use the
<code>versions.tag('path');</code> method. If you supply it with the path <code>/foo/bar.js</code> it
will return <code>http:<span class="comment">//e</span>xample.com/versions:<span class="number">0.0</span>.<span class="number">0</span>/foo/bar.js</code>.

</p>
<h3>Clusters &amp; multiple origins</h3>
<p>Versions has support for clusters out of the box -- at Nodejitsu we run it on
multiple drones. You only need to set the <code><span class="identifier"><span class="keymethods">sync</span></span></code> configuration
and supply it with your redis details and it's ready to go.

</p>
<p><div class="snippet"><pre><code>var versions = require('versions');

<span class="comment">// </span>Setup syncing like before
versions.<span class="keyword">set</span>('sync', <span class="literal">true</span>)
  .<span class="keyword">set</span>('redis', { host: 'localhost', port: '<span class="number">6379</span>', auth: 'pass' })
  .connect('http:<span class="comment">//e</span>xample.com');

<span class="comment">// </span>Setup more alias servers so you can spread resources across different servers
<span class="comment">// </span>or to increase parallel download of resources
versions.alias('http:<span class="comment">//e</span>xample.org')
        .alias('http:<span class="comment">//e</span>xample.net');

<span class="comment">// </span>Tag your assets on the fly using:
versions.tag('/filepath.js'); <span class="comment">// </span>http:<span class="comment">//e</span>xample.com/versions:<span class="number">0.0</span>.<span class="number">0</span>/filepath.js
versions.tag('/bar.css'); <span class="comment">// </span>http:<span class="comment">//e</span>xample.net/versions:<span class="number">0.0</span>.<span class="number">0</span>/bar.css
</code></pre></div>

</p>
<p>In addition to running clustered the API client also accepts multiple origin
servers. It will balance your assets between supplied servers using the
<a href="http://github.com/3rd-eden/node-hashring">node-hashring</a> module. Ensuring load and cache size are distributed
equally. This comes with the benefit of parallel downloading as each host can 
only download 4-8 assets at the same time.

</p>
<p>So if you ever need a high performance static server for your Node.js
application feel free to take <a href="http://github.com/3rd-Eden/versions">http://github.com/3rd-Eden/versions</a> for a spin.

</p>
<h3>The CDN in Action</h3>
<p>Both Nodejitsu's website and handbook are powered by our CDN. Over the last
weeks we integrated our documentation with the website. Formerly, our
documentation was accessible on a separate domain outside the website. We changed 
our handbook module to a dependency of the website, to provide a more consistent 
look and feel. In addition, we changed handbook from a blacksmith powered
static file server to a Markdown document collection.

</p>
<p><img src="/content-delivery-network-in-node-js/before-after.png" alt="" />

</p>
<p>Beside we think it looks better, thats nothing special right? But how
are we gonna serve images in the Markdown content without storing them remotely
or relying on some third party storage. This is where versions comes into play.
We can simply call <code>https:<span class="comment">//v</span>ersions.nodejitsu.com/resources/img.png</code> to acquire
the image. If it is not yet available on our CDN it will be fetched from the
configured external resources. This allows us to keep content centralized. Also
handbook is explicitly about serving Markdown content. Versions will keep images in
cache and ensure our website will serve documents blazing fast.

</p>
<p><img src="/content-delivery-network-in-node-js/images.png" alt="" />

</p>
<p>The old handbook site loaded our <a href="https://www.nodejitsu.com/documentation/features/webops">WebOps documentation</a> in a un-cached
state in 5.1 seconds. The new documentation does this in 3.67 seconds. With
primed cache you were still looking at 3.7 seconds for the old site and only
1.7 seconds for the new version. We think this isn't bad for a page full of big images.
So we saved about <strong>2 seconds</strong> of load time by using versions. 

</p>
<p>Try it out for yourself! Want to see our CDN in action? Visit
<a href="http://www.nodejitsu.com/">nodejitsu.com</a> or <a href="http://www.nodejitsu.com/documentation">nodejitsu.com/documentation</a>.

</p>
]]></description><link>http://blog.nodejitsu.com/content-delivery-network-in-node-js</link><guid isPermaLink="true">http://blog.nodejitsu.com/content-delivery-network-in-node-js</guid><dc:creator><![CDATA[Arnout Kazemier]]></dc:creator><pubDate>Thu, 07 Mar 2013 09:51:48 GMT</pubDate></item><item><title><![CDATA[<a href="./business-plans">Nodejitsu Business Plans Are Here!</a>]]></title><description><![CDATA[<p>Since we announced our paid <a href="http://blog.nodejitsu.com/paid-individual-plans">Individual Plans</a> in October of 2012 (5 months ago), thousands of you have deployed to Nodejitsu, gotten in touch with us in IRC, and tested our platform to see what its made of. We’ve gotten to see what horizontally scaled 256MB slices of virtual machines <a href="http://konklone.com/post/the-making-of-isitchristmas-dot-com-2012">can do</a>, and how far node can take us in the world of DevOps. But our Individual Plans were always intended for small, lightweight apps. We all wanted more.

</p>
<p>Today, we’re very excited to announce the launch of our <a href="">Business Plans</a>, fueled by a new partnership with <a href="http://www.telefonica.com/en/home/jsp/home.jsp">Telefonica</a>. Business Plans deliver greater reliability and selection for small to medium companies who are looking to host mission critical applications. 

</p>
<p><img src="/business-plans/biz_plan_screenshot.png" alt="" />

</p>
<p>What makes Business Plans different? 

</p>
<h3>Flexible VM sizes for increased reliability</h3>
<p>Business Plans give you the ability to select the size of the VM that you’re deploying to.  Business Plan customers will be able to choose between 256MB, 512MB, and 1024MB VMs. This significantly increases reliability, and reduces the complexity and degree of horizontal scaling required to handle increased load.

</p>
<p>It'll look a little something like this:
</p>
<pre><code>$ jitsu deploy joyent us-sw-<span class="number">1</span> --drones <span class="number">2</span>
info:    Welcome to Nodejitsu jitsuka
info:    jitsu v0.<span class="number">12.0</span>, node v0.<span class="number">8.19</span>
info:    It worked <span class="keyword">if</span> it ends <span class="keyword">with</span> Nodejitsu ok
info:    Executing command deploy joyent us-sw-<span class="number">1</span>
info:    Fetching app nodejitsuftw
info:    App currently deployed to
data:    {
data:        datacenter: <span class="string">'us-east-1'</span>,
data:        ram: <span class="number">256</span>,
data:        drones: <span class="number">1</span>,
data:        provider: <span class="string">'joyent'</span>
data:    }
info:    Deploying application <span class="keyword">in</span> cloud <span class="keyword">with</span>:
data:    {
data:        datacenter: <span class="string">'us-sw-1'</span>,
data:        ram: <span class="number">256</span>,
data:        drones: <span class="number">2</span>,
data:        provider: <span class="string">'joyent'</span>
data:    }
info:    App example is now started
info:    http:<span class="comment">//nodejitsuftw.jyt.us.sw1.nodejitsu.com on Port 80</span>
info:    Nodejitsu ok</code></pre>
<h3>Choose your infrastructure provider, and datacenter</h3>
<p>You now have the choice of Telefonica and Joyent, and a variety of datacenters to deploy to. As of today, we have support for Joyent’s datacenters in Virginia, Las Vegas and Amsterdam, and Telefonica’s datacenter in London.

</p>
<p>For example:

</p>
<pre><code>$ jitsu cloud list
info:    Welcome to Nodejitsu jitsuka
info:    jitsu v0.<span class="number">12.0</span>, node v0.<span class="number">8.18</span>
info:    It worked <span class="keyword">if</span> it ends <span class="keyword">with</span> Nodejitsu ok
info:    Executing command cloud list
info:    You can use one of the following providers
data:    jitsu cloud joyent us-east-<span class="number">1</span>
data:    jitsu cloud joyent us-sw-<span class="number">1</span>
data:    jitsu cloud joyent eu-ams-<span class="number">1</span>
data:    jitsu cloud telefonica eu-london-<span class="number">1</span>
info:    Nodejitsu ok</code></pre>
<p>This means you can choose your location, and reduce your app’s latency to your customers <em>that matter.</em> 

</p>
<pre><code>$ jitsu cloud joyent us-sw-<span class="number">1</span>
info:    Welcome to Nodejitsu jitsuka
info:    jitsu v0.<span class="number">12.0</span>, node v0.<span class="number">8.19</span>
info:    It worked <span class="keyword">if</span> it ends <span class="keyword">with</span> Nodejitsu ok
info:    Executing command cloud joyent us-sw-<span class="number">1</span>
info:    Fetching app example
info:    App currently deployed to
data:    {
data:        datacenter: <span class="string">'us-east-1'</span>,
data:        ram: <span class="number">256</span>,
data:        drones: <span class="number">1</span>,
data:        provider: <span class="string">'joyent'</span>
data:    }
info:    Deploying application <span class="keyword">in</span> cloud <span class="keyword">with</span>:
data:    {
data:        datacenter: <span class="string">'us-sw-1'</span>,
data:        ram: <span class="number">256</span>,
data:        drones: <span class="number">1</span>,
data:        provider: <span class="string">'joyent'</span>
data:    }
info:    App example is now started
info:    http:<span class="comment">//example.jyt.us.sw1.nodejitsu.com on Port 80</span>
info:    Nodejitsu ok</code></pre>
<h3>High Performance Webops</h3>
<p>All of these new features are also available in our <a href="https://webops.nodejitsu.com">Webops dashboard</a> which has gotten a complete overhaul to <a href="https://github.com/learnboost/engine.io">engine.io</a>.

</p>
<h3>Full support for Europe!</h3>
<p>These new features, and our partnership with Telefonica mean one more thing: we now have full support for Europe. Telefonica, one of the world’s largest Telecommunications companies, has recently launched its <a href="http://cloud.telefonica.com/instantservers/">Instant Servers</a>, offering Joyent’s cutting-edge cloud technology to users from its own, growing selection of datacenters.  Combined with Nodejitsu’s unparalleled Node.js PaaS, this will enable Node-based sites and apps to server users in the European market like never before.plans

</p>
<h4>Ready to take your hosting to the next level? <a href="https://www.nodejitsu.com/paas/pricing">Let's do this!</a></h4>
<h3>Wait...did you think that was it?</h3>
<p>Just in case that’s not enough for you, <em>we also launched a new, improved version of our frontend website, <a href="http://nodejitsu.com/">Nodejitsu.com</a>.</em> Our rebranded site is meant to make it easier to understand how our product works, and who we are. We also think it looks a whole lot slicker.

</p>
<p><img src="/business-plans/nodejitsu_new_home.png" alt="" />

</p>
<p>Thanks for hosting with us! We’re glad to have you on board.





</p>
]]></description><link>http://blog.nodejitsu.com/business-plans</link><guid isPermaLink="true">http://blog.nodejitsu.com/business-plans</guid><dc:creator><![CDATA[Ana Hevesi]]></dc:creator><pubDate>Tue, 12 Feb 2013 17:30:00 GMT</pubDate></item><item><title><![CDATA[<a href="./waiting-for-godot">Waiting for Godot</a>]]></title><description><![CDATA[<p>Monitoring sucks, <a href="https://github.com/monitoringsucks">right?</a>. At Nodejitsu, we run a large distributed system <a href="http://nodejitsu.com/enterprise/products.html">with next-to-zero external dependencies</a>. Designing a monitoring solution that met our needs of:

</p>
<ul>
<li>Able to handle thousands of messages per second.</li>
<li>Scaling to accommodate the dynamic needs of thousands of applications.</li>
<li>Flexibility to make decisions based on various criteria.</li>
</ul>
<p>was challenging. In fact, it is something we've tried to address in several implementations. Over the past two years, it was clear the team that we needed something new. <strong>Today we are happy to announce that we are releasing this new solution, <a href="https://github.com/nodejitsu/godot">godot</a> as Open Source software under the MIT license.</strong>

</p>
<h2>Prior Art</h2>
<p>There <a href="http://www.nagios.org/">are</a> <a href="http://www.newrelic.com">an</a> <a href="http://ganglia.sourceforge.net/">endless</a> <a href="http://www.boundary.com/">number</a> of <a href="http://www.pingdom.com">monitoring</a> solutions out there. There was one that caught our eye when considering our needs: <a href="http://riemann.io">Riemann</a>. Riemann stood out because it is designed as a <strong><a href="http://en.wikipedia.org/wiki/Complex_event_processing">complex event processor</a>.</strong> In their own words:

</p>
<blockquote>
<p>Riemann provides low-latency, transient shared state for systems with many moving parts.

</p>
</blockquote>
<p>The events the Riemann processes are simple, with a single <code>metric</code> property representing <em>a single numeric value for the event.</em> <strong>Godot uses this same event format for the structure of events.</strong> 

</p>
<p><div class="snippet"><pre><code>{
  host:         "A hostname, e.g. 'api1', 'foo.com'"
  service:      "e.g. 'API port 8000 reqs/sec'",
  state:        "Any string less than 255 bytes, e.g. 'ok', 'warning', 'critical'",
  time:         "The time of the event, in unix epoch seconds",
  description:  "Freeform text",
  tags:         "Freeform list of strings, e.g. ['rate', 'fooproduct', 'transient']"
  metric:       "A number associated with this event, e.g. the number of reqs/sec."
  ttl:          "A floating-point time, in seconds, that this event is valid for."
}</code></pre></div>

</p>
<p>When we dug into the Reimann codebase, obviously being predispositioned to <a href="http://nodejs.org">node.js</a>, the overwhelming feeling was that <em>it felt to heavy-weight and <a href="https://github.com/aphyr/riemann/blob/master/src/riemann/streams.clj#L550-L592">a little bit obtuse</a>.</em> That and the strong emphasis on streams made this type of system an ideal candidate for a node.js incantation.

</p>
<p><strong>Enter godot.</strong>

</p>
<h2>Introducing Godot</h2>
<p>Lets jump right in. A common use-case for monitoring is ensuring that everything is still running using <a href="http://en.wikipedia.org/wiki/Heartbeat_network">heartbeats</a>. In <code>godot</code> you just need to declare <em>a client to send heartbeats and a server to ensure heartbeats are received.</em>

</p>
<p>Both of these operations can be done <strong>in a single line of Javascript.</strong> First lets focus on the server:

</p>
<p><strong>server.js</strong>
<div class="snippet"><pre><code>var godot = require('godot');

<span class="comment">//</span>
<span class="comment">// </span>Reactor server which will email `user@host.com`
<span class="comment">// </span>whenever any service matching /.*\/health\/heartbeat/
<span class="comment">// </span>fails to check <span class="keyword">in</span> after <span class="number">60</span> seconds.
<span class="comment">//</span>
godot.createServer({
  <span class="comment">//</span>
  <span class="comment">// </span>Defaults to tcp
  <span class="comment">//</span>
  type: 'tcp',
  reactors: [
    godot.reactor()
      .where('service', '*/health/heartbeat')
      .expire(<span class="number">1000</span> * <span class="number">60</span>)
      .email({ to: 'user@host.com' })
  ]
}).listen(<span class="number">9876</span>);</code></pre></div>

</p>
<p>Now that the server is listening for connections from heartbeat clients, lets create a client to start sending messages.

</p>
<p><strong>client.js</strong>
<div class="snippet"><pre><code>var godot = require('godot');

<span class="comment">//</span>
<span class="comment">// </span>Producer client which sends events <span class="keyword">for</span> the service
<span class="comment">// </span>`app.server/health/heartbeat` every <span class="number">15</span> seconds.
<span class="comment">//</span>
godot.createClient({
  <span class="comment">//</span>
  <span class="comment">// </span>Defaults to TCP
  <span class="comment">//</span>
  type: 'tcp',
  producers: [
    godot.producer({
      host: 'app.server.com'
      service: 'app.server/health/heartbeat',
      ttl: <span class="number">1000</span> * <span class="number">15</span>
    })
  ]
}).connect(<span class="number">9876</span>);</code></pre></div>

</p>
<p>Both the <code>.createClient</code> and the .<code>createServer</code> methods of <code>godot</code> accept <strong>multiple producers and reactors</strong> <em>(respectively)</em> allowing you to compose complex behavior from multiple simple streams.

</p>
<p><img style="margin: 0 0 0 150px;" src="/waiting-for-godot/godot-overview.png" />
<br /><span style="margin-left: 170px;"><strong>Figure 1: High-level Godot Architecture</strong></span>

</p>
<p>Lets examine the dataflow of a simple reactor that sends <code><span class="identifier">ops</span><span class="variable">@host</span>.<span class="identifier">com</span></code> an email whenever the CPU load of a server goes above 50%. 

</p>
<p><div class="snippet"><pre><code>godot.reactor()
  .where('service', 'cpu')
  .over(50)
  .email({ to: 'ops@host.com' });</code></pre></div>

</p>
<p><img style="margin: 0 0 0 50px;" src="/waiting-for-godot/email-flow.png" />
<br /><span style="margin-left: 170px;"><strong>Figure 2: Data-flow for sending email on high CPU load</strong></span>

</p>
<p>This is obviously <em>very naive</em> and you should probably perform somekind of <a href="http://en.wikipedia.org/wiki/Exponential_smoothing#The_exponential_moving_average">exponentially decaying moving average</a> to avoid false-positives on short-lived spikes (<code>godot</code> has EWMA built-in via the <a href="https://github.com/indexzero/window-stream">window-stream</a> module).

</p>
<p><div class="snippet"><pre><code><span class="identifier">var</span> <span class="constant">windowStream</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'window-stream'</span>),
    <span class="identifier">godot</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'godot'</span>);

<span class="identifier">var</span> <span class="constant">M1_ALPHA</span> = <span class="number">1</span> - <span class="constant">Math</span>.<span class="identifier">exp</span>(-<span class="number">5</span>/<span class="number">60</span>);

<span class="identifier">godot</span>.<span class="identifier">reactor</span>()
  .<span class="identifier">where</span>(<span class="string">'service'</span>, <span class="string">'cpu'</span>)
  .<span class="constant">movingAverage</span>({
    <span class="identifier">average</span><span class="symbol">:</span> {
      <span class="identifier"><span class="keymethods">type</span></span><span class="symbol">:</span> <span class="string">'exponential'</span>,
      <span class="identifier">alpha</span><span class="symbol">:</span> <span class="constant">M1_ALPHA</span>
    },
    <span class="identifier">window</span><span class="symbol">:</span> <span class="identifier"><span class="keymethods">new</span></span> <span class="constant">windowStream</span>.<span class="constant">EventWindow</span>({ <span class="identifier"><span class="keymethods">size</span></span><span class="symbol">:</span> <span class="number">10</span> })
  })
  .<span class="identifier">over</span>(<span class="number">50</span>)
  .<span class="identifier">email</span>({ <span class="identifier">to</span><span class="symbol">:</span> <span class="string">'ops@host.com'</span> });
  </code></pre></div>

</p>
<h2>Performance</h2>
<p>Before writing this, I noticed a recent post from <a href="http://aphyr.com/posts/269-reaching-200k-events-sec">aphyr</a> (the author of Riemann) discussing in intimate detail how he has achieved <em>200k messages per second in Riemann.</em> This intrigued me to see just how this little node program stacked up:

</p>
<p><div class="snippet"><pre><code><span class="identifier">node</span> <span class="identifier"><span class="keymethods">test</span></span>/<span class="identifier">perf</span>/<span class="identifier">pummel</span>.<span class="identifier">js</span> -<span class="identifier">c</span> <span class="number">5</span>
<span class="constant">Starting</span> <span class="identifier">performance</span> <span class="identifier"><span class="keymethods">test</span></span> <span class="identifier">with</span><span class="symbol">:</span>
  <span class="identifier">network</span> <span class="identifier">protocol</span>  <span class="identifier">tcp</span>
  <span class="identifier">concurrency</span><span class="symbol">:</span>      <span class="number">5</span>
  <span class="identifier">sampling</span> <span class="identifier">interval</span> <span class="number">10</span><span class="identifier">s</span>
  <span class="identifier">duration</span><span class="symbol">:</span>         <span class="number">10</span><span class="identifier">s</span>
  <span class="identifier">ttl</span><span class="symbol">:</span>              <span class="number">0</span>
  <span class="identifier">port</span><span class="symbol">:</span>             <span class="number">10557</span>
 
<span class="constant">Starting</span> <span class="identifier">reactor</span> <span class="number">1</span>
<span class="constant">Starting</span> <span class="identifier">producer</span> <span class="number">1</span>
<span class="constant">Starting</span> <span class="identifier">producer</span> <span class="number">2</span>
<span class="constant">Starting</span> <span class="identifier">producer</span> <span class="number">3</span>
<span class="constant">Starting</span> <span class="identifier">producer</span> <span class="number">4</span>
<span class="constant">Starting</span> <span class="identifier">producer</span> <span class="number">5</span>
 
<span class="constant">Now</span> <span class="identifier">receiving</span> <span class="identifier">messages</span>...
 
<span class="constant">Received</span><span class="symbol">:</span>
  <span class="number">1069482</span> <span class="identifier">total</span> <span class="identifier">messages</span>
  <span class="number">106948.2</span> <span class="identifier">per</span> <span class="identifier">second</span></code></pre></div>

</p>
<p>So <em>with little or no attention paid to performance</em> we're already processing <strong>100k messages per second in node.</strong> This makes sense because this sort of IO bound application is exactly what node.js was designed for. I suspect (but have not yet had the time to investigate) that this 100k / second benchmark could be faster because it is deficient in several places:

</p>
<ol>
<li>Single reactor process: the underlying sockets are not shared between multiple processes.</li>
<li>Not distributed: this benchmark was both producing and consuming data from the same machine, so there would be plenty of spare CPU if the messages were produced on a second machine.</li>
<li>No framing: As aphyr points out, combing multiple messages into a single TCP packet can greatly increase network throughput, I'm eager to try this out.</li>
</ol>
<h2>So what is Orchestrion?</h2>
<p>If you've been following Nodejitsu then you've probably read about our monitoring product, <a href="http://nodejitsu.com/enterprise/products.html">Orchestrion</a>. <em>Orchestrion is built on-top of Godot adding primitives for orchestrating cloud applications:</em>

</p>
<ul>
<li><strong>Network monitoring:</strong> Concerned about network or HTTP latency? We've got you covered.</li>
<li><strong>Server and application provisioning:</strong> Wouldn't you like to just scale your app instead of <em>telling your ops team to scale your app?</em></li>
<li><strong>SSH:</strong> Run arbitrary processes on demand to respond to incidents.</li>
<li><strong>Process monitoring:</strong> Notify your team through alerting tools when crashes occur.</li>
</ul>
<p>Lets consider how the above example, <em>emailing your ops team on high CPU load</em>, could be handled with Orchestrion:

</p>
<p><img style="margin: 0 0 0 50px;" src="/waiting-for-godot/provision-flow.png" />
<br /><span style="margin-left: 170px;"><strong>Figure 3: Data-flow for scaling your app on high CPU load</strong></span>

</p>
<p>Automating these common tasks frees up your developers and operations engineers to handle higher-level more important problems like <strong>building your application and your business.</strong>

</p>
<p>Interested in learning more? <strong>Why don't you request a quote for our <a href="http://nodejitsu.com/company/contact.html">Enterprise Product</a>.</strong> If you're using our Public Cloud product today then stay tuned: <em>we'll be integrating many of these higher level features of Orchestrion into the platform soon.</em>

</p>
<p><br /><hr />
<a href="http://thenounproject.com/noun/cloud/#icon-No6853" target="_blank">Cloud</a> designed by <a href="http://thenounproject.com/pjsmits" target="_blank">Pieter J. Smits</a> from The Noun Project.

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

</p>
]]></description><link>http://blog.nodejitsu.com/waiting-for-godot</link><guid isPermaLink="true">http://blog.nodejitsu.com/waiting-for-godot</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Fri, 01 Feb 2013 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./opensource-dot-jitsu">Free Open Source Hosting on Nodejitsu</a>]]></title><description><![CDATA[<p>The team at Nodejitsu knows what its like to <a href="https://github.com/nodejitsu">maintain open source software</a>. We all want to see a thriving OSS community, so as part of our service, we'll provide you with a drone to host your open source app on Nodejitsu for free.

</p>
<p>We first discussed this when we launched our <a href="http://blog.nodejitsu.com/paid-individual-plans">Paid Individual Plans</a>, back in October. Now we've streamlined the process!

</p>
<p>Meet <a href="http://opensource.jit.su/">opensource.jit.su</a>:


</p>
<p><img src="/opensource-dot-jitsu/opensourcejitsu-screenshot.png" alt="" />




</p>
<p>As we say on the page, just fill in your info, and our team will get back to you soon. Big thanks to <a href="https://twitter.com/julian_duque">Julian Duque</a> and <a href="https://twitter.com/karolinaszczur">Karolina Szczur</a> for the design and code. We're looking forward to hearing from you!






</p>
]]></description><link>http://blog.nodejitsu.com/opensource-dot-jitsu</link><guid isPermaLink="true">http://blog.nodejitsu.com/opensource-dot-jitsu</guid><dc:creator><![CDATA[Ana Hevesi]]></dc:creator><pubDate>Fri, 01 Feb 2013 01:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./julian-duque-is-a-jitsuka-">Julian Duque is a Jitsuka!</a>]]></title><description><![CDATA[<p>Please allow me to introduce myself, my name is Julián Duque and I'm from <a href="http://en.wikipedia.org/wiki/Medell%C3%ADn">Medellín</a>, <a href="http://en.wikipedia.org/wiki/Colombia">Colombia</a>, a beautiful city also known as the "City of the eternal spring". I'm a Telecommunications Engineer and a Software Development Specialist, but most importantly, I consider myself a <em>Developer by Passion</em>. I chose this title because coding is what I enjoy doing in my life on a daily basis. I believe that software should be made by passion, not by obligation.

</p>
<h2> </h2>
<p>My other passion is Education, I'm involved in the <a href="http://coderise.org/">Coderise</a> project where we teach the fundamentals of web programming with JavaScript, HTML and CSS to high school teens ages 13 to 17 years old.

</p>
<p>Also I'm the co-founder of two amazing projects, one is <a href="http://medellinjs.org">MedellinJS</a>, the local JavaScript user group, where we have one reunion monthly and about 240 members, the other is <a href="http://espuma.co">Espuma Lab</a>, a hackerspace where we will teach basic programming and electronics using mainly <a href="http://raspberrypi.org">Raspberry Pi</a> and Node.js.

</p>
<p>I felt in love with Node.js at first sight and I'm coming from a Java / Ruby background working mainly developing mobile applications APIs and Cloud Computing Services, now I'm focusing my efforts 100% to the cloud and Node.js projects.

</p>
<p>That's why I'm working at this amazing company, <a href="http://nodejitsu.com">Nodejitsu</a>, as a Support Engineer by night and Community Evangelist by day. I'm very happy because I'm working with top-notch members of the Node.js community. This is a great team!
I will be working closely with the community so I hope we will see you again.

</p>
<p>Pleased to meet you!</p>
]]></description><link>http://blog.nodejitsu.com/julian-duque-is-a-jitsuka-</link><guid isPermaLink="true">http://blog.nodejitsu.com/julian-duque-is-a-jitsuka-</guid><dc:creator><![CDATA[Julian Duque]]></dc:creator><pubDate>Fri, 25 Jan 2013 18:20:02 GMT</pubDate></item><item><title><![CDATA[<a href="./the-nodejitsu-status-page">The Nodejitsu Status Page</a>]]></title><description><![CDATA[<p><img src="the-nodejitsu-status-page/allsystemsfunctioning.png" />

</p>
<p>Say hello to Nodejitsu's new <a href="https://status.jit.su">Status Page</a>! 

</p>
<p>On the Status Page you can get info at a glance on how the cloud is doing. We wanted to give everyone a central place to go where they could check on the status of Nodejitsu services. After all, no one wants to spend valuable time debugging an issue that's actually caused by problems that Nodejitsu is experiencing. Is there any better way to blame someone else than through a beautiful web page? 
I'm joking. Kind of.

</p>
<h2> </h2>
<p>The Status Page has four sections, each representing how a different aspect of our cloud is doing. 

</p>
<ul>
<li><p>The first of these is <strong>API</strong> which refers to the status of our main Nodejitsu API - if this is having issues, deploys and account-related actions won't be working, but running apps will be unaffected. </p>
</li>
<li><p>Next are <strong>Deploys</strong>, which shows the status of deploying new versions of your application.  Deploys will be down if the API or Database is experiencing issues - or we might occasionally have scheduled maintenance.</p>
</li>
<li><p>Then there's the <strong>Database</strong>,  which refers to the database we use internally to store application and user data.  As with an API outage, this will prevent deploys and account-related actions from working, but running apps will not be affected. </p>
</li>
<li><p>Finally, we have the <strong>Balancers</strong>, which refers to the status of our load balancers.</p>
</li>
</ul>
<p>If you're looking for the Status Page on the <a href="http://nodejitsu.com/">Nodejitsu</a> website, scroll to the bottom navigation; it'll be the last link under 'PAAS'.

</p>
<p>Of course, the status page is a <a href="http://flatironjs.org/">Flatiron project</a>. On the database side of things, <a href="http://redis.io/">Redis</a> was used, just to mix it up. As always, if you experience any issues with the status page, or anything else on Nodejitsu, please let us know either in IRC at <a href="http://webchat.jit.su/">#nodejitsu</a> on irc.freenode.net or through email at support@nodejitsu.com.

</p>
]]></description><link>http://blog.nodejitsu.com/the-nodejitsu-status-page</link><guid isPermaLink="true">http://blog.nodejitsu.com/the-nodejitsu-status-page</guid><dc:creator><![CDATA[Christian Howe]]></dc:creator><pubDate>Mon, 17 Dec 2012 03:53:19 GMT</pubDate></item><item><title><![CDATA[<a href="./deployment-status-badges">Deployment Status Badges</a>]]></title><description><![CDATA[<p>Last month we announced <a href="http://blog.nodejitsu.com/github-continuous-deployment">Continuous Deployment with Github and Nodejitsu</a>. Since then we've had thousands of people using this new feature and the overall feedback from our community has been amazing.

</p>
<p>Today we are announcing Deployment Status Badges. When you're using Continuous Deployment on Nodejitsu, these let you know instantly if the deployment is in progress, has been successful, or has failed.

</p>
<h2> </h2>
<p><img src="/deployment-status-badges/handbook_badge.png" alt="Nodejitsu Continuous Deployment Badges" width="90%" />

</p>
<p>If you want to use them it's super simple: If your username in Github was <code>yawnt</code> and the repo was called <code>myblog</code> all you need to do is to add the following Markdown to your <code>readme.md</code> file:

</p>
<pre><code class="markdown">[![Nodejitsu Deploy Status](https://webhooks.nodejitsu.com/yawnt/myblog.png)](https://webops.nodejitsu.com#yawnt/myblog)</code></pre>
<p>We've got info on our badges and a whole lot more in the new and improved <a href="http://handbook.jit.su/features/webhooks#continuous-deployment-deploying-private-repos-&amp;-commit-status-api">Nodejitsu Handbook</a>


</p>
<p>P.S. If you really love the badges don't forget to follow <a href="https://twitter.com/karolinaszczur">@karolinaszczur</a> and tell her all about it!

</p>
]]></description><link>http://blog.nodejitsu.com/deployment-status-badges</link><guid isPermaLink="true">http://blog.nodejitsu.com/deployment-status-badges</guid><dc:creator><![CDATA[Nuno Job]]></dc:creator><pubDate>Fri, 14 Dec 2012 20:15:41 GMT</pubDate></item><item><title><![CDATA[<a href="./github-continuous-deployment">Continuous Deployment with Github and Nodejitsu</a>]]></title><description><![CDATA[<p><img style="margin-left: 30px;" src="github-continuous-deployment/nodejitsu-love-github.png" />

</p>
<p><strong>Today, we would like to announce that from now on you can deploy your open-source <a href="https://github.com">Github</a> repositories directly to Nodejitsu.</strong>

</p>
<p><em>How does this work?</em> By implementing a <a href="https://github.com/github/github-services">Github service</a> for Nodejitsu, you will now be able to deploy your open-source application anytime you <strong>push a commit to Github.</strong> 

</p>
<p><em>But that's not good enough Continuous Deployment you say?</em> We have also added an integration with <a href="https://travis-ci.org/">TravisCI</a> so that you can also deploy your open-source application <strong>only after a successful test run.</strong>

</p>
<p>Open-source is a core value at Nodejitsu. We all maintain several open-source modules that make the node.js community a better place, and promote high profile projects like <a href="http://flatironjs.org/">flatiron</a> and <a href="https://github.com/nodejitsu/http-proxy">http-proxy</a> so we want to make sure that <strong>Open Source developers have the best experience available for deploying their application.</strong>

</p>
<p>Keep reading to learn all the details about getting <em>setup with Continuous Deployment on Nodejitsu!</em>

</p>
<h2> </h2>
<ul>
<li><a href="#getting-started">Getting Started</a></li>
<li><a href="#monitoring-deployments">Monitoring Deployments</a></li>
<li><a href="#working-with-travis">Working with Travis</a></li>
<li><a href="#whats-next">What's next?</a></li>
</ul>
<p><a name="getting-started"></a>
</p>
<h1>Getting started</h1>
<p>To setup continuous deployment with Github and Nodejitsu, first, access the <code>Admin</code> section on your Open Source node.js Github repository. Click <code>Service Hooks</code> and then <code>Nodejitsu</code>. You will be presented with a form with four fields:

</p>
<ul>
<li>Username, which defaults to your Github username</li>
<li>Password, your password or a valid <a href="https://handbook.nodejitsu.com/api#create-an-api-token">Nodejitsu API authentication token</a></li>
<li>Branch, where you can define the branch you wish to deploy and defaults to master</li>
<li>Endpoint, which defaults to <a href="https://webhooks.nodejitsu.com">https://webhooks.nodejitsu.com</a></li>
</ul>
<p><img alt="The Github Interface for Nodejitsu" src="https://lh4.googleusercontent.com/-kiN3YkEG_ys/UJqQ-4aGJbI/AAAAAAAADFc/esjmrqD_2IY/s945/Screenshot%252B2012-11-07%252Bat%252B16.42.57.png" style="width: 700px;" />

</p>
<p>Select <code>Active</code> and hit <code>Update Settings</code>. From now on every-time you commit to github (in the designated deployment branch) we will deploy that application for you. That simple.

</p>
<h2>But wait, I have API keys I can't commit to Github as open source?!</h2>
<p>Don't worry, you can use <code>jitsu <span class="keyword">set</span> env</code> to set environment variables that you can access with <code>process.env</code>. Check our <a href="https://handbook.nodejitsu.com/features#feature/envvars">handbook</a> for more information. Environment variables set this way persist across deployments and are also available in our <a href="https://webops.nodejitsu.com">webops</a> application. 

</p>
<p>If this is your first time getting this setup, then you probably want to set those environment variables first in a new nodejitsu application <strong>before</strong> deploying from Github. Otherwise, your first deployment will fail because the environment variables are not yet set.

</p>
<pre><code>  jitsu apps create your-app
  jitsu env <span class="keyword">set</span> &lt;key&gt; &lt;value&gt;</code></pre>
<p><a name="monitoring-deployments"></a>
</p>
<h1>Monitoring deployments</h1>
<p>There's several ways to access the deployment status in the Nodejitsu Webhook API, and you can find the complete documentation at <a href="http://webhooks.nodejitsu.com">webhooks.nodejitsu.com</a>.

</p>
<p>The most fun way to monitor your deployment is with the realtime status changes feed.

</p>
<pre><code class="bash">  #
  # if your username is foo and password is bar this would be 
  # https://foo:bar@webhooks.nodejitsu.com/1/status/foo/changes
  #
  curl https://username:password@webhooks.nodejitsu.com/1/status/username/changes?include_docs=auto</code></pre>
<p>This will create an HTTP keep alive connection that pushes the status to you in realtime every time someone invokes our API:

</p>
<pre><code class="js">  {
    "id": "https://webhooks.nodejitsu.com/1/status/dscape/changes/2b3de47c2ce04a9dda4d31aac5000a8d",
    "app_name": "hello-world-api-flatiron",
    "uuid": "5p45jm1332436661256",
    "status": "waiting",
    "provider": "github",
    "commit": "dscape/hello-world-flatiron-api/96410ed970f6224a4cd3c450150c5d65bbc77fcd"
  }
  {
    "id": "https://webhooks.nodejitsu.com/1/status/dscape/changes/2b3de47c2ce04a9dda4d31aac5000bab",
    "app_name": "hello-world-api-flatiron",
    "uuid": "aa6e9b1332436698771",
    "status": "ok",
    "provider": "travis",
    "commit": "dscape/hello-world-flatiron-api/96410ed970f6224a4cd3c450150c5d65bbc77fcd"
  }</code></pre>
<p>Each request to our API is logged with a unique <code>uuid</code>, so you can use it to refer possible issues to our support staff.

</p>
<p>We are now ready to deploy, go back to Github and click <code>Test Hook</code>. You should be up and running shortly.

</p>
<p><a name="working-with-travis"></a>
</p>
<h1>Working with Travis</h1>
<p>What about continuous integration?  We added <a href="http://travis-ci.org/">Travis-CI</a> so you can feel safe about your deployments. Simply add something like this in your <code>.travis.yml</code> file.

</p>
<pre><code>notifications:
  webhooks: 
    urls:
      - http:<span class="comment">//w</span>ebhooks.nodejitsu.com/<span class="number">1</span>/deploy
    on_success: always
    on_failure: never</code></pre>
<p>Internally our API will try to see if you have Travis configured like this, and if you do it will put the deployment request from Github on a hold until Travis informs us all tests have passed.

</p>
<p>If tests failed we won't deploy. Simple.
<br />

</p>
<p><a name="whats-next"></a>
</p>
<h1>What's next?</h1>
<p>If you don't have a Nodejitsu account sign up for one at <a href="http://nodejitsu.com">nodejitsu.com</a>. Feel free to take a peek at our <a href="http://nodejitsu.com/#/paas/getting-started">Getting Started</a> guide, and also to check out <a href="http://webops.nodejitsu.com">webops.nodejitsu.com</a> to see the status of your applications.

</p>
<p>Join #nodejitsu on irc.freenode.net and get immediate assistance from our support team! Alternatively you can email support@nodejitsu.com.
<br /><br />

</p>
]]></description><link>http://blog.nodejitsu.com/github-continuous-deployment</link><guid isPermaLink="true">http://blog.nodejitsu.com/github-continuous-deployment</guid><dc:creator><![CDATA[Nuno Job]]></dc:creator><pubDate>Thu, 29 Nov 2012 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./new-nodejitsu-handbook">New Nodejitsu Handbook</a>]]></title><description><![CDATA[<p>You may have noticed some changes to the <a href="http://handbook.jit.su">Nodejitsu Handbook on Github</a>. That's because we've completely revamped the entire handbook thanks to <a href="http://blog.flatironjs.org/01-a-whole-new-blacksmith">the new version of blacksmith</a>.

</p>
<p><img src="/new-nodejitsu-handbook/new-handbook.png" />

</p>
<h2> </h2>
<p>As great as the old handbook was it had some problems:

</p>
<ul>
<li><strong>It was just one big Markdown file.</strong></li>
<li><strong>The build system was archaic.</strong></li>
<li><strong>There was a lot of duplicated content.</strong></li>
</ul>
<p>The best part about the handbook was that it was and still is <a href="https://github.com/nodejitsu/handbook"><strong>totally open source on Github.</strong></a> Now that it is also a blacksmith powered website, we wanted to make sure that stayed the same by adding a "View on Github" button to every page.

</p>
<p><img src="/new-nodejitsu-handbook/view-on-github.png" />

</p>
<p>So now it's time to <em>go practice your nodejitsu!</em>

</p>
]]></description><link>http://blog.nodejitsu.com/new-nodejitsu-handbook</link><guid isPermaLink="true">http://blog.nodejitsu.com/new-nodejitsu-handbook</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Wed, 28 Nov 2012 17:30:00 GMT</pubDate></item><item><title><![CDATA[<a href="./introducing-pkgcloud">Introducing pkgcloud</a>]]></title><description><![CDATA[<p>During the <a href="http://nodeconf.kr/2012/">play.node()</a> conf earlier this week in Korea, Charlie took the stage and released our newest open source module. We're excited to introduce <a href="https://github.com/nodejitsu/pkgcloud">pkgcloud</a>!

</p>
<p>Pkgcloud is a node.js module that allows interaction with multiple cloud service providers. With the help of this module, you're able to manage a variety of cloud resources from within your application. You can provision compute, storage or database instances with ease. 

</p>
<p>IaaS providers have each chosen their own vocabulary for describing the resources they provide, leading to inconsistencies in terminology from one to the next. One of the objectives of pkgcloud is to maintain a unified vocabulary and use a regular terminology for applications without users needing to know which term was chosen by which provider. This is part of our ongoing efforts to be <strong>Infrastructure Agnostic</strong>.

</p>
<h2>Complete Docs</h2>
<p>You can check out the full pkgcloud documentation on Github <a href="https://github.com/nodejitsu/pkgcloud/blob/master/README.md">right here</a>. 

</p>
<p>Looking for an overview? Keep scrolling.

</p>
<h3>Vocabulary</h3>
<p>Here's how the unified vocabulary for pkgcloud breaks down. 

</p>
<h4>Compute</h4>
<table>
  <tr>
    <th>pkgcloud</th>
    <th>OpenStack</th>
    <th>Joyent</th>
    <th>Amazon</th>
  </tr>
  <tr>
    <td>Server</td>
    <td>Server</td>
    <td>Machine</td>
    <td>Instance</td>
  </tr>
  <tr>
    <td>Image</td>
    <td>Image</td>
    <td>Dataset</td>
    <td>AMI</td>
  </tr>
  <tr>
    <td>Flavor</td>
    <td>Flavor</td>
    <td>Package</td>
    <td>InstanceType</td>
  </tr>
</table>

<h4>Storage</h4>
<table>
  <tr>
    <th>pkgcloud</th>
    <th>OpenStack</th>
    <th>Amazon</th>
  </tr>
  <tr>
    <td>Container</td>
    <td>Container</td>
    <td>Bucket</td>
  </tr>
  <tr>
    <td>File</td>
    <td>StorageObject</td>
    <td>Object</td>
  </tr>
</table>

<h2>Getting Started</h2>
<p>First install the library from NPM

</p>
<pre><code>npm install pkgcloud</code></pre>
<p>Once it is installed, you can use it from your code.

</p>
<pre><code class="js">var pkgcloud = require('pkgcloud');</code></pre>
<p>At present <code>pkgcloud</code> supports: <code>compute</code>, <code>storage</code> and <code>database</code> as available resources. You can create a client to provision and control resources from your favorite provider. For client initialization, you will need the authentication info used by your provider, like <code>username</code> and <code>password</code>.

</p>
<h3>Compute</h3>
<pre><code class="js">var joyentOpts = {
  provider: 'joyent',
  username: 'daniel',
  password: '1234'
  // Also you can use key/keyId as authentication
};

var rackspaceOpts = {
  provider: 'rackspace',
  auth: 'yourTokenForRackspace'
};

var amazonOpts = {
  provider: 'amazon',
  keyId: 'YourKeyId',
  key: 'yourkey'
};

//
// Now you can create your client with your config
//

var joyentClient = pkgcloud.compute.createClient(joyentOpts), // Joyent CloudAPI client
    rackspaceClient = pkgcloud.compute.createClient(rackspaceOpts), // Rackspace Cloud Servers client
    amazonClient = pkgcloud.compute.createClient(amazonOpts); // AWS EC2 client</code></pre>
<h3>Storage</h3>
<p>You could also use the same config for <code>storage</code> resources

</p>
<pre><code class="js">var amazonClient = pkgcloud.storage.createClient(amazonOpts), // AWS S3 client
    rackspaceClient = pkgcloud.storage.createClient(rackspaceOpts); // Rackspace Cloud Files client</code></pre>
<p>After creating the client, depending on the chosen provider, <code>pkgcloud</code> will offer some methods for interaction. For detailed information about those methods, please see the complete documentation <a href="https://github.com/nodejitsu/pkgcloud">on github.</a>

</p>
<h3>Databases</h3>
<p>Database Providers supported:

</p>
<ul>
<li>IrisCouch (Couchdb and redis databases)</li>
<li>MongoLab (Mongodb databases)</li>
<li>MongoHQ (Mongodb databases)</li>
<li>RedisToGo (Redis databases)</li>
<li>Rackspace (MySQL databases)</li>
</ul>
<p>As in the previous examples, you will just need to define a few options that include the provider's name in the <code>provider</code> field and the necessary authentication fields.

</p>
<pre><code class="js">var client = pkgcloud.database.createClient(options);</code></pre>
<p>Pleease refer to github for further information about which methods are available for which provider.

</p>
<h2>A realistic example</h2>
<p>Using the newly created <code>joyentClient</code>, we will provision some compute instances.

</p>
<pre><code class="js">var flavor, image;

joyentClient.getFlavors(function (err, flavors) {
  // Choose the flavor (memory, disk, swap)
  flavor = flavors.shift();
  joyentClient.getImages(function (err, images) {
    // Choose the pre-build image
    image = images.shift();
    // Provision a new machine called 'test-server'
    joyentClient.createServer({
      flavor: flavor,
      image: image,
      name: 'test-server'
    }, function (err, server) {
      // Now look the details of your new provisioned server
      console.log(server);
    });
  });
});</code></pre>
<h2>Roadmap</h2>
<ol>
<li>Backport latest fixes from <code>node-cloudfiles</code> and <code>node-cloudservers</code></li>
<li>Include <code>CDN</code> and <code>DNS</code> services.</li>
<li>Implement <code>fs</code> compatible file API.</li>
<li>Support additional service providers.</li>
</ol>
<h2>Thinking about Contributing?</h2>
<p>We welcome contributions to <code>pkgcloud</code> by any and all individuals or organizations. 

</p>
<p>Before contributing, please take a look at the <a href="https://github.com/nodejitsu/pkgcloud/blob/master/CONTRIBUTING.md">Contribution Guidelines</a>. We are pretty flexible about these guidelines, but the more closely you follow them, the more likely we are to merge your pull-request. 

</p>
<p>SO COME ON, WHAT ARE YOU WAITING FOR?
</p>
]]></description><link>http://blog.nodejitsu.com/introducing-pkgcloud</link><guid isPermaLink="true">http://blog.nodejitsu.com/introducing-pkgcloud</guid><dc:creator><![CDATA[Daniel Aristizabal]]></dc:creator><pubDate>Fri, 23 Nov 2012 12:15:03 GMT</pubDate></item><item><title><![CDATA[<a href="./nko-2012">Node Knockout 2012!</a>]]></title><description><![CDATA[<p><a href="http://nodeknockout.com">Node Knockout</a> is just a few hours away and Nodejitsu is proud to be the official contest deployment platform! As everyone is gearing up to get into the ring, here are some helpful reminders.

</p>
<h1>Don't want to hack alone?</h1>
<p>Take a look at the <a href="http://nodeknockout.com/locations">NKO locations</a> page for hosted backspaces around the world. 

</p>
<p>If you're in NY, the Nodejitsu team has partnered with Levo League to provide a chill, comfy space with healthy meals and drinks just south of Union Square. <a href="http://nko2012.eventbrite.com/">RSVP here</a>.

</p>
<h1>Node Knockout Deployment Instructions!</h1>
<h2>Introduction to Jitsu deployment</h2>
<h3>TL;DR</h3>
<pre><code><span class="variable">$ </span><span class="identifier">git</span> <span class="identifier"><span class="keymethods">clone</span></span> <span class="identifier">https</span><span class="symbol">:</span>/<span class="regexp">/github.com/nko</span>3/[<span class="identifier">slug</span>] <span class="identifier">myapp</span>
<span class="variable">$ </span><span class="identifier">cd</span> <span class="identifier">myapp</span>
<span class="variable">$ </span><span class="identifier">sudo</span> <span class="identifier">npm</span> <span class="identifier">install</span> -<span class="identifier">g</span> <span class="identifier">jitsu</span>
<span class="variable">$ </span><span class="identifier">jitsu</span> <span class="identifier">login</span> <span class="comment">## username and password provided on your NKO team page</span>
<span class="variable">$ </span><span class="identifier">jitsu</span> <span class="identifier">deploy</span></code></pre>
<h3>Installing</h3>
<p>To install Jitsu, all you have to do is run: <code>npm install -g jitsu</code>

</p>
<p><strong>Hint:</strong> If <code>npm</code> throws an error, try using <code>sudo npm install -g jitsu</code>.


</p>
<h3>Setting up Jitsu</h3>
<p>Once you install Jitsu, you will need to login with the password that was provided to your team by NKO. This login, and only this login, will need to be used for each team member. <strong>NKO will not accept submissions that are under another Nodejitsu account.</strong>

</p>
<p>To login, use: <code>jitsu login</code>

</p>
<p><strong>Hint:</strong> If you get an error when logging in, try using one of the following:

</p>
<ul>
<li><code>jitsu conf <span class="keyword">set</span> protocol http</code></li>
<li><code>jitsu conf <span class="keyword">set</span> host api.nodejitsu.com</code></li>
</ul>
<h3>Deploying</h3>
<p>Before developing your app, you should clone the repository provided to your team by NKO. This will follow the pattern of <code>nko3/[slug]</code>. For example, if your team is named "Node Bandits", your repository would be <code>nko3/node-bandits</code>.

</p>
<p>If you do not have access to this repository, let someone know immediately. This repository provides a skeleton of what NKO is expecting you to submit when you deploy your application.

</p>
<p>Once you have this repository checked out, you can code your application however you see fit. Once you're done, deploy your application to our cloud by running <code>jitsu deploy</code> in the directory containing the <code>package.json</code> file that was provided by your <code>nko3/[slug]</code> repository.

</p>
<p><strong>Warning:</strong> Make sure you keep version numbers synced across team members. If a team member trying to deploy an application with version 0.0.1 while another team member has deployed 0.0.2, the server will reject the deploy.

</p>
<p><strong>Remember:</strong>

</p>
<ul>
<li><code>nko3/[slug]</code> should be <code><span class="identifier">nko3</span>/<span class="identifier">your</span>-<span class="identifier">team</span>-<span class="identifier"><span class="keymethods">name</span></span></code>. For example, a team named "Node Bandits" would be <code>nko3/node-bandits</code>.</li>
<li>You get one login for Nodejitsu per team. Use it, because your submissions won't be accepted from another account.</li>
<li>Keep version numbers synced amongst your team. Using different versions could, and probably will, cause unintended effects.</li>
</ul>
<h3>Going deeper</h3>
<p>Jitsu has a lot of features including deploying old snapshots, getting running logs, setting environment variables, and even creating databases. More info can be found by just typing <code>jitsu</code> at the command line or in the <a href="http://handbook.jit.su/##jitsu">Nodejitsu Handbook</a>.


</p>
<h3>Help</h3>
<p>You can visit us online at our <a href="http://nodejitsu.com">homepage</a>. You can find out more information about Jitsu on <a href="https://github.com/nodejitsu/jitsu">Github</a>. As always, you can also find us on IRC on <a href="irc://freenode.net/nodejitsu">Freenode</a> on ##nodejitsu.

</p>
]]></description><link>http://blog.nodejitsu.com/nko-2012</link><guid isPermaLink="true">http://blog.nodejitsu.com/nko-2012</guid><dc:creator><![CDATA[Ana Hevesi]]></dc:creator><pubDate>Fri, 09 Nov 2012 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./hello-no-de-users-">Hello, no.de users!</a>]]></title><description><![CDATA[<p>As you’ve probably heard, our partners at <a href="http://joyent.com/">Joyent</a> are expanding their PaaS efforts with Nodejitsu!  This means that if you're an <a href="https://no.de/">No.de</a> user, Nodejitsu is stepping in to continually support all your deployment needs.

</p>
<p>Nodejitsu offers newer versions of node, great customer support, features like
WebSockets and multi-cloud options (coming soon!) all on the best operating
system to run your node.js application: SmartOS Joyent SmartMachines.

</p>
<p>If you want to ensure that your application keeps running continuously, you
should follow our upgrade instructions before October 30th.

</p>
<p>Here’s what you’ll need to know.



</p>
<h2>node.js versions</h2>
<p>Nodejitsu only installs latest versions of node: v0.6 and v0.8.

</p>
<p>At this point node v0.4 should not be considered production quality. Many
bug and security fixes have been introduced in latest releases and didn't
find their way into latest node v0.4 release.

</p>
<p>If you need help with upgrading your application, here are some resources for you:

</p>
<ul>
<li><a href="https://github.com/joyent/node/wiki/API-changes-between-v0.4-and-v0.6">API changes between v0.4 and v0.6</a></li>
<li><a href="https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8">API changes between v0.6 and v0.8</a></li>
</ul>
<p>Also, feel free to drop by our IRC channel to get support from our team and
fellow coders.

</p>
<h2>Upgrading</h2>
<h3>Installing <code>jitsu</code></h3>
<p>To deploy to Nodejitsu, you need our CLI tool, <code>jitsu</code>. You can install it
reqlly easily with <code>npm</code>.

</p>
<pre><code>[sudo] npm -g install jitsu</code></pre>
<p>Now, <code>jitsu</code> command should be globally accessible.

</p>
<h3>Signing up for a nodejitsu account</h3>
<p>There are 2 ways to sign up for a Nodejitsu account: through
<a href="https://nodejitsu.com">the website</a> and with <code>jitsu</code>.

</p>
<p>If you decide to signup through the website, just click on the "Try Nodejitsu
For Free" button and fill in some details.

</p>
<p><code>jitsu</code> command responsible for signing up is <code>jitsu signup</code>. <code>jitsu</code> will
prompt you for username, email address and password and create an account for
you.

</p>
<p>In both cases, you'll receive an email with instructions on what to do next.

</p>
<h3>First deployment</h3>
<p>The major difference between no.de and Nodejitsu deployment is the method of
sending code to servers. no.de uses git-based deployment, while at Nodejitsu
we simply pack your code into a tarball using <code>npm</code>.

</p>
<p>Therefore, to deploy you don't need to commit your changes into version control.
At any point in time you can execute <code>jitsu deploy</code> command and have your
changes reflected in the code running on a remote server (obviously, you should
still use version control; it's just no longer required for deployment).

</p>
<p>So, how your typical deploy will look like:

</p>
<pre><code>[maciej@pc08 test-app]$ jitsu deploy
info:    Welcome to Nodejitsu nodejitsu
info:    jitsu v0.<span class="number">9.7</span>
info:    It worked <span class="keyword">if</span> it ends <span class="keyword">with</span> Nodejitsu ok
info:    Executing command deploy
info:    Analyzing your application dependencies <span class="keyword">in</span> app.js
info:    Checking app availability test-app
info:    Creating app test-app
info:    Creating snapshot <span class="number">0.3</span>.<span class="number">5</span>-<span class="number">46</span>
info:    Updating app test-app
info:    Activating snapshot <span class="number">0.3</span>.<span class="number">5</span>-<span class="number">46</span> <span class="keyword">for</span> test-app
info:    Starting app test-app
info:    App test-app is now started
info:    http:<span class="comment">//test-app-21421.jit.su on Port 80</span>
info:    Nodejitsu ok</code></pre>
<h3>Accessing logs</h3>
<p>Another difference is the way of accessing server logs. no.de offered SSH access.
Accessing logs is a bit different at Nodejitsu - you can fetch them using
<code>jitsu</code>.

</p>
<p>For example, to get 5 most recent lines of logs from app <code>home</code>:

</p>
<pre><code>[<span class="identifier">maciej</span><span class="variable">@pc08</span> ~]<span class="variable">$ </span><span class="identifier">jitsu</span> <span class="identifier">logs</span> <span class="identifier">app</span> <span class="identifier">home</span> <span class="number">5</span>
<span class="identifier">info</span><span class="symbol">:</span>    <span class="constant">Welcome</span> <span class="identifier">to</span> <span class="constant">Nodejitsu</span> <span class="identifier">nodejitsu</span>
<span class="identifier">info</span><span class="symbol">:</span>    <span class="identifier">jitsu</span> <span class="number">v0</span>.<span class="number">9.7</span>
<span class="identifier">info</span><span class="symbol">:</span>    <span class="constant">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="constant">Nodejitsu</span> <span class="identifier">ok</span>
<span class="identifier">info</span><span class="symbol">:</span>    <span class="constant">Executing</span> <span class="identifier">command</span> <span class="identifier">logs</span> <span class="identifier">app</span> <span class="identifier">home</span> <span class="number">5</span>
<span class="identifier">info</span><span class="symbol">:</span>    <span class="constant">Listing</span> <span class="identifier">logs</span> <span class="identifier"><span class="keyword">for</span></span> <span class="identifier">home</span>
[08/<span class="number">29</span> <span class="number">23</span><span class="symbol">:</span>09<span class="symbol">:</span><span class="number">12</span> <span class="constant">GMT</span>+<span class="number">0200</span>] [<span class="identifier">served</span>] /<span class="identifier">css</span>/<span class="identifier">normalize</span>.<span class="identifier">css</span>
[08/<span class="number">29</span> <span class="number">23</span><span class="symbol">:</span>09<span class="symbol">:</span><span class="number">11</span> <span class="constant">GMT</span>+<span class="number">0200</span>] [<span class="identifier">served</span>] /
[08/<span class="number">29</span> <span class="number">23</span><span class="symbol">:</span>08<span class="symbol">:</span><span class="number">59</span> <span class="constant">GMT</span>+<span class="number">0200</span>] [<span class="identifier">served</span>] /<span class="identifier">paas</span>/<span class="identifier">tools</span>.<span class="identifier">html</span>
[08/<span class="number">29</span> <span class="number">23</span><span class="symbol">:</span>08<span class="symbol">:</span><span class="number">15</span> <span class="constant">GMT</span>+<span class="number">0200</span>] [<span class="identifier">served</span>] /<span class="identifier">img</span>/<span class="identifier">visuals</span>/<span class="identifier">visual</span>-<span class="number">2</span>.<span class="identifier">png</span>
[08/<span class="number">29</span> <span class="number">23</span><span class="symbol">:</span>08<span class="symbol">:</span><span class="number">15</span> <span class="constant">GMT</span>+<span class="number">0200</span>] [<span class="identifier">served</span>] /<span class="identifier">img</span>/<span class="identifier">visuals</span>/<span class="identifier">visual</span>-<span class="number">3</span>.<span class="identifier">png</span>
<span class="identifier">info</span><span class="symbol">:</span>    <span class="constant">Nodejitsu</span> <span class="identifier">ok</span></code></pre>
<p>You can more help about that command by executing <code>jitsu logs</code> in your
terminal.

</p>
<h3>Custom domains</h3>
<p>If you were using a custom domain with no.de, you need to apply some changes
to your DNS set up. Instructions on how to do that can be found at
<a href="dns.jit.su">dns.jit.su</a>.

</p>
<h3>Something wrong?</h3>
<p>We'd love to help and make the transition as pleasant as possible! Talk to us 
on #nodejitsu at Freenode IRC or at support@nodejitsu.com.
</p>
]]></description><link>http://blog.nodejitsu.com/hello-no-de-users-</link><guid isPermaLink="true">http://blog.nodejitsu.com/hello-no-de-users-</guid><dc:creator><![CDATA[Maciej Malecki]]></dc:creator><pubDate>Thu, 18 Oct 2012 18:41:58 GMT</pubDate></item><item><title><![CDATA[<a href="./paid-individual-plans">Paid Individual Plans now available</a>]]></title><description><![CDATA[<p><strong>Nodejitsu is happy to announce our <a href="http://www.nodejitsu.com/paas/pricing.html#paas-pricing-individual">Paid Individual Plans</a> are now available.</strong> 

</p>
<p>When Nodejitsu entered public beta, we shared our approach to Platform-as-a-Service pricing, and our commitment to <a href="http://blog.nodejitsu.com/on-disrupting-pricing-models">changing the way that Platform-as-a-Service companies incentivize developers</a>. Today's announcement reflects that commitment and we're pleased to have you try Nodejitsu today for free in our <a href="http://www.nodejitsu.com/paas/pricing.html#paas-pricing-sandbox">Development Sandbox</a>. And when you're ready you can upgrade to one of our Individual Plans <em>starting at <strong>just $3</strong>.</em>

</p>
<p><em>(Please note: at this time we are only introducing Paid Individual Plans. Our Business Plans will be available for purchase soon!)</em> 

</p>
<p><img src="paid-individual-plans/webops.png" width="700px" />

</p>
<h2> </h2>
<h3>If you're hosting on Nodejitsu, you still have one free month left</h3>
<p>If you're using Nodejitsu today you will automatically be enrolled in our <a href="http://www.nodejitsu.com/paas/pricing.html#paas-pricing-sandbox">Development Sandbox</a> next week which will give you <em>one free drone at Nodejitsu for one month.</em> After that time you can upgrade to one of our <a href="http://www.nodejitsu.com/paas/pricing.html#paas-pricing-individual">Paid Individual Plans</a> starting at just $3.

</p>
<p><br />
</p>
<h3>Wait! I'm running more than one app already!</h3>
<p>If you are running more than one app <em>you will have <strong>one week (until Oct. 17th)</strong> before additional apps are turned off.</em> <strong>Your app will not be deleted.</strong> You can always keep as many stopped apps as you want on Nodejitsu. It will remain stopped until you begin paying for the drones to run it.

</p>
<p><br />
</p>
<h3>We're here to help</h3>
<p>Problems? Questions? <em>Reach out to us on Twitter or in #nodejitsu on IRC.</em> We couldn't be more excited to be working with you.

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

</p>
]]></description><link>http://blog.nodejitsu.com/paid-individual-plans</link><guid isPermaLink="true">http://blog.nodejitsu.com/paid-individual-plans</guid><dc:creator><![CDATA[Nodejitsu]]></dc:creator><pubDate>Wed, 10 Oct 2012 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./around-the-world-19-days">Around the World in 19 days</a>]]></title><description><![CDATA[<p>Here at Nodejitsu, we live for the node.js and Javascript community. Honestly, without them this company wouldn't exist. This commitment often results in many members of the Nodejitsu team speaking at events around the world. I was privileged enough to be invited to two such events in China and Lisbon this past month. In booking my travel I actually circumnavigated the globe and I thought a few of our users might be interested in stories of the JS community worldwide!

</p>
<h2>Shanghai, China - HuJS</h2>
<p>When I was invited to HuJS by Glenn Block (from the Microsoft Azure team), I was actually a little surprised that there was enough interest to have this kind of regional Javascript conference in China. The CHINA MARKET meme had become used so much, I had doubts that there would really be anything of substance there. <strong>I couldn't be more wrong.</strong>

</p>
<p>The conference itself was great; I wish I spoke Chinese because <em>over half of the talks were in the native language.</em> I was blown away by the talent and overall prolific output of these Chinese Javascript developers. I was also quite impressed with not just the Javascript community, but the burgeoning startup community in Shanghai. Special thanks to the team over at <a href="http://www.factual.com/">Factual</a> for being gracious hosts and showing me around Shanghai!

</p>
<h2>Lisbon, Portugal - LXJS</h2>
<p>I had been looking forward to LXJS for months. Not just because it was shaping up to be an awesome conference, but because it was one of those rare moments when <em>more than five members of the Nodejitsu team were in the same room.</em> In fact, between staff and speakers there were <strong>eight nodejitsuka</strong> at LXJS:

</p>
<ul>
<li>Paolo Fragomeni - <a href="http://www.youtube.com/watch?v=uNYSqX97bOc&amp;feature=plcp">Thinking Distributed</a></li>
<li>Karolina Szczur - <a href="http://www.youtube.com/watch?v=o70jaNU08F0&amp;feature=plcp">The Pursuit of Simplicity</a></li>
<li>Maciej Malecki - <a href="http://www.youtube.com/watch?v=GV12LGxxSzo&amp;feature=plcp">Node.js Internals</a></li>
<li>Elijah Insua - <a href="http://www.youtube.com/watch?v=XbXcdhYwR8I&amp;feature=plcp">Hardware with Javascript and CNCs</a></li>
<li>Arnout Kazemier - <a href="http://www.youtube.com/watch?v=Qkv8urfTmNw&amp;feature=plcp">Building the Real-Time Web</a></li>
<li>Charlie Robbins - <a href="http://www.youtube.com/watch?v=9PK68ZKcSEk&amp;feature=plcp">Open Source LIKE A BOSS</a></li>
</ul>
<p>Not to mention that the event organizers were three of Nodejitsu's own <strong>Nuno Job, Pedro Teixeira and Ana Hevesi.</strong> They did a great job organizing <em>the best destination conference of the year.</em> Personally I really enjoyed the <a href="http://www.youtube.com/watch?v=GaqxIMLLOu8&amp;feature=plcp">closing keynote by Mikeal Rogers</a>, where he shared some staggering statistics about the Node.js community and how we approach infrastructure:

</p>
<p><strong>On Infrastructure</strong>
</p>
<blockquote>
  All of the papers that people write, and all the blog posts that are saying "this is what a clean infrastructure looks like": they're justifying the old infrastructure after the fact. They built that because they couldn't build it the way that they wanted to; and now it's gospel.
</blockquote>

<p><strong>On Node.js Growth</strong>
</p>
<blockquote>
  Today there are over 15,000 packages in the npm repository. (...) Let's do a quick comparison: RubyForge has [about] 9,000 packages in it. (...) RubyGems has less than 3,000 packages. (...) So [node.js] already more than that. Python has 24,000 packages in it, but it's been around since 1989; [node.js] has been around three years so we'll close in on them by the end of next year.
</blockquote>

<h2>It's not over yet!</h2>
<p>In the past two years, the Javascript community has raised the bar for technology conferences by, as Chris Williams (creator of JSConf) says, "growing out, not up". That means we're having <em>more conferences</em> not <em>bigger conferences.</em> This allows the same intimate and friendly atmosphere to be fostered at every event while still serving the needs of a vastly distributed community. What does this mean? It means conference season is just getting warmed up. Here's a rundown of awesome events and a look at where the Nodejitsu team will be.

</p>
<h3>October</h3>
<ul>
<li><a href="http://rejectjs.org/">Reject.js</a> <strong>Berlin, Germany</strong> : <em>October 4th</em> <strong>(Karolina Szczur, Paolo Fragomeni)</strong></li>
<li><a href="http://nodecopter.com/">NodeCopter.js</a> <strong>Berlin, Germany</strong> : <em>October 5th</em> <strong>(Karolina Szczur, Paolo Fragomeni)</strong></li>
<li><a href="http://2012.jsconf.eu/">JSConfEU</a> <strong>Berlin, Germany</strong> : <em>October 5th and 7th</em> <strong>(Karolina Szczur, Paolo Fragomeni)</strong></li>
<li><a href="http://nodedublin.com">NodeDublin</a> <strong>Dublin, Ireland</strong> : <em>October 18th and 19th</em> <strong>(Paolo Fragomeni, Charlie McConnell, Maciej Malecki)</strong></li>
<li><a href="http://empirejs.org">EmpireJS</a> - <strong>New York, NY</strong> : <em>October 22nd</em> <strong>(Charlie Robbins, Ana Hevesi, Charlie McConnell)</strong></li>
<li><a href="http://redisconf.com">RedisConf</a> - <strong>Portland, OR</strong> : <em>October 22nd</em> <strong>(Arnout Kazemier)</strong></li>
<li><a href="http://2012.krtconf.com">Keeping it Realtime</a> - <strong>Portland, OR</strong> : <em>October 23rd and 24th</em> </li>
</ul>
<h3>November</h3>
<ul>
<li><a href="http://cascadiajs.com/">CascadiaJS</a> - <strong>Seattle, WA</strong> : <em>November 8th and 9th</em></li>
<li><a href="http://nodejsconf.it/">Nodejsconf.it</a> - <strong>Brescia, Italy</strong> : <em>November 10th</em> <strong>(Maciej Malecki)</strong></li>
<li><a href="http://nodefest.jp/2012/">Node.js Fest Japan</a> - <strong>Tokyo, Japan</strong> : <em>November 18th</em> <strong>(Charlie Robbins)</strong></li>
<li><a href="http://dotjs.eu">dotJS.eu</a> - <strong>Paris, France</strong> : <em>November 30th</em> <strong>(Charlie Robbins)</strong></li>
</ul>
<p>You should also definitely be subscribed to <a href="http://confnotice.com">ConfNotice</a>, a newsletter about awesome events curated by JSConf's own Chris Williams.

</p>
]]></description><link>http://blog.nodejitsu.com/around-the-world-19-days</link><guid isPermaLink="true">http://blog.nodejitsu.com/around-the-world-19-days</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Tue, 02 Oct 2012 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./change-in-nodejitsu-leadership">Change in Nodejitsu's Leadership</a>]]></title><description><![CDATA[<p>As of this past Tuesday, Marak Squires is no longer an employee of Nodejitsu. As one of the founding members of the company, Marak has been an integral part of what Nodejitsu has built so far, and changes like this are never easy.

</p>
<p>Over the last two years, as the business and team have grown, the founders’ ideas about management and policy grew to be at odds. Starting a company takes passion and strong personalities, but eventually company disagreements spilled over into being too personal. In order to maintain a healthy, respectful work environment, we felt we needed to separate ourselves.

</p>
<p>To clarify, Flatiron is a Nodejitsu initiative.  While Marak has been one of its key architects and proponents, his departure from the company does not mean the end of Flatiron.  Quite to the contrary, the Flatiron framework and associated tools are used to power many key parts of Nodejitsu’s cloud offering. Flatiron will remain open-source, and our commitment to free open source software with non-restrictive licenses remains steadfast. We will continue to collaborate with the node.js community to build and innovate Flatiron.js.

</p>
<p>Marak’s contributions to Nodejitsu, as well as node.js in general, have been innumerable.  His evangelism in the early days was instrumental to helping many people find and embrace node.js - including several key members of our team.  Perhaps most importantly, his unique and outgoing sense of humor has been an important part of our team morale, as well as the spirit of the node community in general.

</p>
<p>This has been a very difficult decision, but one which had to be made so that we could continue to build and grow Nodejitsu into what we believe it can be. We will always be grateful for Marak’s contributions and we hope the node.js community will continue to benefit from his talents. 
</p>
]]></description><link>http://blog.nodejitsu.com/change-in-nodejitsu-leadership</link><guid isPermaLink="true">http://blog.nodejitsu.com/change-in-nodejitsu-leadership</guid><dc:creator><![CDATA[Nodejitsu]]></dc:creator><pubDate>Thu, 13 Sep 2012 18:31:32 GMT</pubDate></item><item><title><![CDATA[<a href="./resource-reflection-in-flatiron">Resource Reflection in Flatiron</a>]]></title><description><![CDATA[<blockquote>
<p>In computer science, reflection is the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of an object at runtime - <a href="http://en.wikipedia.org/wiki/Reflection_(computer_programming)">Wikipedia</a>

</p>
</blockquote>
<p><br />
</p>
<div align="center">
  <iframe width="420" height="315" src="http://www.youtube.com/embed/SYOjGcrLbGQ" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
</div>

<p>The <a href="http://flatironjs.com">Flatiron framework</a> is designed to help with the rapid development of robust isomorphic JavaScript applications. Flatiron is built on the <a href="http://blog.nodejitsu.com/the-nodejs-philosophy">node.js philosophy</a> of small, distinct, usable components. Every component of the framework can be used independently, for it's own distinct purpose.

</p>
<h2>Resource-View-Presenter</h2>
<p>While developers have the choice to assemble these Flatiron components in anyway they like, Flatiron <em>encourages</em> the use of the RVP (<a href="http://blog.nodejitsu.com/scaling-isomorphic-javascript-code#rvp">Resource-View-Presenter</a>) pattern. 


</p>
<p>Using the RVP pattern allows developers to move their applications towards a <a href="http://en.wikipedia.org/wiki/Domain-driven_design">domain driven design</a>. This rather utopian computer science idea is usually muddled by several layers of UML diagrams and poorly instrumented tool chains.

</p>
<p><strong>Flatiron's approach towards attaining such programming nirvana is a bit more simple and realistic.</strong>

</p>
<h2>Resources are JavaScript Objects</h2>
<p>A <code>Resource</code> is a JavaScript object. You've probably worked with them before.

</p>
<p>Let's define a <code>Creature</code> resource using the <a href="http://github.com/flatiron/resourceful">resourceful</a> library.

</p>
<pre><code class="js">var resourceful = require('resourceful');
var Creature  = resourceful.define('creature');</code></pre>
<p><code>Creature</code> is a <a href="http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)">constructor function</a> for creating <code><span class="keyword">new</span> Creatures</code>. It's easy I promise.

</p>
<pre><code class="js">var bob = new Creature({ 
  id   : 'Bob',
  type : 'dragon'
});</code></pre>
<p>You can totally still export <code>Creature</code> in a Node.js module.

</p>
<pre><code class="js">exports.Creature = Creature;</code></pre>
<p>This newly created <code>Creature</code> instance <code>Bob</code> comes with some built-in methods to help you out with performing basic <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> operations. 

</p>
<p>By default, resources will use an in-memory storage engine provided by <a href="http://github.com/flatiron/resourceful">resourceful</a>. The storage engine itself is pluggable and supports several modern database engines.

</p>
<pre><code class="js">//
// save, create, destroy, all, find, etc...
//
bob.save({ type: "giant moth" }, function(err, result){

});</code></pre>
<p>Here are <a href="https://github.com/flatiron/resourceful/tree/master/examples">several code examples</a> of using these CRUD methods.


</p>
<h2>Woah, I don't want this CRUD</h2>
<p><strong>Easy!</strong> You can, <a href="http://en.wikipedia.org/wiki/NOP">noop</a> them out, override their definitions at will, or just igore them. A resource is a just a JavaScript object and <code>create</code>, <code>save</code>, etc are just functions!

</p>
<p><strong>over-ride built-in resource methods</strong>

</p>
<pre><code class="js">// No more delete
delete Creature.destroy;

// Custom save
Create.save = function(id, data, callback){
  callback(null, 'The googles do nothing');
});</code></pre>
<h2>Extending Bob the Dragon</h2>
<p>Now we have a new <code>Creature</code>, Bob the Dragon. Bob can pretty much do anything a respectful CRUD dragon could do.

</p>
<p>Well, almost! We are also going to add a feed action to <code>Creatures</code>, because Bob will probably get hungry at some point.

</p>
<pre><code class="js">Creature.feed = function (_id, options, callback) {
  var self = this;
  self.get(_id, function(err, creature){
    if(err) {
      return callback(err);
    }
    var life = creature.life + 1;
    self.update(_id, { life: life }, function(err, result){
      callback(null, 'I have been fed my life is: ' + result.life);
    });
  });
  self.remote = true;
}</code></pre>
<p><em>Note: The <code>remote</code> property is used to indicate the method should be reflected via public remote interfaces. Any methods which are not remote, will not be exposed to public interfaces.*</em>

</p>
<h2>Let's get reflecting</h2>
<p><strong>I thought this was a post about  <a href="http://en.wikipedia.org/wiki/Reflection_(computer_programming))">reflection</a>? Well it is!</strong>

</p>
<ul>
<li>We defined our resource, <code>Creature</code></li>
<li>We gave <code>Creature</code> a custom <code>feed</code> method</li>
<li>We created Bob the Dragon</li>
</ul>
<p>Now we are going to reflect our <code>Creature</code> across across several interfaces!

</p>
<p><strong>Flatiron currently supports resource reflection across:</strong>

</p>
<ul>
<li>RESTful <a href="http://github.com/flatiron/restful">HTTP Server / Clients</a> </li>
<li><a href="http://github.com/flatiron/formful">HTML Forms</a></li>
<li>socket.io websocket <a href="http://github.com/flatiron/socketful">Server / Clients</a> </li>
<li><a href="http://github.com/flatiron/commandful">Command Line Interfaces</a></li>
</ul>
<p><strong>simple restful server:</strong>

</p>
<pre><code class="js">restful.createServer([Creature]).listen(8000, function () {
  console.log(' &gt; restful server started on port 8000');
});</code></pre>
<p><em>individual code examples can be found in each reflection library</em>

</p>
<p>This means that Bob the Dragon can be expressed as a fully functional HTTP / websocket isomorphic application with a command line interface.

</p>
<p style="margin: 0; padding: 0;"><img src="resource-reflection-in-flatiron/restful.png" /></p>
<p style="margin: 0; padding: 0;"><img src="resource-reflection-in-flatiron/root.png" /></p>
<p style="margin: 0; padding: 0;"><img src="resource-reflection-in-flatiron/create.png" /></p>
<p style="margin: 0; padding: 0;"><img src="resource-reflection-in-flatiron/validation.png" /></p>
<p style="margin: 0; padding: 0;"><img src="resource-reflection-in-flatiron/show.png" /></p>


<h2>This sounds like a giant clusterf*ck of auto-generated code</h2>
<p><strong>No way!</strong> First off, there is <strong>zero</strong> auto-generated or scaffolded code in the reflection process. I've done that before, and it's stupid. 

</p>
<p>Flatiron breaks down the problem of uber-reflection into separate and distinct modules that have no direct dependency or relation to each other.

</p>
<p>The core dependency ( or the <strong>R</strong> in <strong>R</strong>VP) is the <a href="http://github.com/flatiron/resourceful">resourceful library</a>. Resourceful allows you to define <strong>resources</strong>. The Flatiron framework then has several distinct projects for <strong>reflecting resources</strong> across well-defined and well tested interfaces.

</p>
<h2>Customization already sounds impossibly complicated</h2>
<p><strong>No way!</strong> Any interface not directly reflected can just as easily be implemented using the appropriate backing library. <strong>All Flatiron modules are broken down into distinct and re-usable projects.</strong>

</p>
<p>For example, if you used <a href="http://github.com/flatiron/restful">restful</a> to reflect a RESTful router server-side in node.js, you will then have access to a <code>Director.router</code> instance. This router is created by the heavily used <a href="http://github.com/flatiron/director">Director</a> library. 

</p>
<p>If you need to override a generated route, or create an ad-hoc route, or make any customization, the API is <em>exactly</em> the same as the Director API. 

</p>
<p><strong>customize a reflected router interface:</strong>

</p>
<pre><code class="js">app.router.get('/', function(){
  this.res.end('home page');
});

//
// Overrides `/creature/larry` but won't override,
// any other `/creature/:id` captures.
//
app.router.get('/creatures/larry', function(){
  this.res.end('larry is special!');
});</code></pre>
<p>Like most of Flatiron's reflection libraries, <a href="http://github.com/flatiron/restful">restful</a> is built to solve 90% of use-cases. If you hit a case where restful is causing a problem, you can simply drop into the <code>Director</code> API. 

</p>
<p><strong>Resource reflection</strong> is <em>highly</em> encouraged, but most definitely <strong>optional</strong>.

</p>
<p><strong>TL;DR; All of Flatiron's reflection libraries are optional and have a well-defined library backing it's interface.</strong>

</p>
<h2>Wait, what about schema? What about validations?</h2>
<p><a href="http://github.com/flatiron/resourceful">Resourceful</a> provides support for custom validation functions and an optional <a href="http://en.wikipedia.org/wiki/JSON#Schema">JSON-Schema</a> implementation through <a href="https://github.com/flatiron/revalidator">revalidator</a>. 

</p>
<p>You can arbitrarily create validation functions or use JSON-Schema on any property or resource and all interfaces will respect these validations at run-time. It's slightly magical.

</p>
<p><strong>validation on individual properties</strong>
</p>
<pre><code class="js">
// Number between 0 and 10
Creature.property("life", Number, { min: 0 max: 10 });

// Email validation
Creature.property("email", String, { format: 'email' });

// Custom validation conforms
Creature.property("even", Number, { 
  conform: function (value) {
    return value % 2 === 0;
  } 
});</code></pre>
<p><strong>use <code>before</code> and <code>after</code> hooks for resource validations on resource actions</strong>

</p>
<pre><code class="js">Creature.before('create', function(options, callback){
  if(options.foo !== 'bar') {
    return callback(new Error('foo is not bar!'));
  }
  console.log('about to create a new creature!', options);
  callback(null, options);
});

Creature.after('create', function(err, result){
  console.log('Creature was created!', result);
});</code></pre>
<p><br />

</p>
<h2>Fine, this might work. What about relational data?</h2>
<p><strong>Easy!</strong> <a href="http://github.com/flatiron/resourceful">Resourceful</a> supports relationships between resources ( one-one, one-many, many-many ). Relationships are defined in resources through the <code>Resource.parent</code> API. 

</p>
<p>Each reflection library will respect these relationships and act accordingly. You can find additional code examples for setting up relational data in resourceful <a href="https://github.com/flatiron/resourceful/tree/master/examples">here</a> or in the README for the specific reflection library you are using.

</p>
<p><strong>defining a simple resource relationship</strong>

</p>
<pre><code class="js">var Album = resourceful.define('album');
var Song  = resourceful.define('song');
Song.parent('album');</code></pre>
<p><em>Everything else will be handled for you by Flatiron. It's that easy.</em>

</p>
<h2>Okay, I believe. What now?</h2>
<p>Get over to <a href="http://github.com/flatiron"><a href="http://github.com/flatiron">http://github.com/flatiron</a></a> and get started! 

</p>
<p>Flatiron is already the <strong>most contributed to</strong> Node.js Framework on Github. With the upcoming 1.0 version, we are about to enter a new age of isomorphic JavaScript frameworks and web-development. Join the JavaScript party! 

</p>
<p><em>Giddy-up!</em></p>
]]></description><link>http://blog.nodejitsu.com/resource-reflection-in-flatiron</link><guid isPermaLink="true">http://blog.nodejitsu.com/resource-reflection-in-flatiron</guid><dc:creator><![CDATA[Marak Squires]]></dc:creator><pubDate>Mon, 27 Aug 2012 05:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./this-is-now">'This Is Now' on Nodejitsu</a>]]></title><description><![CDATA[<p>A couple weeks ago we discovered that a little site called <a href="http://now.jit.su/">now.jit.su</a> was absolutely blowing up on <a href="http://nodejitsu.com/">Nodejitsu</a>. The project, entitled <a href="http://now.jit.su/">This Is Now</a>, is a real time Instagram feed from 8 different cities around the world. It was crafted by <a href="http://lexicalgap.com.au/">Lexical Gap</a>, a Sydney-based team of creative technologists made up of <a href="https://twitter.com/marciopuga">Marcio Puga</a>, <a href="https://twitter.com/mauriciomassaia">Mauricio Massaia</a>, and <a href="https://twitter.com/@PerThoresson">Per Thoresson</a>.

</p>
<h2>This is Now</h2>
<p>The app is a mosaic of images which gives you a window into the lives of people in cities around the world. You check out <a href="http://thenewyork-now.jit.su/">NY</a> and find photos of sky scrapers, Brooklyn street corners, and people's pets, while the <a href="http://london-now.jit.su/">London</a> feed still reveals remnants of the 2012 Olympics. I caught up with Marcio who explained that this project was Lexical Gap's first foray into node.js. The Lexical Gap team used <a href="http://socket.io/">Socket.io</a> to communicate with the <a href="https://github.com/dguzzo/instagram_api">Instagram API</a> via <a href="https://github.com/mckelvey/instagram-node-lib">Instagram-node-lib</a> to deliver a smooth real-time experience.

</p>
<p><img src="/this-is-now/thisisnowhomepage.png" alt="" />
<img src="/this-is-now/thisisnowny.png" alt="" />   

</p>
<p>This Is Now also turned out to be a great opportunity for our team to test what happens when apps running on our small drone servers get hammered with traffic (i.e. 500 concurrent Socket.io connections per drone). We were able to quickly scale up the app by running it on multiple drones, seamlessly handling the burst of interest in the app, spurred on by several articles in the press - the more popular cities, like New York and Los Angeles, were peaking at well over 2000 concurrent websocket connections.  While there were a few regressions, we jumped in to handle them quickly, and everything went great. 

</p>
<p>To quote Marcio "We received a private beta account from Nodejitsu on the 21st of April, and we have never left. The platform provided a robust suite of functionality that assisted in the development, management, and deployment of our Node.js applications. The deployment tools are definitely the most user-friendly in the industry. Everything highlighted above would be already enough reason for us to be convinced to use it, but our respect/admiration really grew when we met the guys behind Nodejitsu."  

</p>
<p>Thanks. :) Congrats to the Lexical Gap guys on the success. We can't wait to see what community turns out next.  
</p>
]]></description><link>http://blog.nodejitsu.com/this-is-now</link><guid isPermaLink="true">http://blog.nodejitsu.com/this-is-now</guid><dc:creator><![CDATA[Ana Hevesi]]></dc:creator><pubDate>Tue, 21 Aug 2012 01:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./new-nodejitsu-features">New nodejitsu features</a>]]></title><description><![CDATA[<p>Recently, many things changed at nodejitsu, including the introduction of
several long-awaited features. Here's a brief overview of what
happened and how it affects you.

</p>
<h2>Zero downtime deploys!</h2>
<p>I am thrilled to announce that your application no longer requires stopping
in order to start running new code.

</p>
<p>Essentially, that means two things:

</p>
<ul>
<li>no downtime during regular deployment</li>
<li>if deploy fails, your application stays up, running the last snapshot</li>
</ul>
<p>This feature involves a semantic change to our API. <code>POST</code> <code>/apps/:username/:appname/start</code>
first starts a new drone, then kills the old one. You will never again see a
"Cannot start running application" error while accessing this endpoint.

</p>
<p>This is different from <code>POST</code> <code>/apps/:username/:appname/restart</code>, which tells our
application server to restart the application (as in, kill your process and start
it again).  Because the <code>restart</code> endpoint affects the already-running instance, zero-downtime does not apply.

</p>
<h2>Fetching snapshots</h2>
<p>Many of our users were asking about a way to fetch an existing snapshot
from our cloud, and here it is! The API endpoint for downloading a snapshot is
<code>GET</code> <code>/<span class="identifier">apps</span>/<span class="symbol">:<span class="identifier">username</span></span>/<span class="symbol">:<span class="identifier">appname</span></span>/<span class="identifier">snapshots</span>/<span class="symbol">:<span class="identifier"><span class="keymethods">id</span></span></span>.<span class="identifier">tgz</span></code>. The API will respond with a
tarball.

</p>
<pre><code><span class="identifier">var</span> <span class="identifier">fs</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'fs'</span>),
    <span class="identifier">request</span> = <span class="identifier"><span class="keyword">require</span></span>(<span class="string">'request'</span>);

<span class="identifier">request</span>(<span class="string">'http://user:pass@api.nodejitsu.com/apps/user/app/snapshots/v0.0.1.tgz'</span>)
  .<span class="identifier"><span class="keymethods">pipe</span></span>(<span class="identifier">fs</span>.<span class="constant">createWriteStream</span>(<span class="string">'user-app-v0.0.1.tgz'</span>));</code></pre>
<p>We also <a href="https://github.com/nodejitsu/jitsu/commit/0ea3827a6548b8d6ad09342827245f4159578892">introduced</a>
a new command in <code>jitsu</code>: <code><span class="identifier">jitsu</span> <span class="identifier">snapshots</span> <span class="identifier"><span class="keymethods">fetch</span></span></code>.  This will download a tarball of your app to your current working directory.

</p>
<h2><code>jitsu</code> hooks</h2>
<p>Another feature which was requested quite often was pre- and post-deploy hooks for <code>jitsu</code>. Obviously,
we <a href="https://github.com/nodejitsu/jitsu/pull/254">implemented</a> them!

</p>
<p>In some cases, you might want to perform some action before or after deploying
an application. That's where these hooks come in handy.

</p>
<p>Example:

</p>
<pre><code>{
  "name": "test-app",
  "subdomain": "test-app",
  "scripts": {
    "predeploy": "echo This will be run before deploying the app",
    "postdeploy": "echo This will be run after deploying the app",
    "start": "app.js"
  },
  "engines": {
    "node": "0.6.x"
  },
  "version": "0.0.0"
}</code></pre>
<p>Results in the following output from <code>jitsu</code>:

</p>
<pre><code>[maciej@pc08 test-app]$ jitsu deploy
info:    Welcome to Nodejitsu nodejitsu
info:    It worked <span class="keyword">if</span> it ends <span class="keyword">with</span> Nodejitsu ok
info:    Executing command deploy
info:    Analyzing your application dependencies <span class="keyword">in</span> app.js
info:    Checking app availability test-app
info:    Creating app test-app
This will be run before deploying the app
info:    Creating snapshot <span class="number">0.0</span>.<span class="number">0</span>
info:    Updating app test-app
info:    Activating snapshot <span class="number">0.0</span>.<span class="number">0</span> <span class="keyword">for</span> test-app
info:    Starting app test-app
info:    App test-app is now started
info:    http:<span class="comment">//test-app.jit.su on Port 80</span>
This will be run after deploying the app
info:    Nodejitsu ok</code></pre>
<p>There are various use-cases, including build or compile steps, tagging releases, and so on.

</p>
<h2>That's it!</h2>
<p>Thanks for all the feedback and support - and if there are other features you think would be awesome, let us know!
We're always looking to make our platform even better than it already is.

</p>
<p>If you have any questions, feel free to reach out to us at #nodejitsu on
Freenode IRC.
</p>
]]></description><link>http://blog.nodejitsu.com/new-nodejitsu-features</link><guid isPermaLink="true">http://blog.nodejitsu.com/new-nodejitsu-features</guid><dc:creator><![CDATA[Maciej Malecki]]></dc:creator><pubDate>Thu, 02 Aug 2012 21:31:00 GMT</pubDate></item><item><title><![CDATA[<a href="./js13kgames">Calling All Game Developers</a>]]></title><description><![CDATA[<p>We love encouraging hackers to <a href="http://blog.nodejitsu.com/you-laugh-you-lose">push their skills</a> to new heights. That's why we've decided to help out with the <a href="http://js13kgames.com/">js13kGames competition</a> as the official deployment platform and prize sponsor.

</p>
<h2>What's js13kgames anyway?</h2>
<p><img src="/js13kgames/jsgames.png" alt="" />

</p>
<p><a href="http://js13kgames.com/">js13kGames</a> is a coding challenge for HTML5 game developers founded by <a href="http://twitter.com/end33r">Andrzej Mazur</a> (a game dev himself). The main rule is to keep your file size <strong>below 13kB</strong>. There's no official theme for entries, so be creative! You'll want to check out the full list of guidelines <a href="http://js13kgames.com/#rules">here</a>.

</p>
<p>While the contest is focused on JavaScript we strongly encourage all participants to try Node.js for your back end needs! In case of any problems you can always hang out in the <strong>#nodejitsu</strong> channel on <code>irc.freenode.net</code> to get some answers.

</p>
<h2>Prizes</h2>
<p>About those prizes...Nodejitsu is giving away <strong>one six month Regular plan</strong> for free! You'll be able to deploy and manage your apps and games with all the goodness our platform has to offer: WebSockets, CoffeeScript, ImageMagick and libxml support, custom domains, and free SSL on <code>*.nodejitsu.com</code>. Sounds awesome, right? 

</p>
<p>Our partner - <a href="http://thenodefirm.com/">The Node Firm</a> is sponsoring <strong>one ticket</strong> to the open Node.js training of your choice. If you're not yet familiar with the technology but want to learn from top-notch developers (core contributors and module creators) that's a perfect occassion to do that!

</p>
<p>Other prizes include three licenses for <a href="http://impactjs.com/">Impact.js</a>, the JavaScript game engine created by <a href="https://twitter.com/phoboslab/">Dominic Szablewski</a>, a ticket to <a href="http://training.bocoup.com/">Bocoup training</a>, two books from O'Reilly media and three copies of <a href="http://www.apress.com/9781430232919">Foundation HTML5 Canvas for Games and Entertainment</a> by Rob Hawkes. That makes a great set both for beginners and seasoned developers.

</p>
<h2>Submitting your game</h2>
<p>All entries should be public repositories on Github. In order to participate you need to fill out the form on the <a href="http://js13kgames.com/">js13kGames website</a> with a link to the repository, the app itself (hosted at Nodejitsu), and a few details about yourself.

</p>
<h2>Deployment to Nodejitsu</h2>
<p>Since Nodejitsu is already in <a href="http://blog.nodejitsu.com/nodejitsu-is-now-in-public-beta">public beta</a>, every participant can register for a <em>Developer Sandbox</em> account for free.

</p>
<p>After successful registration with <a href="https://github.com/nodejitsu/jitsu">jitsu</a>, all you have to do to deploy your application is run the following in your app's top level directory:

</p>
<p><code>jitsu deploy</code>

</p>
<p>This will use <a href="https://github.com/isaacs/npm">npm</a> to bundle your application, send it to nodejitsu, and deploy it!

</p>
<p><img src="/js13kgames/jitsu.png" alt="" />

</p>
<p>Because jitsu uses npm to bundle your application, dependencies and app configuration are managed through your package.json. You can read more about the package.json format at <a href="http://package.json.jit.su"><a href="http://package.json.jit.su">http://package.json.jit.su</a></a>. Jitsu will automatically prompt you for a number of required fields as needed, such as your desired application subdomain (ex: <code>myfungame</code> for <code>http:<span class="comment">//m</span>yfungame.jit.su</code>), desired node.js version, and anything else we need. You can read more about how nodejitsu works from <a href="http://handbook.jit.su">our handbook</a>.

</p>
<p>Every time you want to deploy a new version of your application, just run <code>jitsu deploy</code>. If you have any problems, just copy and paste all of jitsu's output into a <a href="https://gist.github.com">gist</a> and show it to our support team in <a href="http://webchat.jit.su">#nodejitsu on freenode.net</a>.

</p>
<p>Good luck!
</p>
]]></description><link>http://blog.nodejitsu.com/js13kgames</link><guid isPermaLink="true">http://blog.nodejitsu.com/js13kgames</guid><dc:creator><![CDATA[Karolina Szczur]]></dc:creator><pubDate>Tue, 31 Jul 2012 20:50:38 GMT</pubDate></item><item><title><![CDATA[<a href="./nodejitsu-is-now-in-public-beta">Announcing Nodejitsu Public Beta!</a>]]></title><description><![CDATA[<p>Last week Nodejitsu CEO, Charlie Robbins told the audience at <a href="http://nodeconf.com">Nodeconf</a> that we would be moving into Public Beta <strong>very</strong> soon. I am happy to announce that public beta has arrived!


</p>
<p><strong>Nodejitsu is now available for all.</strong>  You can <a href="http://nodejitsu.com/#/">sign up for Nodejitsu</a> and will immediately be placed in the <a href="http://nodejitsu.com/#/paas/pricing">Development Sandbox</a> without having to wait for an activation.


</p>
<h2>If you already have a Nodejitsu account and you've been waiting for activation…</h2>
<p>It's your lucky day. You should be receiving an email including your confirmation code. So long as you have <a href="http://nodejs.org/">node.js</a> and our CLI tool, <a href="https://github.com/nodejitsu/jitsu">jitsu</a> installed, you're good to go; all you have to do is run the confirmation command! Check out the <a href="https://github.com/nodejitsu/handbook">Nodejitsu Handbook</a> if you need a refresher on how to deploy.


</p>
<h2>If you're a beta tester…</h2>
<p>You don't need to do anything right now. You're already in. Hope you've been enjoying yourself. 


</p>
<h2>Billing and the Developer Sandbox</h2>
<p>All users at this stage are in the "Development Sandbox", which is free. Our billing plans will roll out in the next couple of weeks and at that point you can choose to upgrade to a higher level of service.


</p>
<p>You can check out our soon-to-be-live pricing plan <a href="http://nodejitsu.com/#/paas/pricing/">here.</a>


</p>
<h2>What took so long?</h2>
<p>We're aware that many of you have been waiting a very long time for access to Nodejitsu. There are a few reasons why we chose to stay in private beta and to limit access for this long. Firstly, We're deeply committed to the quality of our service. We want to provide first class, hands-on support by people who actually love what they do. 

</p>
<p>We are also building a product, not just a public cloud. We've been building a <a href="http://nodejitsu.com/#/enterprise/products">cohesive suite of tools</a> that can be deployed to your data center so you can build your own Node.js clouds, on your own hardware. We want to help node succeed within established businesses as well as with individual developers.

</p>
<p>Finally, at Nodejitsu, our success is directly proportional to the success of Node.js itself. Most of all, we want to ensure that the node community is provided with the best solution possible.

</p>
<p>Some of you may remember the early wild west days of node when a new release meant everything you had built had broken in one way or another. Back then (in fact for most of our first year of business) our focus was to ensure that users (and us!) had the right set of tools to build applications. We knew that without this ecosystem of Open Source tools Node.js (and therefore Nodejitsu) would never succeed. The second year was greatly focused on building out our infrastructure. Now the time is right to present you with the culmination of this work.



</p>
<p>It's been a privilege so far to work with such an awesome community. We're both humbled and excited to be opening our doors. Let's hack!
</p>
]]></description><link>http://blog.nodejitsu.com/nodejitsu-is-now-in-public-beta</link><guid isPermaLink="true">http://blog.nodejitsu.com/nodejitsu-is-now-in-public-beta</guid><dc:creator><![CDATA[Ana Hevesi]]></dc:creator><pubDate>Mon, 09 Jul 2012 19:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./ten-lessons-learned-maintaining-nodejs-modules">Ten Lessons Learned Maintaining Nodejs Modules</a>]]></title><description><![CDATA[<p><a href="http://nodejs.org">Node.js</a> has grown so much since I started working with it sometimes I can't believe it. Not just the <a href="http://nodeconf.com">awesome community</a>, but the core APIs. 

</p>
<p>Maintaining software is no walk in the park: writing modules is at once the most rewarding and most difficult thing you can do. I'm often reminded of what <code>isaacs</code> once said on the nodejs mailing list:

</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>This article represents the lessons learned from writing node modules since <code>node@0.1.103</code>.

</p>
<h2> </h2>
<h2>Maintaining Software is Hard</h2>
<ul>
<li><a href="#commitment">Understand the Commitment</a></li>
<li><a href="#define-the-module">Define What You're Going to do and do it</a></li>
<li><a href="#get-some-attention">Get Some Attention</a></li>
<li><a href="#dependencies">Keep your Dependencies Lean and Fresh</a></li>
<li><a href="#refactor">Don't be Afraid to Refactor</a></li>
<li><a href="#compiled-dependencies">Be Wary of Compiled Modules</a></li>
<li><a href="#support">Support Your Users</a></li>
<li><a href="#pull-requests">Assess Pull-Requests Carefully</a></li>
<li><a href="#unpublish">Unpublish Versions you won't Support</a></li>
<li><a href="#moving-on">Know When to Throw in the Towel</a></li>
</ul>
<p><a name="commitment"></a>
</p>
<h3>Understand the Commitment</h3>
<p>It bears repeating: <strong>maintaining software is hard.</strong> If you're not up to the challenge of responding to issues, publishing hotfixes, and generally making your module a priority in your life then you probably want to consider <a href="http://search.npmjs.org">looking for something that already exists</a>.

</p>
<p><a name="define-the-module"></a>
</p>
<h3>Define What You're Going to do and do it</h3>
<p>By the time you've decided to commit to writing a module make sure you completely understand the problem at hand. Whether it's an API library, a utility module, or a framework be clear on the expectations early on. Too many times I've seen libraries that are <a href="http://github.com/toots/node-asana">doing too much</a> or <a href="https://github.com/jprichardson/node-fs-extra">making choices that not all of their user-base will appreciate</a>.

</p>
<p><a name="get-some-attention"></a>
</p>
<h3>Get Some Attention</h3>
<p>If you're new to Open Source, you need to understand that your modules <a href="http://zachholman.com/posts/open-source-marketing/">don't just market themselves</a>. You are defining a <a href="http://blog.nodejitsu.com/understanding-open-source-branding">brand</a> and you need to get some attention for it. More attention means more users. More users means better issues and more pull-requests. It's a positive feedback loop that is going to do more for your module than you could possibly imagine. 

</p>
<p><a name="dependencies"></a>
</p>
<h3>Keep your Dependencies Lean and Fresh</h3>
<p>One of the toughest things about maintaining modules is maintaining your dependencies. When you're building an application you can <a href="http://blog.nodejs.org/2012/02/27/managing-node-js-dependencies-with-shrinkwrap/">shrinkwrap your dependencies</a> to a hard version, but when you're building a module you need to be flexible. <strong>This means that your underlying dependencies can change without an explicit change from you.</strong> 

</p>
<p>Generally, setting a dependency version to <code>0.N.x</code> (where N is a hard number) is safe, but be sure to stay on top of things or you're in for some unexpected surprises. It also means you should be careful what dependencies you take on. The more dependencies you don't maintain, the more unexpected complexity you may encounter.

</p>
<p><a name="refactor"></a>
</p>
<h3>Don't be Afraid to Refactor</h3>
<p>There is nothing worse than coming back to a module after several months and realizing you made some bad initial decisions, or even worse your public API needs to change. Read up on <a href="http://semver.org/">Semantic Versioning</a> and if you're module is pre-1.0.0, then don't be afraid to refactor. Refactoring can breathe new life into your module and your enthusiasm for it. <strong>Just be sure to update the version of your module appropriately and maintain a changelog.</strong>

</p>
<p>In <a href="http://github.com/nodejitsu/forever">forever@0.10.0</a>, we refactored the core programmatic <code>Monitor</code> functionality out into a new module: <a href="http://github.com/nodejitsu/forever-monitor">forever-monitor</a>. This separation of concerns is important: <code>forever</code> is a CLI application for running <code>forever-monitor</code> with daemonization.

</p>
<p><a name="compiled-dependencies"></a>
</p>
<h3>Be Wary of Compiled Dependencies</h3>
<p>This is a subtle but brutally important lesson about writing Node.js modules. <strong>Taking on any compiled dependencies, whether as a node addon or 3rd party library, is going to increase the complexity of your install process by an order of magnitude.</strong> It is also going to (probably) make your module incompatible with your Windows users because they may not have a full compiler tool-chain. 

</p>
<p>In <a href="http://github.com/nodejitsu/forever">forever</a> we learned this lesson the hard way. Until detached child processes were implemented in Node.js and libuv in 0.8.0 we were using a compiled add-on called <a href="https://github.com/indexzero/daemon.node">daemon.node</a>. <strong>At least 10% of all issues opened on forever (and a lot on npm itself) were related to this compiled dependency.</strong> Poorly configured Node.js installations, incompatible versions of Python (used by <code>node-waf</code> and <code>node-gyp</code>), and rebuilding between Node.js versions are just a small sample of the common errors your users will encounter if you go with compiled modules.

</p>
<p>Chances are what you're looking for already has a pure Javascript implementation. If not, then just be aware what you're getting yourself into.

</p>
<p><a name="support"></a>
</p>
<h3>Support Your Users</h3>
<p>When working with your users you have to <a href="http://blog.nodejitsu.com/understanding-open-source-branding#divorce-your-ego">divorce your ego</a>. Be helpful, friendly, and responsive. Any attitude is poison to your success. Your first users will become your greatest champions in the Open Source community at large. 

</p>
<p>That being said, know when to say "no" and "not now". If your module gets successful you're going to get a lot of feature requests. It is not your responsibility to implement all of these features, nor to implement them immediately. Have a roadmap and stick to it.

</p>
<p><a name="pull-requests"></a>
</p>
<h3>Assess Pull-Requests Carefully</h3>
<p>Once your module reaches a critical mass, you're going to get pull-requests. This is awesome. In the face of this awesomeness, however, don't lose sight of what's important. <strong>Make sure your own coding style, test coverage, and vision for your module do not suffer in your eagerness to merge a pull-request.</strong>

</p>
<p><a name="unpublish"></a>
</p>
<h3>Unpublish Versions you won't Support</h3>
<p>This lesson will probably draw some contention from the community at large. In fact, at <a href="http://nodeknockout.com/">Node Knockout</a> last year, a team made an npm registry clone for ensuring this doesn't happen. 

</p>
<p><img src="/ten-lessons-learned-maintaining-nodejs-modules/npmfjs.png" />

</p>
<p>That being said, making this decision will help you explicitly manage the expectations of your users when they open issues on your module. By removing it from <code>npm</code> you're saying implicitly that you will no longer maintain that version. If you've ever tried to keep multiple version branches in-line with hotfixes to master you understand how difficult this is and why it's not always worth it.

</p>
<p>With <a href="http://github.com/nodejitsu/forever">forever</a>, older versions were unpublished when we decided to no longer support the lowest Node.js version supported by that module. 

</p>
<p><a name="moving-on"></a>
</p>
<h3>Know When to Throw in the Towel</h3>
<p>This is a sad, but true, fact of maintaining Open Source modules. If you don't have the time to keep your module going issues are going to pile up, feature requests will go unanswered and users are going to know. This immediately forces your users to fill the void and start publishing their versions to npm. <strong>Having multiple forks of your project being used is only going to fracture whatever community you've managed to build up.</strong> 

</p>
<p>All is not lost however. Many of the most successful Open Source projects are no longer maintained by their creator. When you realize that your module is falling by the wayside reach out to your most active users. Who opened the most pull-requests? Who is the most active on your mailing list? Who helps users with issues? Any user who matches one or two of those questions is likely your best candidate for a new maintainer.  

</p>
<h2>A Grain of Salt</h2>
<p>These lessons come from years of experience writing and maintaining Node.js modules, but it is important to remember these experiences are my own. You may decided to do things differently and that is a good thing. Experiment, be creative and keep hacking!

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

</p>
]]></description><link>http://blog.nodejitsu.com/ten-lessons-learned-maintaining-nodejs-modules</link><guid isPermaLink="true">http://blog.nodejitsu.com/ten-lessons-learned-maintaining-nodejs-modules</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Fri, 06 Jul 2012 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./you-laugh-you-lose">Congrats to You Laugh You Lose on Hacking Their Way to NodeConf</a>]]></title><description><![CDATA[<p>Last weekend <a href="https://twitter.com/#!/indexzero">Charlie Robbins</a> and I ran <a href="http://hacknodeconf.jit.su">Hack Your Way to NodeConf</a>, a 17 hour overnight hackathon to give away our last ticket to the sold out conference.  The winner would receive the ticket for NodeConf, airfare, and hotel (bonus: the chance to party with us). It was a huge prize and there could only be one winner.

</p>
<h2>The challenge:</h2>
<p>We kicked off the fun-but-grueling event at Pivotal Labs in NY over beer and artichoke pizza. I stepped up to rehash the rules, Charlie gave a live demo, and <a href="https://twitter.com/#!/jonmarkgo">Jon Gottfried</a> of Twilio presented the Portal 2 Replica Gun (!!) being offered as a side prize for best Twilio hack. 

</p>
<p><img src="/you-laugh-you-lose/intros.jpg" alt="" />

</p>
<p><img src="/you-laugh-you-lose/portal2.jpg" alt="" />

</p>
<p>After that, everyone broke and rushed off to hole themselves up in various conference rooms to code like mad  for the next 17 hours. Some formed teams while others were 1 person armies. We made coffee. We drank Red Bull. We cracked jokes. Ideas were spun up and tossed aside. The hours wore on and we all started to get a bit bleary eyed. 

</p>
<p><img src="/you-laugh-you-lose/thumbsup.jpg" alt="" />

</p>
<h2>The winner:</h2>
<p>At 1:30pm the next day, we officially ended hack time. Charlie gathered everyone around for demos and I ran the conference call with our handpicked judging panel: <a href="https://twitter.com/#!/dshaw">Daniel Shaw</a>, <a href="https://twitter.com/#!/CarterRabasa">Carter Rabasa</a>, <a href="https://twitter.com/#!/csanz">Christian Sanz</a>, <a href="https://twitter.com/#!/dscape">Nuno Job</a> (of Nodejitsu), <a href="https://twitter.com/#!/joemccann">Joe McCann</a> and <a href="https://twitter.com/#!/visnup">Visnu Pitiyanuvath</a>. Judging was based on Originality, Completeness, Design, and Fun.

</p>
<p>The judges selected <a href="http://youlaugh.youlose.jit.su">You Laugh You Lose</a> (requires either <a href="https://tools.google.com/dlpage/chromesxs">Canary</a> or <a href="http://www.opera.com/">Opera</a>), created by <a href="https://twitter.com/#!/reconbot">Francis Gulotta</a> and <a href="https://twitter.com/#!/koudelka">Michael Shapiro</a>. YLYL used OpenCV for facial recognition and flashes a bunch of funny pictures from internet memes. If you laugh, you’re disqualified. For added fun, you can play against others remotely.

</p>
<p><img src="/you-laugh-you-lose/winners.jpg" alt="" />

</p>
<p><img src="/you-laugh-you-lose/ylyl.jpg" alt="" />

</p>
<p>It was great to have everyone involved, and it was especially cool that some folks who were new to node came out and used the event as an excuse to get themselves up and running.
More <a href="https://www.dropbox.com/sh/q14z0cty0wrakar/stfVFJIwoB">photos</a> from Hack Your Way to NodeConf can be found here. 

</p>
<p>Next stop, Portland!
</p>
]]></description><link>http://blog.nodejitsu.com/you-laugh-you-lose</link><guid isPermaLink="true">http://blog.nodejitsu.com/you-laugh-you-lose</guid><dc:creator><![CDATA[Ana Hevesi]]></dc:creator><pubDate>Thu, 28 Jun 2012 02:51:48 GMT</pubDate></item><item><title><![CDATA[<a href="./introducing-blakmatrix-and-migratorbot">Introducing blakmatrix and migratorBot</a>]]></title><description><![CDATA[<p>Hi, my name is Farrin Reid. I <em>love</em> developing awesome software, tinkering with open source hardware, and trying out new hobbies. I am most intrigued by automation, strong AI, and all fields of science. I am excited to be working at <a href="http://jit.su/">Nodejitsu</a> as one of the team.

</p>
<h2> </h2>
<p>I graduated from the <a href="http://www.uaf.edu/uaf/about/">University of Alaska Fairbanks</a> in 2009. I stuck around for a few years and became a developer/programmer for the University of Alaska. About a year ago, I decided I wanted to move away; out of the cold, closer to family, and to expand my career horizon.  I packed up 8 years of worth of collected belongings between my wife and I into our car and at 1:30pm June 18, 2011, I started my journey out of Fairbanks, AK to Seattle, WA. 


</p>
<p>I had a few interviews lined up when I arrived, but at the time the market was looking for senior developers. In the interim of looking for something to pay the bills, I got introduced to node.js and all its' awesomeness. Long story short, a friend and I decided to step out of our comfort zones and sign up for a competition in a language we knew nothing about (other than a little JavaScript/jQuery knowledge). We signed up for the <a href="http://nodeknockout.com/">Node Knockout 2011</a> competition. We had a trial run and did everything wrong and 26 hours in decided to start drinking, when we woke up 52 hours later we had an app called YUMDUM—Don't ask, we don't even know... As for how we did at the competition, we didn't place but we had fun leaning more about node.js, <a href="https://developers.google.com/transit/gtfs/reference">GTFS</a>, and attempting to make a simple public transit routing application on the web. 


</p>
<p>Shortly after the competition I started a Support Engineer role at a local company in Seattle. There I got to learn what support was like at the first tier of a software company and all about graveyard shifts. In other words, I completed my Jedi training (in reverse) and became a <a href="http://i.imgur.com/wiNnI.jpg">Master of Support</a>.  


</p>
<p><a href="http://www.youtube.com/watch?v=aZJZK6rzjns"><img src="http://i.imgur.com/ibuKh.jpg" alt="Tim the Enchanter is the ultimate master of support" /></a>  


</p>
<p>Fast forwarding to the past few weeks, I was on my normal graveyard shift when I decided to ping Josh and see what was up with him and Nodejitsu. We got to talking about how awesome his job was, how he could really use an awesome Support Engineer, and how together we could pave the way to glory for Nodejitsu with node.js. And then that talk became reality!


</p>
<p>For my first project at Nodejitsu, I have been working on a bot that will make node.js code compliant with the version that is being released very soon. Actually, the change was first introduced in node.js v0.3.0 but it hasn't been an issue until node v0.8.0. this is because the “sys” module throws if you try to require it in an application.  


</p>
<p>The <a href="https://github.com/blakmatrix/node-migrator-bot">migratorBot</a> has several modes, but the most interesting are "repo" and "npm". The "repo" command will take either a location to a folder or a git hub link to a repository.  If you provide it with a Github repository it will take your provided username,fork the repository, clone it locally, check out a new branch, make any changes, push that commit back to Github, <strong>then it will <a href="https://github.com/nodejitsu/node-http-proxy/pull/267">submit a Pull Request</a> to the original repository owner with a friendly message about why the changes were made.</strong> 

</p>
<p><a href="https://github.com/nodejitsu/node-http-proxy/pull/267"><img src="http://i.imgur.com/ywJTU.png" alt="The Pull Request - the robot is quite smashing, if I do say so myself" /></a>


</p>
<p>The other interesting mode is "npm". This mode will query ALL of the packages in npm that have links to Github repositories and will process all 10,000+ repositories, this might be why your reading this blog if the <a href="https://github.com/blakmatrix/node-migrator-bot">migratorBot</a> has left you with a pull request on Github. <em>You’re Welcome!</em>


</p>
<p>This project has been fun and challenging as its been about six months since I have developed any serious node.js applications. Coming back onto the scene and being greeted with flatiron, <a href="https://github.com/flatiron/winston">winston</a>, and various other highly useful frameworks and tools has been highly rewarding.
</p>
]]></description><link>http://blog.nodejitsu.com/introducing-blakmatrix-and-migratorbot</link><guid isPermaLink="true">http://blog.nodejitsu.com/introducing-blakmatrix-and-migratorbot</guid><dc:creator><![CDATA[Farrin Reid]]></dc:creator><pubDate>Sat, 23 Jun 2012 03:05:10 GMT</pubDate></item><item><title><![CDATA[<a href="./a-global-look-at-community-building-and-where-to-find-us-next">A Global Look At Community Building And Where To Find Us Next</a>]]></title><description><![CDATA[<p>Not so long ago we've <a href="http://blog.nodejitsu.com/april-conference-overload">blogged</a> about conferences we're planning to attend. But since face time with the community is really important to Nodejitsu, there's another batch of events we'll be visiting and organizing. 

</p>
<h2>Hacking our way to NodeConf</h2>
<p>Of course, we're heading to NodeConf this July and showing up in force. But we've got one extra ticket for the sold out conference, and we've figured out a fun way to give it away. This weekend we're hosting <a href="http://hacknodeconf.jit.su/">a hackathon</a> in NY along with folks at <a href="http://pivotallabs.com/">Pivotal Labs</a> and <a href="http://twilio.com/">Twilio</a>. Whoever puts together the best hack will win the last ticket to NodeConf, airfare, and space in the hotel with the Nodejitsu team.

</p>
<h2>Meet.js</h2>
<p>On the other side of the world, <a href="https://twitter.com/hij1nx">Paolo</a> recently travelled to Germany for <a href="http://berlinbuzzwords.de/">Berlin Buzzwords</a>, and being so close to Poland, he decided to pop in and pay <a href="https://twitter.com/#!/mmalecki">Maciej</a> and me a visit. This was a great excuse for me to invite him to JavaScript meetups I've recently started organizing - <a href="http://twitter.com/meetjs">meet.js</a>, a series of barcamps held in various Polish cities, originally founded by <a href="http://twitter.com/varjs">Damian Wielgosik</a>.

</p>
<p>We managed to get an interesting lineup in place for our most recent gathering on Monday, June 11th. Besides node.js basics (covered by Paolo) other topics were: behavior driven development, ECMAScript.next and functional programming. The event had more than 60 attendees and apparently vast majority was really curious about server-side of things. 

</p>
<p><img src="/a-global-look-at-community-building-and-where-to-find-us-next/meetjs.png" alt="Paolo at Meet.js" />

</p>
<p>Obviously we were onto something. I decided to quickly team up with gang of passionate developers at <a href="http://www.futuresimple.com/">Future Simple</a> known for organizing <a href="http://hackkrk.com/">HackKRK</a> hackathons and do something more to meet the needs of passionate Polish JS community.

</p>
<h2>Node.js workshops</h2>
<p>We've decided to do a workshop conducted by Paolo. The interest simply went beyond our expectations. We've gathered one workshop group and had another on the waiting list. We were contacted by people from other countries as well - either willing to attend or help to organize such workshop in different locations. Apparently there are developers willing to travel across the country to listen to talks about Node. Of course this is a pattern - in the past conferences like <a href="http://www.nodeconf.com/">NodeConf</a> or <a href="http://2012.jsconf.eu/">jsConf</a> sold out literally within seconds. 

</p>
<h2>Spain.js</h2>
<p>Another event we'll be present on is small conference in Madrid, Spain. I'll be speaking about <em>The Pursuit of Simplicity</em>; embracing the importance of sane decisions during design and development processes, the case of various libraries or frameworks and many more. So if you happen to be in sunny Spain make sure to drop me a line.</p>
]]></description><link>http://blog.nodejitsu.com/a-global-look-at-community-building-and-where-to-find-us-next</link><guid isPermaLink="true">http://blog.nodejitsu.com/a-global-look-at-community-building-and-where-to-find-us-next</guid><dc:creator><![CDATA[Karolina Szczur]]></dc:creator><pubDate>Thu, 14 Jun 2012 21:42:57 GMT</pubDate></item><item><title><![CDATA[<a href="./on-disrupting-pricing-models">On Disrupting Pricing Models</a>]]></title><description><![CDATA[<p><strong>Today Nodejitsu is happy to announce our <a href="http://nodejitsu.com/#/paas/pricing">Public Cloud Pricing</a>, which will become widely available in the next few weeks.</strong>

</p>
<p>It has been a long time coming. We have been working on making Nodejitsu the best-of-breed Node.js platform with outstanding <a href="http://www.nodejitsu.com/#/enterprise/products">cloud orchestration and infrastructure tools</a> to back it up for over two years. In that time, the Node.js community has grown organically into a vibrant group of dedicated professionals from all over the world. They are focusing on the right problems: creating and improving software and tools that set the standard for innovation. 

</p>
<p><strong>Our commitment to the community remains steadfast and the pricing for Nodejitsu is designed to only further the goals of the community and our customers.</strong>

</p>
<p>Our plans are designed to service both <strong><em>Individuals</em></strong> building non-critical applications or experiments and <strong><em>Businesses</em></strong> who need dedicated resources for hosting mission critical applications.

</p>
<p><br />
</p>
<h3>Individuals</h3>
<p style="margin: 0; padding: 0;"><img src="on-disrupting-pricing-models/individuals.png" /></p>

<p><br />
</p>
<h3>Businesses</h3>
<p style="margin: 0; padding: 0;"><img src="on-disrupting-pricing-models/businesses.png" /></p>

<p>It may be surprising to you that Nodejitsu is not offering an unlimited free tier. This is intentional. The choice represents our deeply held belief that <strong>competing Platform-as-a-Service pricing models are doing damage to developer communities everywhere. We do not want to be part of the same problem.</strong>

</p>
<h2> </h2>
<p>And what is the problem at hand? Let me preface this by saying I am an technologist. I have been building things with technology as long as I can remember. So believe me that I say this with all the love in my heart: <strong><em>developers feel too entitled.</em></strong> Far too frequently in the Open Source community, I see the wasted potential of those focused on making demands instead of spending their energy on creating value. Don't forget, <a href="http://blog.nodejitsu.com/getting-refunds-on-open-source-projects">there are no refunds on Open Source projects</a>.

</p>
<p>It is, however, not completely their fault. <strong>Developers have been subject to pervasive incentives for years.</strong> In our Information economy those who understand and actively shape the flow of information (i.e. developers) hold a heavy sway over public opinion:

</p>
<ul>
<li>Our families and friends value our opinions of what technology to buy. </li>
<li>Our labors contribute to the consumer products reaching millions of people.</li>
<li>The opinions of our communities -- both in the mainstream and the dissents -- shape the futures of multi-billion dollar corporations, whose executives pay close attention to what developers have to say.</li>
</ul>
<p>Thus to leading tech companies, in both the consumer and enterprise markets (read: Google, Microsoft, Apple, etc) the mantra has become "make developers happy and ye shall succeed."

</p>
<h2>Impact on Cloud Computing</h2>
<p><strong>Now consider cloud computing.</strong> In their drive to make developers happy early Platform-as-a-Service companies introduce an <em>unlimited</em> "free tier" usually comprised of one or two compute units of varying size. This may be an energetic effort to increase product distribution, but it is <strong><em>the fundamental problem with Platform-as-a-Service pricing.</em></strong>

</p>
<p>You may be asking yourself: "Huh? Isn't an unlimited free tier a good thing?" In reality, this pricing system distorts developers’ incentives, to the detriment of their customers and themselves. Investors with whom I’ve spoken who have placed bets with some of Nodejitsu’s competitors have told me that if they were to "do it over again, they would never have created a free tier."

</p>
<p><br />
</p>
<h3>1. <em>It ignores the varying needs of customer segments</em></h3>
<p>Very early in the life of Nodejitsu, based on feedback and user data from our private beta, two distinct customer segments became obvious to us:

</p>
<p><strong><em>Individuals:</em></strong> Developers or independent freelancers who wish to host personal applications which they expect small to moderate amounts of traffic. If these apps experience higher than average latency or less than a 24x7 SLA the disruption has a minimal effect on the customer.

</p>
<p><strong><em>Businesses</em>:</strong> Small to medium sized businesses that want to host one or more applications in a real <em>production environment.</em> These applications need minimal latency and maximum uptime; disruptions could mean a real impact on their revenue or their reputation with their customers.

</p>
<p>What both segments have in common is their wish to offload completely their developer operations  to Nodejitsu (That said, if you already have a devops team <a href="http://www.nodejitsu.com/#/enterprise/products">why don't you checkout some of our Enterprise solutions?</a>).

</p>
<p><strong>By creating two different pricing plans for both Individuals and Businesses we at Nodejitsu seek to find a middle ground for everyone.</strong>

</p>
<p><br />
</p>
<h3>2. <em>It discourages giving back</em></h3>
<p>Economists like to evaluate incentives by considering <a href="http://en.wikipedia.org/wiki/Rational_choice_theory">rational behavior</a> and <a href="http://en.wikipedia.org/wiki/Utility">utility theory</a>. <a href="http://www.investopedia.com/terms/r/rational-behavior.asp">To sum it up</a>:

</p>
<blockquote>
<p>Rational behavior is a decision-making process that is based on making 
choices that result in the most optimal level of benefit or utility
for the individual.

</p>
</blockquote>
<p>How might an unlimited free tier influence the rational behavior of developers? If the desired utility can be obtained for free, then there is no incentive for developers to contribute beyond improving a product and workflow they use regularly. Although this secondary incentive will elicit contributions from some developers there is a huge set of developers for whom this is not enough.

</p>
<p><strong>We are working on new and innovative ways to motivate developers to contribute to the Open Source community through the Nodejitsu platform.</strong>

</p>
<p><br />
</p>
<h3>3. <em>It encourages "beating the system"</em></h3>
<p>To save money on the free tier many Platform-as-a-Service companies will turn off applications while they are not in use. In theory, this may create economy for the platform companies, but by offering an unlimited free tier these companies have told developers "if you keep this application active it will stay up." I can't tell you how many times I've heard a ludicrously simple way of getting around these idle shutdown systems. This is why many of our competitors <a href="https://devcenter.heroku.com/articles/http-routing#timeouts">do not support long-held connections or WebSockets</a>. 

</p>
<p><strong>Nodejitsu <em>was <a href="http://github.com/nodejitsu/node-http-proxy">the first platform to support WebSockets</a></em> and we remain committed to providing the best WebSocket and soft real-time experience on the web.</strong>

</p>
<p><br />
</p>
<h3>4. <em>It causes price inflation for average users</em></h3>
<p>So if an unlimited free tier encourages abuse of resources, who pays the price for the waste? Platform-as-a-Service companies really have two choices. The first is to operate at a loss. This has been the model for large technology companies with existing revenue models that are attempting to break into the market space. Operating at a loss is, obviously, not sustainable. As more platform companies announce pricing plans over the coming months, we expect many of them to transition to the second choice for dealing with this cost inefficiency:&nbsp;<em>passing this cost on to the&nbsp;<strong>paying user</strong>.</em>&nbsp;This is already a widespread practice in the platform startup space, and somehow it seems to be tolerated.  For what should be an affordable resource, the markup on 300MB of RAM has <a href="https://www.dotcloud.com/pricingfaq.html">really gotten out of control.</a>

</p>
<p><strong>I’ll say it again: paying customers (many of them individual developers and freelancers) are subsidizing the warped incentive for developers to work around platform companies’ payment plan restrictions.</strong>

</p>
<p><br />
</p>
<h2>Our Commitment to You</h2>
<p>These ideas all underpin our decision at Nodejitsu to limit the free tier in our <a href="http://nodejitsu.com/#/paas/pricing/sandbox">Development Sandbox</a>. <strong>We want you to try Nodejitsu today for free.</strong> We will do our best to ensure that your trial period lasts as long as possible. When that trial period is over <em>we have paid plans starting at just $4 per month.</em> We will also be offering many of our <a href="http://www.nodejitsu.com/#/enterprise/products">Enterprise Products</a> as a service in addition to our existing Enterprise software model. 

</p>
<p>It may be difficult to accept, but it is our belief that a limited free tier will encourage developers to look beyond the free services of the platform and to consider how they can best use Nodejitsu's tools to continue to build a better community. We developers need to realize that we have the power to actively shape our surroundings through self-motivated creation instead of waiting for the next version of your favorite library. <em>Fix a bug, fork a project, add a feature, you're going to make someone else's day.</em> Stay tuned and keep creating! 

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

</p>
]]></description><link>http://blog.nodejitsu.com/on-disrupting-pricing-models</link><guid isPermaLink="true">http://blog.nodejitsu.com/on-disrupting-pricing-models</guid><dc:creator><![CDATA[Charlie Robbins]]></dc:creator><pubDate>Mon, 11 Jun 2012 17:00:00 GMT</pubDate></item><item><title><![CDATA[<a href="./introducing-winstond">Introducing Winstond</a>]]></title><description><![CDATA[<p>Logging seems like it should be simple enough, but when you're dealing with
multiple machines, multiple nodes, and multiple apps which all need to log in
some kind of organized fashion, things can get complicated very quickly.
To make things more interesting, not only do these things need to log, but they
need to manage and access the logs as well.

</p>
<hr />
<p>A year and a half ago, <a href="https://github.com/flatiron/winston">Winston</a> was created in an attempt to unify all
potential logging transports. While winston serves its job well, another
project needed to be added to the equation to help solve the problem mentioned
above.

</p>
<p>Winston's success has been defined by it's ability to instantiate loggers and
add multiple different transports to each one.

</p>
<the-deceptively-simple-nature-of-logging>

<p>I'm sure it would be easy enough to whip up your own logger which simply creates
and writes to a file stream, but, obviously, there is more to winston than just
a single transport. The portability is key, along with the extensibility of any
transport imagineable.

</p>
<p><img src="./introducing-winstond/dia0.png" />

</p>
<p>While the logger above is great, and winston carries all the extensibility in
the world, you're still stuck with one logger inside one process. Kind of like
an in-process database: it's great, and simple, until it becomes its own
obstacle, and gets in its own way.

</p>
<p>One day you're using sqlite, and everything just works, until you need massive
amounts of webscale; direct intravenous injections of pure webscale. All of the
sudden, in-process doesn't cut it, and you need a <strong>server</strong>. This is what led
to the creation of <a href="https://github.com/flatiron/winstond">winstond</a>.

</p>
<h2>winstond</h2>
<p><a href="https://github.com/flatiron/winstond">Winstond</a> is an attempt to solve this problem. As the name implies, it is a
configurable server, built on top of <a href="https://github.com/flatiron/winston">winston</a>, using all of winston's core
methods. This means it acts exactly like a logger, and uses the same transports
winston does.

</p>
<p>A winstond server doesn't look much different from winston itself. The only
difference between a winstond instance and a winston <code>Logger</code> is the ability
to act as a server using one of two different backends. Right now, that includes
<a href="https://github.com/flatiron/winston/blob/master/lib/winston/transports/http.js">HTTP</a> and <a href="https://github.com/nodejitsu/nssocket">NsSocket</a>, although more future backends aren't out of the
question.

</p>
<p>Creating a winstond nssocket server and talking to it should be simple enough.

</p>
<h3>winstond (our server):</h3>
<the-deceptively-simple-nature-of-logging>

<p>The HTTP backend would look similar. The differences between the two, aside from
the HTTP backend using a non-bidirectional protocol, is that the HTTP backend
uses json-rpc and the <code>Http</code> transport to communicate with winstond.

</p>
<h3>winston (our client):</h3>
<the-deceptively-simple-nature-of-logging>

<p>Using the Nssocket transport, winstond can handle the querying and streaming
on the client's behalf.

</p>
<hr />
<p>While it may not appear to be terribly practical at first, the fact that a
winstond server is still just a winston Logger instance at heart has some
interesting implications, such as creating the possibility of adding the
nssocket transport to a winstond server, and have it talk to another winstond
server.

</p>
<the-deceptively-simple-nature-of-logging>

<p><img src="./introducing-winstond/dia1.png" />

</p>
<h2>winston</h2>
<p>While winstond is a thin layer on top of winston, maybe the the most interesting
things this entails are the changes to winston itself.

</p>
<p>The creation of winstond has some implications. Not only do you need this server
over an in-process model, you also need to access and manage your data. This is
very helpful for a winstond server, but it's also just helpful for winston being
used standalone.

</p>
<p>Most every winston transport has now been equipped with the ability to stream
logs back to winston, as well as to query logs, using Loggly-like query options.

</p>
<p>Depending on the transport's natural abilities to do this, (e.g. redis might
have a harder time querying than couch), every future transport should include
a <code>stream()</code> and <code>query()</code> method. If a transport does not support these
methods, the transport will be ignored when a logger needs to query or stream.

</p>
<h3>Querying</h3>
<the-deceptively-simple-nature-of-logging>

<p>Query results will return an aggregate object, containing all results from each
transport. This can be avoided by specifying a transport name in the options.

</p>
<h3>Streaming</h3>
<the-deceptively-simple-nature-of-logging>

<p>This essentially <code>tail -f</code>'s the log file we setup using the <code>File</code> transport.
The stream will stream in every transport possible, and because it cannot
produce an aggregate object like the <code>query</code> method can, a <code>transports</code>
property will be added to each log object.

</p>
<h3>Underneath the Surface</h3>
<p>So how is something like streaming implemented? In Mongo, we can use a
<a href="http://www.mongodb.org/display/DOCS/Tailable+Cursors">tailable cursor</a>. In Redis, we can use the
<a href="http://redis.io/topics/pubsub">built-in pub/sub capabilities</a>. As mentioned above, for files, we can
implement our own <code>tail -f</code>, which polls the file with constant <code><span class="identifier"><span class="keymethods">read</span></span>(<span class="number">2</span>)</code> calls,
and in Couch, we can use Couch's <a href="http://wiki.apache.org/couchdb/HTTP_database_API"><code>_changes</code></a> notification functionality.
Each transport usually has some ability to stream, or query, that can be
tapped into. Winston will now unite all of this functionality.

</p>
<p>Unfortunately, some transports might not carry any built-in streaming
(or querying) functionality in any way, in which case, the transport will have
to resort to more primitive and less elegant measures, like polling. Don't get
the impression that winston makes the choice of transport irrelevant, because
it doesn't. It only makes things cleaner. You still probably want to
decide between files, couch, redis, mongo, etc., depending.

</p>
<p>Any future transports for winston would be smart to add <code>query</code> and <code>stream</code>
methods, but it is not necessary.

</p>
<h2>Solutions</h2>
<p>At Nodejitsu, winstond will be used as the basis for our logging server.
This will allow users to easily stream logs from their apps rather than
essentially polling for them by hand.

</p>
<h2>Conclusion</h2>
<p>So what would be the difference between having all of your apps log to a shared
Couch server, as opposed to passing all logs through a winstond server first?
Winstond can handle multiple transports, it can talk to other winstond servers,
all traffic can be handled at a single configurable, hookable, administrable
endpoint, and <em>only</em> this endpoint has to be configured the way you want it.
Every other process can mindlessly talk to the winstond server, using the
<code>nssocket</code> or <code>http</code> transport.

</p>
<p>If you have more than a few apps to deal with, and want to unify their logs in
a useful way, winstond might do the trick as far as consolidating these logs.

</p>
</the-deceptively-simple-nature-of-logging></the-deceptively-simple-nature-of-logging></the-deceptively-simple-nature-of-logging></the-deceptively-simple-nature-of-logging></the-deceptively-simple-nature-of-logging></the-deceptively-simple-nature-of-logging>]]></description><link>http://blog.nodejitsu.com/introducing-winstond</link><guid isPermaLink="true">http://blog.nodejitsu.com/introducing-winstond</guid><dc:creator><![CDATA[Christopher Jeffrey]]></dc:creator><pubDate>Mon, 04 Jun 2012 18:33:04 GMT</pubDate></item><item><title><![CDATA[<a href="./it-s-about-time">It's about time</a>]]></title><description><![CDATA[<p>Hi, my name is <a href="http://tmpvar.com">Elijah Insua</a>.  I have a deep interest in node and javascript in general.  In my free time I build computer controlled machines and make my own pcbs for hardware projects.  I enjoy playing / building games, experimenting with the countless modules on npm, and keeping up with web standards. I have been acquainted with the nodejitsu co-founders since before nodejitsu and this is my story!

</p>
<h2>History</h2>
<p>It was a cold New York night in early 2010, and we were all huddled around a projector watching people present their new javascript libraries. I do not recall all of the speakers that night at NYC.js, but I do know that is where I met Marak Squires after he gave a talk on some outlandishly awesome webhook thing (now known as <a href="https://github.com/hookio">hook.io</a>).  He was dressed in a full on suit, sneakers, and a fitted NY baseball cap cocked slightly to the side.  Being an inquisitive person, I decided to figure out what made this guy tick.

</p>
<p>So I pulled him aside, as the meeting was breaking up, and introduced myself. After a short talk with him I realized he was <em>at least</em> as fanatical about javascript and node.js as I was.  A group of us went back to the apartment he shared with Charlie Robins for beers and a "Javascript Party".

</p>
<p>Things clicked pretty well between Charlie, Marak, and myself, and I would head over there nearly daily to hang out and hack on various node projects with Marak.  Charlie was still a Microsoft dude by day and ruby guy by night. Over the course of a month or so, after enthusiastic debates and poking bits of fun, we actually got Charlie writing javascript under node.  It did not take long until he had the bug, just as Marak and I had after seeing Ryan Dahl's jsconf.eu talk in late 2009. It was perfect timing to throw Paolo Fragomeni into the mix.

</p>
<p>Paolo and I had been talking about node and jsdom over irc while he was living in Texas.  Apparently he could sense what was going down in NYC and decided to make the move.  At one point he asked me if I had a couch or knew of one he could crash on while he found a place.  I explained that I lived an hour out of the way by subway, but I mentioned that Marak was more centrally located and there was potentially a couch there for him to crash on.  It worked out and we gained another javascript/node fanatic!

</p>
<h2>Fun times, cut short</h2>
<p>Shortly thereafter, my employer at the time took on a <em>huge</em> contract which required me and a couple others to carry the load of a 15+ person IT staff that was relieved of duty at a moments notice.  It was a bloated legacy mess of enterprise java, and it was our job to keep the site running and eventually rebuilt it.  There were many long nights, and my "Javascript Party" time was limited greatly.

</p>
<p>Unfortunately, I missed the birth of nodejitsu, but I tried to see the nodejitsu guys as much as time would allow. A year later I decided to take my leave of NY and move to Arizona. I've spent nearly a year consulting, building open source projects, <a href="https://vimeo.com/34575470">tinkering</a> <a href="http://www.youtube.com/watch?v=DbJdYH99TcU">with</a> <a href="http://www.youtube.com/watch?v=rkpCB_RS760">hardware</a>, <a href="http://i.imgur.com/vzBaU.png">enjoying nature</a>, and trying to relax.

</p>
<h2>Working at nodejitsu</h2>
<p>I am extremely excited to be working with the nodejitsu of today!  They have built a solid and compelling product, and I simply cannot wait to help get them to the next level.</p>
]]></description><link>http://blog.nodejitsu.com/it-s-about-time</link><guid isPermaLink="true">http://blog.nodejitsu.com/it-s-about-time</guid><dc:creator><![CDATA[Elijah Insua]]></dc:creator><pubDate>Fri, 01 Jun 2012 20:15:55 GMT</pubDate></item><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><a href="/hiring-open-source-developers#become-open-source-developer">How to become an open-source developer?</a></li>
<li><a href="/hiring-open-source-developers#get-recruited-as-open-source-developer">How do you get recruited as an open-source developer?</a></li>
</ul>
<p><a name="become-open-source-developer"></a>
</p>
<h2>How to become an open-source developer?</h2>
<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>
<h2>How do you get recruited as an open-source developer?</h2>
<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><strong>Get a pull request merged on Github.</strong>

</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>
<h3>The problem</h3>
<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>
<h2>To iterate is human, to recurse is divine</h2>
<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="./ioc-and-dependency-injection-with-broadway">Inversion of Control and Dependency Injection with Broadway</a>]]></title><description><![CDATA[<p>Over the last few months I've been using <a href="https://github.com/flatiron">flatiron</a> and by extension <a href="https://github.com/flatiron/broadway">broadway</a>.

</p>
<p>I like broadway a lot, so I'd like to take this opportunity to explain how it works and why you should be using it.

</p>
<p>Here are a few phrases and bits of jargon that tend to pop up when discussing broadway:

</p>
<ul>
<li>Inversion of Control</li>
<li>Dependency Injection / Feature reflection</li>
<li>Application extensibility</li>
</ul>
<p>In this post, I'm going to explain what the mean, how they work in broadway, and why they're a good thing.

</p>
<p>More after the break!

</p>
<h2> </h2>
<h1>What's Inversion of Control?</h1>
<p>Inversion of control is basically just a fancy term for plugins. For example, connect and express middlewares implement a sort of inversion of control:

</p>
<pre><code>connect.use(<span class="function"><span class="keyword">function</span> <span class="title">invertedControl</span> <span class="params">(req, res, next)</span> {</span>
  <span class="comment">// Function now has control of our request and response</span>

  <span class="comment">// Code that may or may not manipulate the req and res objects.</span>

  next();
});</code></pre>
<p>The idea of "inversion of control" is usually contrasted with an older "procedural" paradigm. When writing code in a procedural style, you would have a central piece of code and change its behavior directly. Here's an example with python 2.7's BaseHTTPServer:

</p>
<pre><code><span class="identifier">from</span> <span class="constant">BaseHTTPServer</span> <span class="identifier">import</span> <span class="constant">HTTPServer</span>, <span class="constant">BaseHTTPRequestHandler</span>

<span class="class"><span class="keyword">class</span> <span class="title">RequestHandler</span>(<span class="title">BaseHTTPRequestHandler</span>):</span>
  <span class="function"><span class="keyword">def</span> <span class="title">do_GET</span><span class="params">(<span class="identifier">s</span>)</span>:</span>
    <span class="identifier">s</span>.<span class="identifier">send_response</span>(<span class="number">200</span>)
    <span class="identifier">s</span>.<span class="identifier">end_headers</span>()
    <span class="identifier">s</span>.<span class="identifier">wfile</span>.<span class="identifier"><span class="keymethods">write</span></span>(<span class="string">'Pong!'</span>)

<span class="identifier">server</span> = <span class="constant">HTTPServer</span>((<span class="string">''</span>, <span class="number">8080</span>), <span class="constant">RequestHandler</span>)


<span class="identifier">server</span>.<span class="identifier">serve_forever</span>();</code></pre>
<p>This snippet runs a synchronous http server and uses classes for handlers. There isn't an equivalent here for node, since node's http server is asynchronous.

</p>
<p>Even though it sounds complicated, it simply describes a family of design patterns where an object is manipulated directly by a called function.

</p>
<p>In broadway, a basic example of inversion of control looks like this:

</p>
<pre><code><span class="keyword">var</span> app = <span class="keyword">new</span> broadway.App;

<span class="comment">// This will throw an error.</span>
<span class="comment">//app.say('Oh, what a world.');</span>

<span class="comment">// This plugin is often a separate module.</span>
<span class="keyword">var</span> sayPlugin = {
  attach: <span class="function"><span class="keyword">function</span> <span class="title">attachSay</span> <span class="params">()</span> {</span>
    <span class="keyword">this</span>.say = console.log;
  }
}

app.use(sayPlugin);

<span class="comment">// Will print 'Hi world!' as we expect.</span>
app.say(<span class="string">'Hi world!'</span>);</code></pre>
<p>In this example, when our app <code>.use</code>s the <code>sayPlugin</code>, the <code>attachSay</code> function gains control of the <code>app</code> object (referred to in the scope of <code>attachSay</code> as <code><span class="keyword">this</span></code>). Now all we need to do to give our broadway app a working <code>.say</code> is use the <code>sayPlugin</code> plugin!

</p>
<p>This of course hardly scratches the surface of broadway's capabilities.

</p>
<h1>What are Dependency Injection and Feature Reflection?</h1>
<p>Really, dependency injection is a particular flavor of these "inversion of control" patterns. Yes, I said the 'p-word'. But don't worry! All this means is that dependency injection is a 'thing'.

</p>
<p>Dependency injection implies 3 things:

</p>
<ul>
<li>An <strong>injection container</strong> that uses plugins</li>
<li><strong>plugins</strong> that modify the behavior of the container</li>
<li>A way to for some plugins to <strong>depend</strong> on other previously-loaded plugins</li>
</ul>
<p>The <a href="http://en.wikipedia.org/wiki/Dependency_injection">Wikipedia article</a> on the subject says as much, but focuses on the use of dependency injection in static languages like Java. For instance, the <a href="http://www.springsource.org/spring-framework">Spring</a> framework for Java <a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-introduction">implements this approach</a>. You <em>already saw</em> an example of the same style of "IoC container" in this article. The Spring framework's version, perhaps unsurprisingly, requires you to write as much XML as Java (perhaps more). I don't say this to dig on Java or Spring; I say this to point out how much more lightweight it can be in a dynamically typed language such as JavaScript.

</p>
<p>In the previous broadway example, the <code>app</code> was our <em>injection container</em> and it used the <em>plugin</em> <code>sayPlugin</code>. But what about dependencies?

</p>
<p>I'm fond of comparing building applications with broadway to assembling a <a href="http://bwog.com/wp-content/uploads/2011/10/megazord.jpeg">megazord</a> because of the way you can use multiple plugins that depend on each other to build a whole. For an example, suppose I'd like to give my app a <code>head</code> that lets it <code>say</code> things:

</p>
<pre><code><span class="comment">// head.js</span>

exports.name = <span class="string">'head'</span>;

exports.attach = <span class="function"><span class="keyword">function</span> <span class="title">attachHead</span> <span class="params">(opts)</span> {</span>

  <span class="keyword">var</span> head = <span class="keyword">this</span>.head = {};

  head.say = <span class="function"><span class="keyword">function</span> <span class="title">speak</span> <span class="params">()</span> {</span>
    <span class="keyword">var</span> words = Array.prototype.slice.call(arguments).join(<span class="string">' '</span>);

    console.log(<span class="string">'The stranger looks at you and says, "'</span> + words + <span class="string">'"'</span>);
  };

};</code></pre>
<p>Now suppose I want to give my future bot a sweet <code>hat</code>:

</p>
<pre><code><span class="comment">// hat.js</span>

exports.name = <span class="string">'hat'</span>;

exports.attach = <span class="function"><span class="keyword">function</span> <span class="title">attachHat</span> <span class="params">(opts)</span> {</span>

  <span class="comment">// This plugin *depends* on the "head" plugin being loaded.</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>.head) {
    <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'You can\'t wear a `hat` without a `head`!'</span>);
  }

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

  stranger.hat = {};
  stranger.hat.tip = <span class="function"><span class="keyword">function</span> <span class="title">hatTip</span> <span class="params">()</span> {</span>

    stranger.head.say(<span class="string">'Howdy stranger.'</span>);
    console.log(<span class="string">'He tips his hat in that half-Tom-Selleck, half-Frank-Sinatra manner.'</span>);
  };

};</code></pre>
<p>In this example, if the app has a <code>head</code>, it can wear a <code>hat</code> and gains the ability to <code>.tip</code> its <code>.hat</code>. By checking for <code><span class="keyword">this</span>.head</code>, our <code>hat</code> plugin requires that we've already <code>.use</code>d the <code>head</code> plugin.

</p>
<p>Here's what this looks like together:

</p>
<pre><code><span class="comment">// index.js</span>

<span class="keyword">var</span> broadway = require(<span class="string">'broadway'</span>);

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

<span class="keyword">var</span> stranger = <span class="keyword">new</span> broadway.App;

<span class="comment">// Attach a head!</span>
stranger.use(head);

<span class="comment">// Now you can wear a hat!</span>
stranger.use(hat);

<span class="comment">// Tip dat hat</span>
stranger.hat.tip();</code></pre>
<p>Once we give our <code>stranger</code> a head, it can wear a hat and do a pretty good cowboy impression:

</p>
<pre><code>% <span class="identifier">node</span> <span class="identifier"><span class="keymethods">index</span></span>.<span class="identifier">js</span> 
<span class="constant">The</span> <span class="identifier">stranger</span> <span class="identifier">looks</span> <span class="identifier"><span class="keymethods">at</span></span> <span class="identifier">you</span> <span class="identifier"><span class="keyword">and</span></span> <span class="identifier">says</span>, <span class="string">"Howdy stranger."</span>
<span class="constant">He</span> <span class="identifier">tips</span> <span class="identifier">his</span> <span class="identifier">hat</span> <span class="identifier"><span class="keyword">in</span></span> <span class="identifier">that</span> <span class="identifier">half</span>-<span class="constant">Tom</span>-<span class="constant">Selleck</span>, <span class="identifier">half</span>-<span class="constant">Frank</span>-<span class="constant">Sinatra</span> <span class="identifier">manner</span>.</code></pre>
<h1>What About Application Extensibility?</h1>
<p>We at Nodejitsu are excited about broadway because it allows for something we're calling "application extensibility". What does that mean?

</p>
<p>Suppose that you would like to make a hooks-based plugin system for your broadway app, where the main module looks like so:

</p>
<pre><code><span class="comment">// index.html</span>

<span class="keyword">var</span> broadway = require(<span class="string">'broadway'</span>),
    hooks = require(<span class="string">'./hooks'</span>),
    app = <span class="keyword">new</span> broadway.App,
    fooHook = {};

<span class="comment">// Example of a hook we may want to attach,</span>
<span class="comment">// depending on an event hook interface</span>
fooHook.attach = <span class="function"><span class="keyword">function</span> <span class="title">attachFooHook</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.hooks.foo = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    console.log(<span class="string">'You just called `this.hooks.foo`!'</span>);
  };
}

app.use(hooks);
app.use(fooHook);

<span class="comment">// Initialize your app!</span>
app.init(<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="comment">// When we emit 'app::foo', we want `app.hooks.foo` to get called.</span>
  app.emit(<span class="string">'app::foo'</span>);
});</code></pre>
<p>What we want is a nice way to attach 'hooks' that get called when app emits <code>app::*</code> events. Remember, <code>broadway.App</code> inherits from <a href="https://github.com/hij1nx/EventEmitter2">EventEmitter2</a>.

</p>
<p>The output of this example will look like this:

</p>
<pre><code>% node index.js
You just emitted app::foo!
You just called `<span class="keyword">this</span>.hooks.foo`!</code></pre>
<p>As it turns out, writing this plugin is actually relatively straightforward:

</p>
<pre><code><span class="comment">// hooks.js</span>

exports.name = <span class="string">'event-hooks'</span>;

exports.attach = <span class="function"><span class="keyword">function</span> <span class="params">(opts)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;

  <span class="keyword">this</span>.hooks = {};
}

exports.init = <span class="function"><span class="keyword">function</span> <span class="params">(done)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;

  self.on(<span class="string">'app::*'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    console.log(<span class="string">'You just emitted `app::foo`!'</span>);

    <span class="keyword">var</span> plugin = self.hooks[<span class="keyword">this</span>.event.split(self.delimiter)[<span class="number">1</span>]];

    <span class="keyword">if</span> (plugin &amp;&amp; <span class="keyword">typeof</span> plugin === <span class="string">'function'</span>) {
      plugin.call(self, arguments);
    };
  });

  done();
}</code></pre>
<p>First, in the plugin's <code>attach</code> method, we create the <code>app.hook</code> namespace for attaching new hooks. Then, later, the <code>init</code> method adds the relevant event listeners.

</p>
<p>Cool! But even cooler: <strong>You can reuse this "hook" plugin for building apps over and over again</strong>, and then write further plugins that <strong>depend on the hook plugin</strong>.

</p>
<h1>A Real-World Example of Application Extensibility</h1>
<p>Just last week, we released a new flatiron plugin called <a href="https://github.com/flatiron/cli-config">flatiron-cli-config</a>. Here's a version of the example on the project's front page, to illustrate its use with <code>flatiron</code>, whose app is an extended version of the base <code>broadway</code> container:

</p>
<pre><code><span class="comment">// </span>index.js

var flatiron = require('flatiron'),
    app = flatiron.app;

app.name = 'app.js';

<span class="comment">// </span>The flatiron app has loaded a basic `config` plugin.
app.config.file({ file: 'test-config.json' });

<span class="comment">// </span>Use flatiron's `cli` plugin
app.use(flatiron.plugins.cli, {
  usage: 'A simple CLI app using flatiron-cli-config'
});

<span class="comment">// </span>Use `flatiron-cli-config`, which depends on <span class="keyword">then</span> `config` and `cli` plugins.
app.use(require('flatiron-cli-config'));

<span class="comment">// </span>Note that 'app.start' automatically initializes your broadway app.
app.start();</code></pre>
<p>Based on the previous broadway examples, this should be straightforward enough. But, what the heck did the <code>flatiron-cli-config</code> plugin <strong>do</strong>? Basically, it gives you a <strong>complete CLI-based configuration API---the same as the one used by jitsu</strong>. For example, this should work:

</p>
<pre><code>% node index.js config <span class="keyword">set</span> foo bar</code></pre>
<p>Just like we gave our <code>stranger</code> a head and a hat earlier, we just gave this application a complete CLI interface including configuration with an index of only 9 lines.

</p>
<h1>Conclusions</h1>
<p>Here's the tl;dr on broadway:

</p>
<ul>
<li>It's a plugin system.</li>
<li>It lets plugins do <em>almost anything</em> to the host app.</li>
<li>Broadway plugins are like your app's gear and power-ups.</li>
</ul>
<p>Broadway is quite possibly my favorite component of all of flatiron. I hope you find the time to give it a spin! I think you'll find it worthwhile.
</p>
]]></description><link>http://blog.nodejitsu.com/ioc-and-dependency-injection-with-broadway</link><guid isPermaLink="true">http://blog.nodejitsu.com/ioc-and-dependency-injection-with-broadway</guid><dc:creator><![CDATA[Josh Holbrook]]></dc:creator><pubDate>Fri, 10 Feb 2012 21:03:32 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><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>
<h2>Basic strategies in building a decentralized and anonymous database</h2>
<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>
<h2>Introducing hnet</h2>
<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>
<h2>What is an hnet node?</h2>
<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>
<h2>What is an hnet storage engine?</h2>
<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>
<h2>Why hnet?</h2>
<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>
<h2>How does hnet work?</h2>
<h3>Many dumb hnet nodes, <a href="http://github.com/hookio/hnet/">one smart client</a>.</h3>
<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>
<h2>The hnet protocol is JSON</h2>
<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>
<h3>The <em>link</em> method is particularly important.</h3>
<h3>It indicates that we should lazily link this document from a remote dataset into the current position in the item array.</h3>
<h3>This allows us to create large datasets from many small hnet nodes.</h3>
<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>
<h2>Establishing a TTL ( Time To Live ) for circular link resolution</h2>
<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>
<h2>A quick note on Steganography and Cryptography</h2>
<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>
]]></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>
<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>
<h2>It's mathematically impossible your distributed application is not going to fuck up. Deal with it.</h2>
<hr />


<h2>Basic strategies in building fault tolerant applications in node</h2>
<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>
<h2>Hook.io</h2>
<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>
<h2>Basic Paxos</h2>
<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>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>
<h2>Building fault-tolerant node.js application with hook.io</h2>
<p>hook.io can be used programmatically 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 programmatically 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 --autoheal</code></pre>
<p><strong>Terminal 2</strong>

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

</p>
<pre><code> hookio --autoheal</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>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>
<h3>Applications built with hook.io now have no central point of failure.</h3>
<h3>But wait, there's more!!!</h3>
<h3>Mdns</h3>
<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>
<h2>Conclusion</h2>
<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>
<h2> </h2>
<h2>What is Travis CI?</h2>
<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><img src="travis-ci-at-nodejitsu/run-the-tests.png" alt="Run the fucking tests" />

</p>
<h2>Why is it important for a CI to be realtime?</h2>
<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><img src="travis-ci-at-nodejitsu/failing-code.png" alt="Checked in failing code?" />

</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>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>
<h2>Versions!</h2>
<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>
<h2>Travis is easy!</h2>
<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>
<h2>Summary</h2>
<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. 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>
<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><a name="Installing_npm"></a>
</p>
<h2>Installing npm</h2>
<pre><code> curl http:<span class="comment">//n</span>pmjs.org/install.sh | sh</code></pre>
<p><a name="Update_npm"></a>
</p>
<h2>Update npm</h2>
<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><a name="View_details_of_a_npm_package"></a>
</p>
<h2>View details of a npm package</h2>
<pre><code> npm view hook.io</code></pre>
<p><a name="Installing_a_npm_package_locally"></a>
</p>
<h2>Installing a npm package locally</h2>
<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><a name="Installing_a_npm_package_into_an_application"></a>
</p>
<h2>Installing a npm package into an application</h2>
<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><a name="Understanding_Global_versus_Local_installs_in_npm"></a>
</p>
<h2>Understanding Global versus Local installs in npm</h2>
<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><a name="Global_Package_Installation"></a>
</p>
<h2>Global Package Installation</h2>
<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><a name="Uninstalling_a_package_locally"></a>
</p>
<h2>Uninstalling a package locally</h2>
<pre><code>cd mynewapp/
npm uninstall http-server</code></pre>
<p><a name="Uninstalling_a_package_globally"></a>
</p>
<h2>Uninstalling a package globally</h2>
<pre><code>npm uninstall http-server -g</code></pre>
<p><a name="Installing_a_specific_version_of_a_package"></a>
</p>
<h2>Installing a specific version of a package</h2>
<pre><code>cd mynewapp/
npm install http-server@0.3.0</code></pre>
<p><a name="Cloning_a_module_from_Github"></a>
</p>
<h2>Cloning a module from Github</h2>
<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><a name="Linking_any_npm_package_locally"></a>
</p>
<h2>Linking any npm package locally</h2>
<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><a name="Linking_local_npm_packages_to_multiple_applications"></a>
</p>
<h2>Linking local npm packages to multiple applications</h2>
<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><a name="Unlinking_a_npm_package_from_an_application"></a>
</p>
<h2>Unlinking a npm package from an application</h2>
<pre><code>cd newapp/
npm unlink http-server</code></pre>
<p><a name="Unlinking_a_npm_package_from_your_system"></a>
</p>
<h2>Unlinking a npm package from your system</h2>
<pre><code>cd http-server/
npm unlink</code></pre>
<p><a name="Create_a_new_npm_package"></a>
</p>
<h2>Create a new npm package</h2>
<pre><code>mkdir mypackage/
cd mypackage/
npm init</code></pre>
<p><a name="Creating_a_new_user_account_on_npm"></a>
</p>
<h2>Creating a new user account on npm</h2>
<pre><code>npm adduser</code></pre>
<p><a name="Publishing_a_npm_package"></a>
</p>
<h2>Publishing a npm package</h2>
<pre><code>cd mypackage/
npm publish</code></pre>
<p><a name="Unpublishing_a_npm_package"></a>
</p>
<h2>Unpublishing a npm package</h2>
<pre><code>npm unpublish http-server</code></pre>
<p><a name="Managing_owners_of_packages"></a>
</p>
<h2>Managing owners of packages</h2>
<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>