Permalink
Browse files

Handle unexpected errors better

This lets us avoid stats in all cases, and just infer directory-ness
based on the errors that we see.
  • Loading branch information...
1 parent d951675 commit 3427809071a4f8ad4397b1dce11dc3133da48087 @isaacs committed Feb 6, 2013
Showing with 20 additions and 6 deletions.
  1. +20 −6 rimraf.js
View
26 rimraf.js
@@ -63,16 +63,20 @@ function rimraf_ (p, cb) {
if (er && er.code === "ENOENT")
return cb()
if (er && (er.code === "EPERM" || er.code === "EISDIR"))
- return rmdir(p, cb)
+ return rmdir(p, er, cb)
return cb(er)
})
}
-function rmdir (p, cb) {
+function rmdir (p, originalEr, cb) {
// try to rmdir first, and only readdir on ENOTEMPTY
+ // if we guessed wrong, and it's not a directory, then
+ // raise the original error.
fs.rmdir(p, function (er) {
if (er && er.code === "ENOTEMPTY")
rmkids(p, cb)
+ else if (er && er.code === "ENOTDIR")
+ cb(originalEr)
else
cb(er)
})
@@ -110,9 +114,19 @@ function rimrafSync (p) {
return
if (er.code !== "EPERM" && er.code !== "EISDIR")
throw er
- fs.readdirSync(p).forEach(function (f) {
- rimrafSync(path.join(p, f))
- })
- fs.rmdirSync(p)
+ try {
+ fs.rmdirSync(p)
+ } catch (er2) {
+ if (er2.code === "ENOENT")
+ return
+ if (er2.code === "ENOTDIR")
+ throw er
+ if (er2.code === "ENOTEMPTY") {
+ fs.readdirSync(p).forEach(function (f) {
+ rimrafSync(path.join(p, f))
+ })
+ fs.rmdirSync(p)
+ }
+ }
}
}

0 comments on commit 3427809

Please sign in to comment.