Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Async load list of files from directory, with optional extensions filtering and natural sort in nodejs
// 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
You can’t perform that action at this time.