<?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; node</title>
	<atom:link href="http://www.sitepen.com/blog/tag/node/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, 22 May 2013 22:36:10 +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>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>Introducing Pintura</title>
		<link>http://www.sitepen.com/blog/2010/01/22/introducing-pintura/</link>
		<comments>http://www.sitepen.com/blog/2010/01/22/introducing-pintura/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 09:43:40 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
				<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Persevere]]></category>
		<category><![CDATA[narwhal]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[Perse]]></category>
		<category><![CDATA[Persevere 2.0]]></category>
		<category><![CDATA[pintura]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[Server-Side JavaScript]]></category>
		<category><![CDATA[sofea]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/?p=898</guid>
		<description><![CDATA[<p>Pintura is a CommonJS/JSGI-compliant, server-side JavaScript-based framework for building rich Internet application with the REST architectural style, thin storage-oriented server design, and the consistency of end-to-end JavaScript. The Pintura framework forms the core of Persevere 2.0, and is the first framework built to run on multiple CommonJS platforms like node.js, Narwhal/Jack, and Flusspferd/Zest. It utilizes [...]</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/pintura">Pintura</a> is a <a href="http://commonjs.org/">CommonJS</a>/<a href="http://wiki.commonjs.org/wiki/JSGI/Level0/A">JSGI</a>-compliant, <a href="http://www.sitepen.com/blog/2010/01/19/commonjsjsgi-the-emerging-javascript-application-server-platform/">server-side JavaScript</a>-based framework for building rich Internet application with the <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">REST architectural style</a>, <a href="http://www.thinserverarchitecture.com/home">thin storage-oriented server design</a>, and <a href="http://mvalente.eu/2009/11/25/requirements-for-a-modern-web-development-framework/">the consistency of end-to-end JavaScript</a>. The Pintura framework forms the core of Persevere 2.0, and is the first framework built to run on multiple CommonJS platforms like <a href="http://nodejs.org/">node.js</a>, <a href="http://narwhaljs.org/">Narwhal/Jack</a>, and <a href="http://github.com/ashb/Zest">Flusspferd/Zest</a>. It utilizes a layered approach to application development that facilitates straightforward, modular web applications. </p>
<p>Pintura is <strong>not</strong> a traditional MVC web server framework, which often conflate presentation and interaction concerns across the client and server, but rather follows the <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_2">REST prescription</a> of maintaining simple storage and serialization oriented server also known as <a href="http://www.thinserverarchitecture.com/home">thin server architecture</a> or <a href="http://bittwiddler.wordpress.com/2008/05/04/sofea-is-beautiful/">SOFEA</a>. Pintura is designed <a href="http://www.sitepen.com/blog/2008/07/18/clientserver-model-on-the-web/">to cleanly separate the concerns of presentation and interaction on the client, and storage and model logic concerns on the server</a>. This design fits perfectly with comprehensive JavaScript frameworks like <a href="http://www.dojotoolkit.org/">Dojo</a>, <a href="http://www.generalinterface.org/">General Interface</a>, <a href="http://cappuccino.org/">Cappuccino</a>, YUI, and ExtJS that provide <a href="http://www.sitepen.com/blog/2009/08/28/mvc-in-the-browser/">client-side MVC</a>. In particular, Dojo has excellent support for <a href="http://docs.dojocampus.org/dojox/data/JsonRestStore">standards-based JSON REST interaction</a> that matches perfectly with this server-side framework.</p>
<p><span id="more-898"></span></p>
<p>The core design principles behind Pintura:</p>
<ul>
<li>Standards should be leveraged as much as possible to maximize interoperability with other projects, and facilitate freedom in composing web applications with the tools of choice. Pintura is based on <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC 2616 (HTTP/REST)</a>, <a href="http://tools.ietf.org/html/draft-zyp-json-schema-01">JSON Schema</a>, <a href="http://commonjs.org/">CommonJS</a>, JSGI, JSON-RPC, and other interoperable standards.</li>
<li>Presentation and data model logic should be properly separated such that clients can provide the user interface and servers can handle storage and application modeling logic. One should be able to develop multiple web clients for a given application data server.</li>
<li>Storage and data processing concerns should be separated, with <a href="http://www.vldb.org/conf/1997/P266.PDF">pluggable storage options that can easily be switched and combined</a> (such MongoDB plus a MySQL database).
<li>The best option choice between configuration and convention is neither. Integration between different entities without dependence upon certain programming patterns (convention or configuration) is optimal.</li>
<li>End-to-end consistency in data (JSON/JavaScript) handling provides the smoothest communication and interaction from client to server and back.</li>
<li>The most common cases, like standard CRUD style applications, should be very easy, while still making it possible to build more unusual or sophisticated applications.</li>
<li>A framework should be simple enough to read the source and easily extend or modify. Applications and frameworks should be organized into layers of functionality.</li>
<li>Utilize object-capability design for security to allow for flexible security design while protecting against confused deputy style vulnerabilities.</li>
<li>Full support throughout for <a href="http://en.wikipedia.org/wiki/Futures_and_promises">promises</a>, providing asynchronous functionality (used extensively by Node), while preserving clean encapsulated interfaces.</li>
</ul>
<h2>Improvements over Persevere 1.0</h2>
<p>The <a href="http://www.sitepen.com/blog/2010/01/19/commonjsjsgi-the-emerging-javascript-application-server-platform/">server-side JavaScript community has dramatically changed</a> since Persevere development started. There have been numerous exciting new server-side projects that have started like node.js, flusspferd, and Narwhal, utilizing the new generation of advanced high-performance JavaScript engines like <a href="http://code.google.com/p/v8/">V8</a>, <a href="https://wiki.mozilla.org/JavaScript:TraceMonkey">TraceMonkey</a>, and <a href="http://webkit.org/blog/189/announcing-squirrelfish/">JavaScriptCore</a>. Persevere&#8217;s main focus is on enabling efficient client server interaction and for well-structured web application development, and matching this functionality with powerful new platforms is a great fit.</p>
<p>In many ways, Pintura represents a simplification of Persevere. With an entirely JavaScript-based modular design, it is very easy to dig in and understand how it works, and the complicated Java-JavaScript bridges have been eliminated. The central request handling mechanism is composed of about 13 middleware modules that can easily be rearranged and used on their own. From the ground up, Pintura has a simple, minimal, direct approach to providing REST functionality.</p>
<p>There are numerous other improvements over Persevere 1.0. Pintura introduces a new security system that is based on the object capability model and is therefore much more flexible and powerful than the previous purely role-based mechanism. Much scientific research has pointed to the superiority of capability based design and how it avoids <a href="http://waterken.sourceforge.net/aclsdont/current.pdf">dangerous confused deputy issues</a>. Pintura utilizes &#8220;facets&#8221; (also known as proxies) to provide fine-grained access control to different stored objects. Each facet defines what actions are available for objects, with the flexibility of programmatic guard functions. In the end, security is essentially as simple as defining what facets are available for given users, and then defining what actions the facets allow.</p>
<p>Pintura also has moved to implementing the W3C proposed standard <a href="http://dev.w3.org/2006/webapi/WebSimpleDB/">Indexed Database APIs</a> object store interface for all data stores. Pintura is based around the <a href="http://github.com/kriszyp/perstore">Perstore persistence library</a>, which implements this simple API consisting of a REST-style interface. The stores expose <code>get</code>, <code>put</code>, and <code>delete</code> methods and is used at multiple levels in the framework for simplicity and consistency, including for facets, model classes, as well as lower level object stores. Furthermore, additional functionality is easily applied to stores with provided store wrappers that add support for inheritance, caching, replication, event notification and more. Not only that, but with the interface likely to be implemented in browsers soon, this API will provide true end-to-end consistency.</p>
<p>Pintura has also embraced a much more asynchronous oriented design. JavaScript in the browser uses shared-nothing event loop concurrency, and server side projects like Node and Narwhal are following suit. This not only improves client-server consistency, but there is compelling evidence that suggests that <a href="http://blog.webfaction.com/a-little-holiday-present">event-based design performs and scales much better</a> than traditional thread-based web servers. One of the major challenges of event-based systems is the encapsulation of functionality when dealing with callbacks, but promises are used extensively to greatly simplify working with asynchronous code.</p>
<p>Pintura also leverages the link relation definitions specified by the <a href="http://tools.ietf.org/html/draft-zyp-json-schema">JSON schema specification</a>  that is now a submitted Internet-Draft. Link relations superset the functionality of JSON referencing, and allow for much cleaner, more flexible referencing syntax. This further advances the flexibility of a loosely coupled hyperlink-driven REST architecture.</p>
<p>A core feature of Pintura is now content negotiation, following the REST architectural design of permitting multiple representations of a resource. Resources effectively are persistable JavaScript objects, and representations allows these objects to be serialized and deserialized in multiple formats. Pintura has excellent RFC 2616 conformance to content negotiation and provides a number of out of the box media type handlers, such JSON, JavaScript, CSV, and more, while making it easy to create new custom media type handlers.</p>
<p>Finally, Pintura uses greatly <a href="http://groups.google.com/group/json-query/browse_thread/thread/a7255cc47ef484be">simplified querying syntax</a>. It continues to provide powerful URL-based querying, but the format is simplified to work easily with standard HTML form URL-encoding, aligns with the <a href="http://tools.ietf.org/html/draft-nottingham-atompub-fiql">feed item query language</a>, and has an easy to use and extensible call syntax. Pintura provides a parsing mechanism to help developers implement their own custom query handlers.</p>
<h2>Role in Persevere 2.0</h2>
<p>Persevere 2.0 is not a single monolithic project, but will be a distribution of several web stack configurations composed of various components including Pintura, Perstore, and <a href="http://www.sitepen.com/blog/2009/01/14/store-explorer/">the store explorer</a>. Pintura and Perstore are still alpha stage software, but the Persevere 2.0 system is shaping up quickly.</p>
<p><img src="http://www.sitepen.com/blog/wp-content/uploads/2010/01/PinturaStack.png" alt="PinturaStack" title="PinturaStack" width="574" height="421" class="size-full wp-image-993" /></p>
<h2>The Next Web Stack</h2>
<p>Pintura brings together the cumulative advances of modern JavaScript and web architecture design patterns, including object capability based security, event-driven flow, immutable promises, JSON Schema, REST style, and thin server architecture. Coupled with the powerful new CommonJS platforms and remarkably fast JavaScript engines, this framework fulfills a critical role in the next generation web application stack, and is built to adapt to your JS platform of choice. The next article in this series will explore how to get started with Pintura.</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/01/22/introducing-pintura/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<series:name><![CDATA[Server-Side JavaScript, Pintura, and Persevere 2.0]]></series:name>
	</item>
	</channel>
</rss>
