deferred-fs
Provides a promise-based API for Node.js's filesystem API.
Requirements
Node.js
Installation
The easiest way is to install deferred-fs using npm, like this:
$ npm install deferred-fs
This will install deferred-fs into your project's node_modules
subdirectory. From a Node app, you can then load dfs by doing require('deferred-fs')
.
Deferred-fs API
The object returned by require('deferred-fs')
works exactly like Node's fs
library, except that its asynchronous methods return a promise object instead of accepting a callback argument.
Here's an example showing how to use writeFile
to asynchronously write a file and print a completion message when done:
var dfs = ;dfs;
In cases where a normal callback would return an "error" argument, the returned promise rejects, meaning the second callback is invoked:
var dfs = ;dfs;
The above program will output:
Yikes, an error occurred! Error: ENOENT, open 'c:\file_that_does_not_exist'
The real advantage of the promise approach comes from chaining promises together, allowing you to transform values returned by earlier callbacks and implement high-level error handling.
Promise API
The promise object returned by deferred-fs's asynchronous methods has the familiar "then" API:
then(onResolve, onReject)
Internally these promises are implemented using the Deferred library from Eclipse Orion. This means they're 100% compliant with the Promises/A+ specification, version 1.1.
Deferred API
deferred-fs also exports Orion's Deferred library, giving you access to a richer API than simple promises:
var Deferred = Deferred; var promises = ;Deferredallpromises;
Consult the Deferred JSDoc for details of the available API methods. In addition to Promises/A+ compliance, Orion's Deferred also implements some evolving APIs like progress and cancellation.