Skip to content

Instantly share code, notes, and snippets.

@fiveisprime
Created September 17, 2013 14:15
Show Gist options
  • Save fiveisprime/6594898 to your computer and use it in GitHub Desktop.
Save fiveisprime/6594898 to your computer and use it in GitHub Desktop.
var async = require('async')
, Q = require('q')
, fs = require('fs');
//
// Typical node style function that uses a callback (fn).
//
var piratize = function(file, fn) {
fs.readFile(file, 'utf8', function(err, data) {
if (err) return fn(err, null);
var outFile = 'pirate.' + file
, output = 'Yarr! ' + data
.replace(/you/g, 'ye')
.replace(/You/g, 'Ye')
.replace(/and/g, 'n\'')
.replace(/your/g, 'yer')
.replace(/Your/g, 'Yer');
fs.writeFile(outFile, output, function(err) {
if (err) return fn(err, null);
fn(null, outFile);
});
});
};
//
// Q promise style which only accepts what's necessary to process the request
// and returns a promise.
//
var piratizePromise = function(file) {
var deferred = Q.defer();
fs.readFile(file, 'utf8', function(err, data) {
if (err) return deferred.reject(err);
var outFile = 'pirate.' + file
, output = 'Yarr! ' + data
.replace(/you/g, 'ye')
.replace(/You/g, 'Ye')
.replace(/and/g, 'n\'')
.replace(/your/g, 'yer')
.replace(/Your/g, 'Yer');
fs.writeFile(outFile, output, function(err) {
if (err) return deferred.reject(err);
deferred.resolve(outFile);
});
});
return deferred.promise;
};
//
// Classic node style.
// Notice the two check for err in the callbacks.
//
piratize('note.txt', function(err, path) {
if (err) return console.error(err);
fs.readFile(path, 'utf8', function(err, out) {
if (err) return console.error(err);
console.log(out);
});
});
//
// Async style.
// Cleaner (no duplicate checks), but a very different style.
//
async.waterfall([
function(callback) {
piratize('note.txt', callback);
}
, function(file, callback) {
fs.readFile(file, 'utf8', callback);
}
], function(err, result) {
if (err) return console.error(err);
console.log(result);
});
//
// Promise style with Q node function calls.
// Because the error and results are separated into their own methods on the
// promise, the calls can be bound directly to the log and error methods
// of the console.
//
Q.nfcall(piratize, 'note.txt')
.then(function(file) {
// Return the resulting promise.
return Q.nfcall(fs.readFile, file, 'utf8');
})
.then(console.log)
.fail(console.error)
.done();
//
// Promise style with Q.
// The piratizePromise function returns a promise so there is no need to
// use Q for the call. Again log and error are bound directly to the result
// of the promises resolve/then and reject/fail methods.
//
piratizePromise('note.txt')
.then(function(file) {
return Q.nfcall(fs.readFile, file, 'utf8');
})
.then(console.log)
.fail(console.error)
.done();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment