Skip to content

Commit

Permalink
Merge pull request #27 from GAumala/master
Browse files Browse the repository at this point in the history
Don't swallow exceptions thrown in callbacks
  • Loading branch information
mihneadb authored Apr 22, 2017
2 parents 7f6a121 + e9bfead commit 74b3245
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
29 changes: 19 additions & 10 deletions lib/directory-tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@
const FS = require('fs');
const PATH = require('path');

function safeReadDirSync (path) {
let dirData = {};
try {
dirData = FS.readdirSync(path);
} catch(ex) {
if (ex.code == "EACCES")
//User does not have permissions, ignore directory
return null;
else throw ex;
}
return dirData;
}

function directoryTree (path, options, onEachFile) {
const name = PATH.basename(path);
const item = { path, name };
Expand All @@ -27,16 +40,12 @@ function directoryTree (path, options, onEachFile) {
}
}
else if (stats.isDirectory()) {
try {
item.children = FS.readdirSync(path)
.map(child => directoryTree(PATH.join(path, child), options, onEachFile))
.filter(e => !!e);
item.size = item.children.reduce((prev, cur) => prev + cur.size, 0);
} catch(ex) {
if (ex.code == "EACCES")
//User does not have permissions, ignore directory
return null;
}
let dirData = safeReadDirSync(path);
if (dirData === null) return null;
item.children = dirData
.map(child => directoryTree(PATH.join(path, child), options, onEachFile))
.filter(e => !!e);
item.size = item.children.reduce((prev, cur) => prev + cur.size, 0);
} else {
return null; // Or set item.size = 0 for devices, FIFO and sockets ?
}
Expand Down
10 changes: 10 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,14 @@ describe('directoryTree', () => {
const tree = dirtree('./test/test_data');
expect(tree).to.deep.equal(testTree);
});

it('should not swallow exceptions thrown in the callback function', () => {
const error = new Error('Something happened!');
const badFunction = function () {
dirtree('./test/test_data', {extensions:['.txt']}, function(item) {
throw error;
});
}
expect(badFunction).to.throw(error);
})
});

0 comments on commit 74b3245

Please sign in to comment.