-
-
Save lcherone/d5cd7e378e8f0eaa624d435bb1bef00b to your computer and use it in GitHub Desktop.
Async load list of files from directory, with optional extensions filtering and natural sort in nodejs
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
// asyncDirListNaturalSort.js | |
const path = require('path') | |
const fs = require('fs') | |
/** | |
* Asynchronous load list of files from directory, | |
* - with optional extensions filtering and natural sort | |
* | |
* @param {string} dirPath directory path to folder | |
* @param {array} extFilter extentions to filter, with dots | |
* @param {bool} sort enable natral sort on the returned list | |
*/ | |
const readDir = (dirPath, extFilter, sort) => { | |
return new Promise((resolve, reject) => { | |
fs.readdir(dirPath, (err, files) => { | |
if (err) return reject(err) | |
// filter list | |
if (extFilter && extFilter.length) files = files.filter(element => extFilter.includes(path.extname(element))) | |
// sort list | |
if (sort) { | |
files = files.sort((new Intl.Collator(undefined, { | |
numeric: true, | |
sensitivity: 'base' | |
})).compare) | |
} | |
resolve(files) | |
}); | |
}) | |
} | |
/** | |
* Example/s | |
* | |
* node asyncDirListNaturalSort.js ./some/folder/path/to/images | |
*/ | |
const pathSupplied = path.join(__dirname, process.argv[2]) | |
const extFilter = ['.jpg', '.png', '.gif'] | |
// using async/await | |
;(async () => { | |
try { | |
let list = await readDir(pathSupplied, extFilter, true) | |
console.log(list) | |
} catch (e) { | |
console.error(e) | |
} | |
})() | |
// using promise | |
readDir(pathSupplied, extFilter, true).then(list => { | |
console.log(list) | |
}).catch(e => { | |
console.error(e) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment