Skip to content

Commit 53f154b

Browse files
authored
fix(readdir, rmdir): should throw ENOTDIR if used on files (#34)
1 parent 411c6d6 commit 53f154b

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

src/CacheFS.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const path = require("./path.js");
2-
const { ENOENT, EEXIST, ENOTEMPTY } = require("./errors.js");
2+
const { EEXIST, ENOENT, ENOTDIR, ENOTEMPTY } = require("./errors.js");
33

44
const STAT = 0;
55

@@ -149,15 +149,18 @@ module.exports = class CacheFS {
149149
dir.set(basename, entry);
150150
}
151151
rmdir(filepath) {
152+
let dir = this._lookup(filepath);
153+
if (dir.get(STAT).type !== 'dir') throw new ENOTDIR();
152154
// check it's empty (size should be 1 for just StatSym)
153-
if (this._lookup(filepath).size > 1) throw new ENOTEMPTY();
155+
if (dir.size > 1) throw new ENOTEMPTY();
154156
// remove from parent
155157
let parent = this._lookup(path.dirname(filepath));
156158
let basename = path.basename(filepath);
157159
parent.delete(basename);
158160
}
159161
readdir(filepath) {
160162
let dir = this._lookup(filepath);
163+
if (dir.get(STAT).type !== 'dir') throw new ENOTDIR();
161164
return [...dir.keys()].filter(key => typeof key === "string");
162165
}
163166
writeFile(filepath, data, { mode }) {

src/__tests__/fs.promises.spec.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,17 @@ describe("fs.promises module", () => {
152152
});
153153
});
154154
});
155+
it("read a file throws", done => {
156+
fs.mkdir("/readdir2").finally(() => {
157+
fs.writeFile("/readdir2/not-a-dir", "").then(() => {
158+
fs.readdir("/readdir2/not-a-dir").catch(err => {
159+
expect(err).not.toBe(null);
160+
expect(err.code).toBe('ENOTDIR');
161+
done();
162+
});
163+
})
164+
})
165+
});
155166
});
156167

157168
describe("rmdir", () => {
@@ -199,6 +210,17 @@ describe("fs.promises module", () => {
199210
});
200211
});
201212
});
213+
it("delete a file throws", done => {
214+
fs.mkdir("/rmdir").finally(() => {
215+
fs.writeFile("/rmdir/not-a-dir", "").then(() => {
216+
fs.rmdir("/rmdir/not-a-dir").catch(err => {
217+
expect(err).not.toBe(null);
218+
expect(err.code).toBe('ENOTDIR');
219+
done();
220+
});
221+
});
222+
});
223+
});
202224
});
203225

204226
describe("unlink", () => {

src/errors.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ function Err(name) {
1414

1515
const EEXIST = Err("EEXIST");
1616
const ENOENT = Err("ENOENT");
17+
const ENOTDIR = Err("ENOTDIR");
1718
const ENOTEMPTY = Err("ENOTEMPTY");
1819

19-
module.exports = { EEXIST, ENOENT, ENOTEMPTY };
20+
module.exports = { EEXIST, ENOENT, ENOTDIR, ENOTEMPTY };

0 commit comments

Comments
 (0)