Skip to content

Commit 5283820

Browse files
authored
feat: add du method (#45)
1 parent eb21a02 commit 5283820

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

src/CacheFS.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,4 +248,19 @@ module.exports = class CacheFS {
248248
dir.set(basename, entry);
249249
return stat;
250250
}
251+
_du (dir) {
252+
let size = 0;
253+
for (const [name, entry] of dir.entries()) {
254+
if (name === STAT) {
255+
size += entry.size;
256+
} else {
257+
size += this._du(entry);
258+
}
259+
}
260+
return size;
261+
}
262+
du (filepath) {
263+
let dir = this._lookup(filepath);
264+
return this._du(dir);
265+
}
251266
};

src/PromisifiedFS.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ module.exports = class PromisifiedFS {
4848
this.readlink = this._wrap(this.readlink, false)
4949
this.symlink = this._wrap(this.symlink, true)
5050
this.backFile = this._wrap(this.backFile, true)
51+
this.du = this._wrap(this.du, false);
5152

5253
this.saveSuperblock = debounce(() => {
5354
this._saveSuperblock();
@@ -303,4 +304,7 @@ module.exports = class PromisifiedFS {
303304
await this._writeStat(filepath, size, opts)
304305
return null
305306
}
307+
async du(filepath) {
308+
return this._cache.du(filepath);
309+
}
306310
}

src/__tests__/fs.promises.spec.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,4 +446,31 @@ describe("fs.promises module", () => {
446446
});
447447
});
448448

449+
describe("du", () => {
450+
it("du returns the total file size of a path", done => {
451+
fs.mkdir("/du").finally(() => {
452+
fs.writeFile("/du/a.txt", "hello").then(() => {
453+
fs.writeFile("/du/b.txt", "hello").then(() => {
454+
fs.mkdir("/du/sub").then(() => {
455+
fs.writeFile("/du/sub/a.txt", "hello").then(() => {
456+
fs.writeFile("/du/sub/b.txt", "hello").then(() => {
457+
fs.du("/du/sub/a.txt").then(size => {
458+
expect(size).toBe(5)
459+
fs.du("/du/sub").then(size => {
460+
expect(size).toBe(10)
461+
fs.du("/du").then(size => {
462+
expect(size).toBe(20)
463+
done();
464+
});
465+
});
466+
});
467+
});
468+
});
469+
});
470+
});
471+
});
472+
});
473+
});
474+
});
475+
449476
});

0 commit comments

Comments
 (0)