<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:series="http://organizeseries.com/"
	>

<channel>
	<title>SitePen Blog &#187; nodejs</title>
	<atom:link href="http://www.sitepen.com/blog/tag/nodejs/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sitepen.com/blog</link>
	<description>SitePen Services and notes about Dojo, Persevere, CometD, JavaScript, and the Web</description>
	<lastBuildDate>Wed, 15 May 2013 22:02:34 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5</generator>
		<item>
		<title>Now Supporting all Major Toolkits!</title>
		<link>http://www.sitepen.com/blog/2012/07/19/now-supporting-all-major-toolkits/</link>
		<comments>http://www.sitepen.com/blog/2012/07/19/now-supporting-all-major-toolkits/#comments</comments>
		<pubDate>Thu, 19 Jul 2012 15:20:25 +0000</pubDate>
		<dc:creator>Dylan Schiemann</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[AMD]]></category>
		<category><![CDATA[Cometd]]></category>
		<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[dgrid]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[Support]]></category>
		<category><![CDATA[backbone]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[support]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/?p=4951</guid>
		<description><![CDATA[<p>We have been providing JavaScript and Dojo support to freelancers, start-ups and Fortune 500 companies for nearly a decade. As we intently watch enterprise organizations everywhere begin to roll out AMD (read about why AMD matters) and the associated code improvements, we are thrilled with the industry&#8217;s direction toward toolkit interoperability! Why? Because! Our masterful [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>We have been providing JavaScript and Dojo support to freelancers, start-ups and Fortune 500 companies for nearly a decade.  As we intently watch enterprise organizations everywhere begin to roll out AMD <a href="http://www.sitepen.com/blog/2012/07/10/amd-for-the-business-side/">(read about why AMD matters)</a> and the associated code improvements, we are thrilled with the industry&#8217;s direction toward toolkit interoperability!  Why?  Because! Our masterful engineering team, consisting of influential members of various open source communities, positions SitePen perfectly to offer full-on, front-end web development support to the world! </p>
<p>Getting right to the point, (<a href="http://www.prnewswire.com/news-releases/sitepen-expands-service-offering-to-popular-javascript-toolkits-163018596.html">The Official Point!</a>), we are pleased to announce the expansion of SitePen Support to officially include more than fifteen popular open-source JavaScript toolkits! </p>
<p><strong>Now supporting the following JavaScript toolkits:</strong></p>
<table style="width:600px;">
<tr>
<td>
<ul>
<li>Dojo</li>
<li>Persevere packages</li>
<li>dgrid</li>
<li>Curl.js</li>
<li>CometD</li>
<li>Twine</li>
</ul>
</td>
<td>
<ul>
<li>jQuery</li>
<li>Backbone</li>
<li>underscore</li>
<li>RequireJS</li>
<li>PhoneGap/Cordova</li>
<li>MooTools</li>
</ul>
</td>
<td>
<ul>
<li>jQueryUI</li>
<li>Wire</li>
<li>Socket.IO</li>
<li>Express</li>
</ul>
</td>
</tr>
</table>
<p>In addition to toolkits, we will continue to support your custom JavaScript source code, as well as key underlying technologies and formats, including JSON, HTML5, WebSockets, SVG/Canvas, Mobile Web, Server-Side JavaScript, AMD, Node.js and many more.</p>
<p>Our expertise with Dojo and advanced JavaScript is relevant for a wide-range of desktop and mobile web application projects and our approach to SitePen Support has always been flexible with the priority being to improve our customers&#8217; web apps.  We strive to support our customers in every way possible and we continue to be Dojo experts. In addition, we&#8217;re now committed to providing your organization with the front-end development expertise that will optimize your application regardless of which toolkits and technologies your company is comfortable using.  You have our word!</p>
<p>Learn More About <a href="http://www.sitepen.com/support/index.html">SitePen Support</a> or <a href="http://www.sitepen.com/site/contact.html">Contact Us </a>to get started today!</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2012/07/19/now-supporting-all-major-toolkits/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>RequireJS/AMD Module Forms</title>
		<link>http://www.sitepen.com/blog/2010/11/04/requirejsamd-module-forms/</link>
		<comments>http://www.sitepen.com/blog/2010/11/04/requirejsamd-module-forms/#comments</comments>
		<pubDate>Thu, 04 Nov 2010 07:02:31 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[nodules]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[RequireJS]]></category>
		<category><![CDATA[transporter]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/?p=1987</guid>
		<description><![CDATA[<p>The CommonJS AMD proposal defines an elegant, simple API for declaring modules that can be used with synchronous or asynchronous script-tag based loading in the browser. RequireJS already implements this API, and Dojo will soon have full support as well. The API for defining modules is as simple as: define(, , ); This simple API [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>The CommonJS <a href="http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition">AMD proposal</a> defines an elegant, simple API for declaring modules that can be used with synchronous or asynchronous script-tag based loading in the browser. <a href="http://requirejs.org/">RequireJS</a> already implements this API, and <a href="http://dojotoolkit.org/">Dojo</a> will soon have full support as well. The API for defining modules is as simple as:</p>
<pre lang="javascript">
define(<module-name?>, <array-of-dependencies?>, <module-factory-or-object>);
</pre>
<p>This simple API can be used in a variety of different ways for different situations.</p>
<p><span id="more-1987"></span></p>
<h2>Anonymous Modules</h2>
<p>The recommended general purpose way of writing your own modules with this API is to omit the first argument, and just include the dependencies and the module factory. A simple module can be written:</p>
<pre lang="javascript">
define(["math"], function(math){
  return {
    addTen: function(x){
      return math.add(x, 10);
    }
  };
});
</pre>
<p>The first argument defines the set of dependencies (as module names) for this module. The modules exported values are passed in as the arguments to the callback function once the dependent modules have been loaded.</p>
<p>When the module name (of the current module) is omitted, as in the example, the module is anonymous. This is a powerful way to write modules since the module source code is not coupled to any identity. The module can easily be moved to a different location without requiring any code change. This technique follows basic <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Don%27t_repeat_yourself">DRY</a> principles, avoiding duplicate information about the identity of a module (the filename/path information does not need to be duplicated in code). This not only makes writing modules easier, but gives greater flexibility in module reuse.</p>
<p>Let&#8217;s look at how we load this module from a web page. We will assume the above module was put in a file called adder.js. Using RequireJS, we can load our module like this:</p>
<pre lang="html4">
<script src="require.js"></script>
<script>
require(["adder"], function(adder){
  // ready to use adder
});
</script>
</pre>
<p>Once the initial entry require is called, RequireJS takes care of downloading all the dependencies of adder. We can use this same require call to load any of the module forms described below as well.</p>
<p>There are some rules for anonymous module usage. There may only be one anonymous module per file, and the anonymous modules must be loaded through the loader (you can just include a &lt;script&gt; pointing to the module).</p>
<h2>Data Wrapping: The New JSON-P</h2>
<p>Modules that only provide data, or dependency free methods can simply provide an object as the only argument to define():</p>
<pre lang="javascript">
define({
  name:"some data"
});
</pre>
<p>This is similar to JSON-P, but actually provides a significant advantage over JSON-P since it can be written in a static file without requiring the dynamic callback generation. This makes this format cacheable and CDN friendly.</p>
<h2>CommonJS module wrapping</h2>
<p>CommonJS modules can easily be used with the asynchronous module loader by simply wrapping them with a define call. Here you can also omit the first and second parameter, and the module&#8217;s require calls will be scanned to determine the appropriate dependencies. For example:</p>
<pre lang="javascript">
define(function(require, exports){
// standard CommonJS module:
  var math = require("math");
  exports.addTen = function(x){
    return math.add(x, 10);
  };
});
</pre>
<p>It is important to note that this form requires the module loader to inspect the function for require calls. The require calls must be written in the form of <code>require("...")</code> in order for this analysis to work properly. There are also certain browsers where this will simply not work (some versions of Opera mobile and PS3). This may not be an issue at all if your modules will be run through a build process before deployment. However, you can also wrap CommonJS modules, and manually specify dependencies. The specification allows us to also reference CommonJS variables, so we can include the standard &#8220;require&#8221; and &#8220;exports&#8221; variables:</p>
<pre lang="javascript">
define(["require", "exports", "math"], function(require, exports){
// standard CommonJS module:
  var math = require("math");
  exports.addTen = function(x){
    return math.add(x, 10);
  };
});
</pre>
<h2>Full Module Definitions</h2>
<p>A full module definition includes the module name, dependencies, and the factory. This form has the advantage that the module can be included in another file or it can be directly loaded with a script tag. This is the format generated by the build tools so that multiple dependencies can be combined in a single file. An example of this format:</p>
<pre lang="javascript">
define("adder", ["math"], function(math){
  return {
    addTen: function(x){
      return math.add(x, 10);
    }
  };
});
</pre>
<p>Finally, the last permutation of these arguments is to include the module id, but omit the dependencies list. This can be used when you want to indicate the module id (for use with direct script tag), but there are no dependencies. With no dependency array, the arguments default to &#8220;require&#8221;, &#8220;exports&#8221;, and &#8220;module&#8221;. We could alternately create our adder module: </p>
<pre lang="javascript">
define("adder", function(require, exports){
  exports.addTen = function(x){
      return x + 10;
  };
});
</pre>
<p>Again all these module forms can be handled by RequireJS and can be loaded by listing them as dependencies in another module or directly loading them with a require() call.</p>
<p>This simple API provides flexibility to declare modules for a variety of situations, from anonymous modules that can easily be moved around, to &#8220;built&#8221; modules that are ready to be used from script tags. This API is implemented by RequireJS and Dojo, as well <a href="http://github.com/kriszyp/nodules">Nodules</a> for Node. You can also use <a href="http://github.com/kriszyp/transporter">Transporter</a> to do on-the-fly concatenation of AMD modules and automatic wrapping of CommonJS modules that are delivered in this format.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2010/11/04/requirejsamd-module-forms/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Patr: Promise-based Asynchronous Test Runner</title>
		<link>http://www.sitepen.com/blog/2010/09/21/patr-promise-based-asynchronous-test-runner/</link>
		<comments>http://www.sitepen.com/blog/2010/09/21/patr-promise-based-asynchronous-test-runner/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 07:01:30 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[narwhal]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/?p=1719</guid>
		<description><![CDATA[<p>Patr (Promise-based Asynchronous Test Runner) is a simple lightweight cross-platform test runner for promised-based applications. Patr executes tests by simply executing functions of an object and is intended to be used in combination with the &#8220;assert&#8221; module (which is available on NodeJS and Narwhal), so tests can be as simple as: var assert = require("assert"); [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://github.com/kriszyp/patr">Patr</a> (Promise-based Asynchronous Test Runner) is a simple lightweight cross-platform test runner for promised-based applications. Patr executes tests by simply executing functions of an object and is intended to be used in combination with the &#8220;assert&#8221; module (which is available on NodeJS and Narwhal), so tests can be as simple as:</p>
<pre lang="javascript">
var assert = require("assert");
tests = {
  testSomething: function(){
    assert.eq(3, 3);
  }
}
require("patr/runner").run(tests);
</pre>
<p><span id="more-1719"></span></p>
<p>Creating asynchronous tests is easy as well. Inspired by <a href="http://dojocampus.org/content/2009/05/07/a-simple-doh-test-fixture/">Dojo&#8217;s DOH</a> test runner for returning a promise from tests, we don&#8217;t need a new interface to indicate when an asynchronous test is completed. The promise&#8217;s completion or failure indicates the completion or failure of the test. This allows us to elegantly pipe asynchronous operations through to the test runner. Here is an example of an asynchronous test:</p>
<pre lang="javascript">
var fs = require("promised-io/fs");
require("patr/runner").run({
    testFile: function(){
        return fs.readFile("my-file.txt")  // asynchronously read the file
            .then(function(contents){ // next action in promise flow
                // make an assertion
                assert(contents.toString(), "expected contents of the file");
            });
    };
});
</pre>
<p>Now this test will asynchronously read the file, make an assertion, and when completed the returned promise will notify the test runner that the test is complete (or failed) and continue on to the next test.</p>
<p>Tests can be organized into groups by simply creating nested objects: </p>
<pre lang="javascript">
require("patr/runner").run({
    testGroupA: {
      testFile: function(){
        ..
      },
      ..
    },
    testGroupB: {
      testAnother: function(){
      ....
    }
});
</pre>
<p>(Also, remember all your test properties must start with &#8220;test&#8221;.)</p>
<p>The recommended approach for creating test modules is to use the exports object to hold tests. This makes it very easy to run a test module directly or as part of a group. For example:</p>
<pre lang="javascript">
//something.js:
var assert = require("assert");
exports.testSomething: function(){
    assert.eq(3, 3);
};

if (require.main === module)
    require("patr/runner").run(exports);
</pre>
<p>Now we can directly run this module to run these tests. We can also include this module in another set of tests:</p>
<pre lang="javascript">
//all-tests.js:
exports.testSomething = require("./something");
exports.testAnotherGroupOf = require("./more-tests");
if(require.main === module){
    require("patr/runner").run(exports);
}
</pre>
<p>We now have each of these tests within a sub group for easy execution of groups of tests at any level in the hierarchy (all the tests or individual groups).</p>
<h3>Performance Testing</h3>
<p>Patr is also great for performance testing. You can set an iterations flag with in a test group or from the command line to run through the test a specified number of iterations and give performance statistics.</p>
<h2>Summary</h2>
<p>Patr is a lightweight test runner that makes it extremely simple to create test suites and hierarchies with idiomatic JavaScript and asynchronous tests with promises.  Patr is built on <a href="http://www.sitepen.com/blog/2010/09/20/promised-io/">Promised-IO</a>, so it is ready for cross-platform execution, including Node, Narwhal, and within the web browser.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2010/09/21/patr-promise-based-asynchronous-test-runner/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Server-Side JavaScript, Pintura, and Persevere 2.0]]></series:name>
	</item>
		<item>
		<title>Promised-IO</title>
		<link>http://www.sitepen.com/blog/2010/09/20/promised-io/</link>
		<comments>http://www.sitepen.com/blog/2010/09/20/promised-io/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 07:24:22 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[and Persevere 2.0]]></category>
		<category><![CDATA[narwhal]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[pintura]]></category>
		<category><![CDATA[Server-Side JavaScript]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/?p=1596</guid>
		<description><![CDATA[<p>Promises are a well-established mechanism for modeling future or asynchronous actions. Promises allow asynchronicity while maintaining the core programming principles of composability and encapsulation. Writing asynchronous code in JavaScript can often be a confusing exercise due to the extensive need for callbacks, but promises help to define composable units of asynchronicity to encapsulate actions and [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>Promises are a <a href="http://en.wikipedia.org/wiki/Futures_and_promises">well-established mechanism</a> for modeling future or asynchronous actions. Promises allow asynchronicity while maintaining the core programming principles of composability and encapsulation. Writing asynchronous code in JavaScript can often be a confusing exercise due to the extensive need for callbacks, but promises help to define composable units of asynchronicity to encapsulate actions and reliably separate caller and callee&#8217;s concerns.</p>
<h2>Promised-IO</h2>
<p><a href="http://github.com/kriszyp/promised-io">Promised-IO</a> utilizes promises as an abstraction for I/O operations on top of <a href="http://nodejs.org/">Node</a>, <a href="http://narwhaljs.org/">Narwhal</a>/Rhino, and the browser (where possible). This serves two purposes. First, this package provides the benefits of promise usage: clean separation of concerns and proper encapsulation of eventual values. Second, Promised-IO provides a consistent normalized interface for I/O that will work on multiple platforms without sacrificing any of the advantages of asynchronous I/O, making it easy to build modules that can be used by developers on many platforms.</p>
<p><span id="more-1596"></span></p>
<h2>Usage Principles</h2>
<p>One of the characteristics of a good developer is understanding when to apply different abstractions (rather than trying to force a single approach on every situation). Asynchronous code is often more complicated than synchronous code, but can provide big benefits to performance and scalability. In the application of asynchronous I/O there are several different approaches, and each has an appropriate usage.</p>
<h3>Synchronous (don&#8217;t use asynchronous)</h3>
<p>Of course synchronous calls are usually simpler (no addition of callbacks), and for parts of applications that aren&#8217;t &#8220;hot&#8221; parts of concurrent code paths, and aren&#8217;t performance sensitive, this can be the smart choice. For the startup process for servers, long period scheduled tasks, and infrequently executed code, the simplicity and code manageability of using synchronous code can outweigh any performance benefit of asynchronous code.</p>
<p>(There are actually times when synchronous performs better than asynchronous. Asynchronous operations have the additional overhead of handling the low-level callback, then adding the JavaScript callback to the event queue, and finally pulling events of the event loop. Synchronous operations do not have this overhead. For example, for file operations that hit the OS cache, the synchronous operation can often be about twice as fast (half as much CPU time) as the asynchronous counterpart. Of course this is only advantageous for cached data.</p>
<p>Synchronous operations can have a much larger performance advantage when there isn&#8217;t to-the-core support for asynchronicity. Fortunately, most of the I/O operations in NodeJS leverage libeio and low level async Posix operations for good performance, but for actions that are natively synchronous, some libraries use libeio&#8217;s <code>eio_custom</code> function to make it asynchronous. This function can be very expensive and should only be used for operations that will take a significant amount of time (more than about 0.1ms). I have observed synchronous operations executing hundreds of times faster than the asynchronous counterparts when <code>eio_custom</code> is used.</p>
<p>All this being said, most of the time asynchronous is a good choice for code that needs to scale, but it is important to know when and when not to use it.)</p>
<h3>Event Registration</h3>
<p>This is the typical way that one is notified of events in the browser and in NodeJS. You register for an event and are notified of the event anytime after the registration (no notification of past events). Event registration is the most generic and low-level asynchronous API. NodeJS uses this model exclusively because it is a low-level platform for I/O. For some situations (see below) it is appropriate to build abstractions on top of this API. However, event registration is the right choice if multiple events may take place and you only want future events.</p>
<h3>Promises</h3>
<p>An asynchronous abstraction designed specifically to model an action that has a single eventual completion (successful or failing). Promises act much like a value (returned from the result of a function call or computation), except that the result is asynchronous, and may or may not be immediately available. Promises are more specific than event registration, providing encapsulation (that can easily be passed around) of an eventual value and decoupling the receiver from the timing of the underlying events that fulfill the action (whether they be past or future). Promises are the right choice for asynchronous actions that have a single point of eventual completion.</p>
<h3>Streams</h3>
<p>Streams are an asynchronous abstraction for the progressive flow of sequential data. Streams are important for allowing a sender to feed data to a receiver without requiring large scale buffering at either end. Promised-IO implements streams with &#8220;lazy arrays&#8221;, an array-like interface that follows the standard API of JavaScript Arrays. This greatly improves the modularity of streams since they can be used with code that expects standard arrays. Lazy arrays are indeed lazy, following the functional programming principle of lazy evaluation as well. Iterative methods including map, some, filter, and every are purely functional and only iterate through the stream as needed, avoiding any unnecessary buffering or computations. Promised-IO&#8217;s streams also utilize promises to signal the eventual completion of a stream (for the end of a file or end of a HTTP response, for example), for consistency. For situations where you want to model sequential data, streams/lazy arrays are appropriate.</p>
<h2>Promised-IO Modules</h2>
<p>There are several key modules available in Promised-IO for access to promise-based I/O.</p>
<h3>fs</h3>
<p>The &#8220;fs&#8221; module implements key parts of the <a href="http://wiki.commonjs.org/wiki/Filesystem/A">CommonJS file system API</a> (the entire API will eventually be supported). It also provides Node&#8217;s file system API where each asynchronous function returns a promise rather than taking callback parameters (fortunately these two APIs can easily coexist). This gives you access to a number of the convenience functions from CommonJS&#8217;s API (like <code>makeTree()</code>) and gives normalizable access to asynchronous functions. This module is obviously not available for browser usage. Here is an example of using <code>readFile()</code> (an asynchronous function from Node&#8217;s API):</p>
<pre lang="javascript">
var fs = require("promised-io/fs");
return fs.readFile("my-file.txt").then(function(contents){
   // once it is loaded, we can do something with the contents
});
</pre>
<p>One of the most important functions in the &#8220;fs&#8221; module is the <code>open()</code> function which can be used in several powerful ways. The open function returns a file descriptor for use with Node&#8217;s functions that take a descriptor (the read, write, and close functions). While the open function opens the file asynchronously, the returned object can be directly passed to read, write, and close functions (they will execute once the file is open):</p>
<pre lang="javascript">
var fs = require("promised-io/fs");
var myFile = fs.open("my-file.txt", "r");
fs.read(myFile, buffer, offset, length, position).then(function(){
  // buffer should now be filled
});
</pre>
<p>The returned object is also a promise for the completion of the open operation:</p>
<pre lang="javascript">
var when = require("promised-io/promise").when;
var myFile = when(fs.open("my-file.txt", "r"), onSuccess, onFailure);
</pre>
<p>The object returned from open also has methods (based on asynchronous versions of the CommonJS filesystem API) for writing and closing:</p>
<pre lang="javascript">
var myFile = fs.open("my-file.txt", "a");
myFile.write("some data").then(myFile.close);
</pre>
<p>And finally, the returned file object can be treated like a JavaScript array for streamed reading (lazy arrays):</p>
<pre lang="javascript">
var myFile = fs.open("my-file.txt", "r");
myFile.forEach(function(block){
    // called for each block of data
}).then(myFile.close); // The forEach returns promise for the completion of the reading
</pre>
<p>The <code>some()</code> JavaScript array method can be particularly useful if you might not need to traverse the whole file:</p>
<pre lang="javascript">
var myFile = fs.open("my-file.txt", "r");
myFile.some(function(block){
    // if we are searching for something, we can exit be returning true at any time
});
</pre>
<p>One other useful aspect of using these lazy arrays is that we can return the file object directly as the body of JSGI responses and it will automatically be piped to the client.</p>
<pre lang="javascript">
function SomeJSGIApp(request){
  return {
    status: 200,
    headers: {"content-type":"text/plain"},
    body: fs.open("my-file.txt", "r");
  };
}
</pre>
<h3>http-client</h3>
<p>An HTTP client that follows the JSGI API. Originally developed for handling incoming HTTP requests (for web servers) and returning responses, http-client effectively uses the JSGI API for the reverse situation, allowing for the construction of JSGI requests and receiving JSGI responses. This module allows for some extra convenience properties and defaults to make it easy to create a request. You can simply provide a &#8220;url&#8221; property to indicate the target, and then all other properties are optional. For example:</p>
<pre lang="javascript">
var request = require("promised-io/http-client").request;
request({
  url:"http://somesite.com/data",
  method: "GET", // optional
  headers: {} // also optional
}).then(function(response){
  response.status -> http status code
  response.headers -> http response headers
  response.body -> A lazy array stream representing the body of the response
});
</pre>
<p>This module can be used on the server and browser.</p>
<h3>delay</h3>
<p>This module provides promise-based scheduling and timing similar to that of <code>setTimeout</code> and <code>setInterval</code>, but utilizing promises. The two exported functions are <code>delay(ms)</code> and <code>schedule(ms)</code>. The <code>delay()</code> function returns a promise that is fulfilled after the specified amount of time. The <code>schedule()</code> function returns a lazy array that iterates periodically by the given amount of time. For example:</p>
<pre lang="javascript">
var delay = require("promised-io/delay").delay;
delay(2000).then(function(){
  // and two seconds later this executes
});
</pre>
<p>This module can also can be used on the server and browser.</p>
<h3>process</h3>
<p>This module implements the CommonJS &#8220;system&#8221; module API and provides access to a <code>print()</code> function and process arguments.</p>
<h2>Summary</h2>
<p>Promised-IO provides a robust, cross-platform I/O system based on the proven design principles of promises for efficient, portable, asynchronous JavaScript.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2010/09/20/promised-io/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<series:name><![CDATA[Server-Side JavaScript, Pintura, and Persevere 2.0]]></series:name>
	</item>
		<item>
		<title>Real-time Comet Applications on Node with Tunguska</title>
		<link>http://www.sitepen.com/blog/2010/07/19/real-time-comet-applications-on-node-with-tunguska/</link>
		<comments>http://www.sitepen.com/blog/2010/07/19/real-time-comet-applications-on-node-with-tunguska/#comments</comments>
		<pubDate>Mon, 19 Jul 2010 11:34:39 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[comet]]></category>
		<category><![CDATA[jack]]></category>
		<category><![CDATA[narwhal]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[tunguska]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/?p=1289</guid>
		<description><![CDATA[<p>Node is a server-side JavaScript platform that is known for being well suited for Comet-style applications that utilize long-lived connections to allow applications to send messages from the server to the browser asynchronously. In fact, the beginning of the front page of nodejs.org starts out with an example of a web application that delays for [...]</p><p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></description>
				<content:encoded><![CDATA[<p>Node is a server-side JavaScript platform that is known for being well suited for Comet-style applications that utilize long-lived connections to allow applications to send messages from the server to the browser asynchronously. In fact, the beginning of the front page of <a href="http://nodejs.org/">nodejs.org</a> starts out with an example of a web application that delays for a couple seconds before sending a response without any type of blocking; the code is asynchronous and efficient.</p>
<p>However, building a real-life real-time application involves more than just a platform that gives you asynchronous communication, there are a number of other important techniques to understand. We will look at these techniques and introduce <a href="http://github.com/kriszyp/tunguska">project Tunguska</a> that provides some helpful tools to assist in building applications. While a number of Comet projects out there attempt to provide a black box solution to Comet, Tunguska recognizes that most real-time applications involve deep integration into the application and its security, messaging, and data structures. Consequently Tunguska is a set of tools for building real-time applications rather than a closed black box that can&#8217;t easily be integrated with. Let&#8217;s look at some of these tools.</p>
<p><span id="more-1289"></span></p>
<h2>Connections/Message Queues</h2>
<p>The most fundamental concept of building real-time applications is providing the ability to asynchronously deliver messages that occur at any time, to the browser. With new technologies like WebSockets, this is relatively straightforward. You can create a connection to the server and then the server is free to send messages to the browser at any time. However, WebSocket capable browsers are still nowhere near widely distributed enough to rely on (and the WebSocket protocol is still in development, a recent revision rendered the first version incompatible, and more changes are likely to occur due to <a href="http://blogs.webtide.com/gregw/entry/websocket_chat">the immature design</a>).</p>
<p>The most widely used technique for Comet is known as <a href="http://cometdaily.com/2007/11/16/more-on-long-polling/">long-polling</a>. With long-polling an HTTP request is made to the server which waits until it has a message to send. The message is sent to the browser as the response, and upon receiving the response the client makes another request to the server. However, the complication of this strategy is that the server does not have a continuous, uninterrupted stream to send messages to the client. There is a time gap between each message/response being sent from the server and the next long-polling request from the browser reaching the server.</p>
<p>However, we obviously don&#8217;t want to miss the messages that were generated during these time gaps. Therefore we need to provide a virtual connection by creating a queue where messages can be stored during these time gaps between the response and request. These message queues allow us to effectively emulate a continuous connection, whereby messages can be delivered at any time to the virtual connection. If an active long-polling response is waiting the server can immediately deliver the message, otherwise the message can go into a queue to wait for the next request from the browser to send a message.</p>
<p>Tunguska provides this type of virtual connection or message queueing with its <strong>queue</strong> module, and message queues can be accessed with the <code>getQueue(clientId)</code> function. Queues are identified by a client id. This function will return a queue object for a given client id passed as the argument. The queue object extends JavaScript&#8217;s Array (providing array functions for accessing queued events), provides a send() for delivering events, a <code>message</code> event, and a <code>close</code> event (accessible via addListener() or observe()) as the key functionality.</p>
<pre lang="javascript">
var getQueue = require("tunguska/queue").getQueue;
// get the virtual connection for this request
var queue = getQueue("32a3fa5");
queue.addListener("message", function(message){
   // this will be fired by the send call below
});
// put a message in the queue identified by this request.
queue.send("Hello");
</pre>
<p>The queue module does more than just provide a queue object, it also handles timeouts of non-active connections so as to avoid unbounded memory usage, or memory leakage due to accumulation of unused connection objects. It also handles distributed message queues (across multiple processes/machines) as we will see later.</p>
<p>Tunguska also provides a &#8220;jsgi/comet&#8221; module for the higher HTTP level interaction. A message queue, which acts as a virtual connection to a client, can be obtained from a request object (<a href="http://www.sitepen.com/blog/2010/01/19/commonjsjsgi-the-emerging-javascript-application-server-platform/">JSGI</a> or Node) passed into its getClientConnection(request) function. This function will look for the &#8220;Client-Id&#8221; header to use as the client id for connection identification. If a connection exists with the given client id, it will be returned, otherwise a new connection object/message queue will be created and returned.</p>
<p>The connection object is based on the WebSocket API. Sending a message to the client is as simple as calling the <code>send(message)</code> function. The connection object is also an array. New messages are pushed onto the array and any listeners are notified.</p>
<pre lang="javascript">
var comet = require("tunguska/jsgi/comet");
// get the virtual connection for this request
var connection = comet.getClientConnection(request);
// put a message in the queue identified by this request.
connection.send({from:"Kris", body:"hi"});
</pre>
<h2>Long-polling handler</h2>
<p>A long-polling request handler can now listen for messages by initially checking for any messages in the queue for instant delivery and if no messages are ready to deliver to the client, it can listen for <code>message</code> events to trigger delivery. A JSGI middleware appliance is provided with the <code>jsgi/comet</code> module to do just that. We can easily insert this appliance into a middleware stack:</p>
<pre lang="javascript">
cometApp = comet.Broadcaster(nextApp);
</pre>
<p>The optional <code>nextApp</code> parameter can be used to define another middleware appliance that can handle any needed subscriptions and/or other wiring to event triggers to relay messages to the virtual connection object. For example:</p>
<pre lang="javascript">
cometApp = comet.Broadcaster(function(request){
  var connection = comet.getClientConnection(request);
  // user function for registering a user to get user events
  listenForMessagesForUser(
    request.remoteUser, // if we have an authenticated user
    function(message){
      // this can be called when a message needs to be sent to the user
      connection.send(JSON.stringify(message));
    });
});
</pre>
<h2>Message Routing</h2>
<p>One of the key aspects of real-time applications is message routing. When an action or event occurs, the message needs to be routed to the appropriate party. In a chat application, when someone sends a chat message, we need to route and send the message to the recipient. A frequently used mechanism for this is a <a href="http://cometdaily.com/2007/10/26/pubsub-and-topics/">publish/subscribe</a> hub. A hub consists of &#8220;channels&#8221; or &#8220;topics&#8221;, and messages can be published to channels on the hub, and subscribers can listen for messages on these channels. This paradigm decouples sending messages and listening for messages. Message publishers do not need to be concerned with who is subscribed and subscribers do not need to be concerned with the details of who and how messages are published.</p>
<h3>Pub/Sub Hub</h3>
<p>There are certainly alternate approaches to topic-based pub/sub hubs for message routing. Rather than subscribing to a particular named topic, subscribers could provide message filter functions that filter through all messages for appropriate messages of interests. However, this approach does not scale well. As more diverse topics and messages are being sent through a system, a filter often begins to process more non-matching functions and performance suffers. On the other hand, pub/sub hubs scale well. A normal hash-table based hub maintains constant time message routing regardless of the number of topics. This highly scalable approach fits well with the Node philosophy of making it easy to do the right thing (in terms of scalability) and hard to do the wrong thing. By using the named topics, it is very easy to create highly scalable message routing systems.</p>
<p>Creating a very simple pub/sub hub in JavaScript is actually extremely easy. JavaScript&#8217;s hash-based objects make a great core of a hub. You can simply create properties on a &#8220;hub&#8221; object with names that correspond to topics and values that are arrays of listeners. However, more interesting features than simple topic based message routing are often desirable. Tunguska provides a &#8220;hub&#8221; module with a rich set of publish/subscribe capabilities.</p>
<p>The Tunguska hub supports globbing or wildcard-based subscriptions for listening for a set of topics (rather than only being able to register for a single topic at once).</p>
<pre lang="javascript">
var hub = require("tunguska/hub");
hub.subscribe("foo/*", function(event){
  // will be fired by the publish below
});
hub.publish("foo/bar", "hi");
</pre>
<p>It allows for &#8220;typed&#8221; messages to allow for filtering/routing by type as well as topic (essentially allowing a hub to have a two-dimensional namespace). This hub uses &#8220;typed&#8221; messages for broadcasting subscription events, sending out a &#8220;monitored&#8221; event when a topic starts to have subscribers or ceases to have any subscribers.</p>
<pre lang="javascript">
hub.subscribe("foo/*", "monitored", function(event){
  // will be fired by the subscribe action below
});
hub.subscribe("foo/bar", function(){...});
</pre>
<p>Tunguska&#8217;s hub also supports echo suppression, allowing subscribers and publishers to indicate a client identifier so that published messages do not echo back to the client. These components are important for various applications and are essential for Tunguska&#8217;s distributed messaging system, where hubs can be linked together in a cluster.</p>
<pre lang="javascript">
var clientHub = hub.fromClient("42a92f3");
clientHub.subscribe("foo/bar", function(event){
  // will be *not* fired by the publish below
});
clientHub.publish("foo/bar", "for everyone else");</pre>
<h2>Clustering</h2>
<p>Building Comet applications on a single Node process (single threaded) can be deceptively easy. But, scaling Comet applications to multiple concurrent processes is where the bulk of complexity usually arises. Inter-process communication, non-deterministic request delegation, message framing, and true parallel concurrency can combine to create a formidable challenge compared to the rather simple single-process application development. Fortunately, Tunguska provides clustering support for linking distributed pub/sub hubs together, allowing applications to maintain a simple hub-based message routing system without having to worry about the inter-process interaction complexity.</p>
<p>The core component for building Tunguska clusters is the &#8220;connector&#8221; module. The &#8220;connector&#8221; module provides a means of using connections to other processes to coherently link hubs together. These connectors will listen for subscriptions and send subscription requests to other processes, allowing for collection of all messages for a given topic from all processes. A connector can be created by passing it a connection object (that follows the WebSocket API), and the connector will handle the messaging concerns for propagating subscriptions and message routing.</p>
<p><a href="http://www.sitepen.com/blog/wp-content/uploads/2010/06/Tunguska.png"><img class="size-full wp-image-1334" title="Tunguska" src="http://www.sitepen.com/blog/wp-content/uploads/2010/06/Tunguska.png" alt="Tunguska" /></a><br />
WebSocket connection objects can easily be utilized with actual WebSocket TCP connections to other machines. For inter-process communication on a single machine, <a href="http://www.sitepen.com/blog/2010/07/14/multi-node-concurrent-nodejs-http-server/">multi-node</a> provides easy access to a WebSocket-based connection to the sibling HTTP serving processes. Connecting a set of processes with Tunguska with multi-node is very simple:</p>
<pre lang="javascript">
var multiNode = require("multi-node/multi-node"),
    Connector = require("tunguska/connector").Connector;
// start the multiple processes
var nodes = multiNode.listen({port: 80, nodes: 4}, serverObject);

// add a listener for each connection to the other sibling process
nodes.addListener("node", function(stream){
  // create a new connector using the framed WS stream
  Connector("local-workers", multiNode.frameStream(stream));
});
</pre>
<h2>Jack/JSGI Support on Other Platforms</h2>
<p>In addition to Node, Tunguska can run on any other JSGI-compliant server including <a href="http://github.com/kriszyp/jack">Jack 0.3</a>, and should be easily adaptable to RingoJS as well. The main complication with different platforms is creating connectors with alternate forms of cross-process or cross-thread communication. Jack 0.3 utilizes threads for concurrency that implement the WebWorker API and includes special events for connecting to other workers for fully connected workers (achieving fully connected workers, where every worker can talk to every other worker is problematic with the standard worker API since it relies on the less ubiquitous SharedWorker API and requires a high level of name coordination). To use the Tunguska connectors with Jack, you utilize the &#8220;jack-connector&#8221; module, which provides &#8220;worker&#8221; events that return connection streams that can be used with the connectors:</p>
<pre lang="javascript">
require("tunguska/jack-connector").addListener("worker", function(connection){
  Connector("local-workers", connection);
});
</pre>
<p>Tunguska provides a solid set of tools for building scalable, non-blocking, real-time applications with the flexibility and modularity needed to integrate with essential application logic including custom serialization, authorization/access-control, and middleware routing to truly leverage the asynchronous I/O capabilities of Node. Next up, we will look at how Tunguska, which is a sub-project of Persevere, fits into the greater Persevere ecosystem for data integration with real-time data views, and RESTful content negotiation.</p>
<p>SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications.  <a href="http://sitepen.com/services/workshops/index.php">Sign up today!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2010/07/19/real-time-comet-applications-on-node-with-tunguska/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<series:name><![CDATA[Server-Side JavaScript, Pintura, and Persevere 2.0]]></series:name>
	</item>
	</channel>
</rss>
