Skip to content

Instantly share code, notes, and snippets.

@laverdet
Created August 8, 2011 02:12
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save laverdet/1131093 to your computer and use it in GitHub Desktop.
rimraf with futures
var path = require('path'),
fs = require('fs'),
Future = require('fibers/future');
// Create future-returning fs functions
var fs2 = {};
for (var ii in fs) {
fs2[ii] = Future.wrap(fs[ii]);
}
// Return a future which just pauses for a certain amount of time
function timer(ms) {
var future = new Future;
setTimeout(function() {
future.return();
}, ms);
return future;
}
var timeout = 0;
var rimraf = module.exports = function(p, opts) {
opts = opts || {};
opts.maxBusyTries = opts.maxBusyTries || 3;
var busyTries = 0;
while (true) {
try {
var stat = fs2.lstat(p).wait();
if (!stat.isDirectory()) return fs2.unlink(p).wait();
var rimrafs = fs2.readdir(p).wait().map(function(file) {
return rimraf(path.join(p, file), opts);
});
Future.wait(rimrafs);
fs2.rmdir(p).wait();
timeout = 0;
return;
} catch (ex) {
if (ex.message.match(/^EMFILE/)) {
timer(timeout += 10).wait();
} else if (ex.message.match(/^EBUSY/) && busyTries < opt.maxBusyTries) {
timer(++busyTries * 100).wait();
} else {
throw ex;
}
}
}
}.future();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment