-
-
Notifications
You must be signed in to change notification settings - Fork 70
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improve: folder listing perf and sorting
Added explicit sorting since order is undefined on Windows (nodejs/node#3232)
- Loading branch information
Showing
1 changed file
with
3 additions
and
28 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,10 @@ | ||
/* eslint-disable promise/no-nesting */ | ||
const path = require('path') | ||
const fs = require('fs') | ||
const { promisify } = require('util') | ||
const readdir = promisify(fs.readdir) | ||
const stat = promisify(fs.stat) | ||
|
||
// based on http://stackoverflow.com/a/38314404/2533525 | ||
const getFolders = function (dir, filterFn) { | ||
// default filter function accepts all folders | ||
filterFn = filterFn || function () { return true } | ||
|
||
return readdir(dir).then(list => { | ||
return Promise.all(list.map(file => { | ||
file = path.resolve(dir, file) | ||
return stat(file).then(stat => { | ||
if (stat.isDirectory()) { | ||
return filterFn(file) ? file : '' | ||
} | ||
}).catch(err => { | ||
// stat failed for this folder | ||
console.error(err.message) | ||
}) | ||
})).then(results => { | ||
return results.filter(f => { | ||
return !!f | ||
}) | ||
}) | ||
}).then(results => { | ||
// flatten the array of arrays | ||
return Array.prototype.concat.apply([], results) | ||
}) | ||
} | ||
const getFolders = dir => readdir(dir, { withFileTypes: true }) | ||
.then(list => Promise.all(list.map(ent => ent.isDirectory() ? path.resolve(dir, ent.name) : null))) | ||
.then(list => list.filter(f => !!f).sort()) | ||
|
||
module.exports = getFolders |