Created
August 23, 2010 00:50
-
-
Save samleb/544531 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sys = require('sys'), | |
fs = require('fs'), | |
path = require('path'); | |
function rmrf(file, callback) { | |
fs.stat(file, function(err, stat) { | |
if (err) return callback(err); | |
if (stat.isFile()) return fs.unlink(file, callback); | |
var dir = file; | |
fs.readdir(dir, function(err, files) { | |
if (err) return callback(err); | |
if (!files.length) return callback(); | |
var runner = TaskRunner(function(err) { | |
err ? callback(err) : fs.rmdir(dir, callback); | |
}); | |
files.forEach(function(f) { | |
runner.runTask(function(cont) { | |
rmrf(path.join(file, f), cont); | |
}); | |
}); | |
}); | |
}); | |
} | |
function getFiles(dir, condition, callback) { | |
var result = [], | |
runner = TaskRunner(function(err) { | |
callback(err, result); | |
}); | |
function visit(dir) { | |
runner.runTask(function(cont) { | |
fs.stat(dir, function(err, stat) { | |
if (err) return cont(err); | |
if (!condition || condition.test(dir)) { | |
result.push(dir); | |
} | |
if (stat.isFile()) return cont(); | |
fs.readdir(dir, function(err, files) { | |
if (err) return cont(err); | |
files.forEach(function(f) { | |
visit(path.join(dir, f)); | |
}); | |
cont(); | |
}); | |
}); | |
}) | |
} | |
visit(dir); | |
} | |
function TaskRunner(callback) { | |
var remaining = 0, | |
notified = false; | |
function runTask(func) { | |
remaining++; | |
func(taskCompleted); | |
} | |
function taskCompleted(err) { | |
if (notified) return; | |
if (err) { | |
notified = true; | |
callback(err); | |
} else if ((--remaining) == 0) { | |
notified = true; | |
callback(); | |
} | |
} | |
return { | |
runTask: runTask | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment