public
Created

rimraf with futures

  • Download Gist
rimraf.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.