Skip to content

Instantly share code, notes, and snippets.

@thomd
Created February 11, 2015 22:55
Show Gist options
  • Select an option

  • Save thomd/0c21badb4dd6de5aea41 to your computer and use it in GitHub Desktop.

Select an option

Save thomd/0c21badb4dd6de5aea41 to your computer and use it in GitHub Desktop.
escape from callback hell in node.js
var fs = require('fs');
var path = require('path');
var dir = path.join(__dirname, 'temp');
var source = __filename;
var target = path.join(dir, 'target');
fs.mkdir(dir, handlingError(mkdired));
function mkdired() {
fs.readFile(source, handlingError(haveFile));
}
function haveFile(content) {
fs.writeFile(target, content, handlingError(wroteFile));
}
function wroteFile() {
console.log('all done');
}
function handlingError(callback) {
return function(err, result) {
if(err) {
console.log(err);
} else {
callback(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment