rimraf with futures
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 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