Provides a promise-based API for Node's filesystem APIs.
Provides a promise-based API for Node.js's filesystem API.
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
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 = require'dfs';dfswriteFile'hello.txt' 'Hello world!' 'utf8'thenconsole.log'File was written successfully.';;
In cases where a normal callback would return an "error" argument, the returned promise rejects, meaning the second callback is invoked:
var dfs = require'dfs';dfsreadFile'/file_that_does_not_exist'thennullconsole.log'Yikes, an error occurred! ' + error;;
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.
The promise object returned by deferred-fs's asynchronous methods has the familiar "then" API:
deferred-fs also exports Orion's Deferred library, giving you access to a richer API than simple promises:
var Deferred = require'deferred-fs'Deferred;var promises = resolve'resolved!' reject'rejected :(' ;Deferredallpromisesthenconsole.log'All promises resolved: ' + resultsjoin', ';console.log'An error occurred: ' + err;;