-
-
Save medikoo/1133857 to your computer and use it in GitHub Desktop.
rimraf with deferred/promise
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') | |
, deferred = require('deferred'), delay = deferred.delay | |
, promisify = deferred.promisify | |
, lstat = promisify(fs.lstat), unlink = promisify(fs.unlink), readdir = promisify(fs.readdir) | |
, rmdir = promisify(fs.rmdir) | |
var timeout = 0; | |
var rimraf = module.exports = function (p, opts) { | |
opts = opts || {}; | |
opts.maxBusyTries = opts.maxBusyTries || 3; | |
var busyTries = 0; | |
return rimraf_(p, opts) | |
} | |
var rimraf_ = function (p, opts) { | |
return lstat(p) | |
(function (stat) { | |
if (!stat.isDirectory()) return unlink(p); | |
return readdir(p).map(function(file) { | |
return rimraf(path.join(p, file), opts); | |
}) | |
(function () { | |
return rmdir(p); | |
}); | |
}) | |
(function () { timeout = 0 }, function CB (ex) { | |
if (ex.message.match(/^EMFILE/)) { | |
return delay(rimraf_, timeout += 10)(p, opts); | |
} else if (ex.message.match(/^EBUSY/) && busyTries < opt.maxBusyTries) { | |
return delay(rimraf_, ++busyTries * 100)(p, opts); | |
} else { | |
throw ex; | |
} | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment