Skip to content

Commit

Permalink
improve: folder listing perf and sorting
Browse files Browse the repository at this point in the history
Added explicit sorting since order is undefined on Windows (nodejs/node#3232)
  • Loading branch information
bhj committed May 14, 2022
1 parent 48effe6 commit 2365203
Showing 1 changed file with 3 additions and 28 deletions.
31 changes: 3 additions & 28 deletions server/lib/getFolders.js
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

0 comments on commit 2365203

Please sign in to comment.