Skip to content

Instantly share code, notes, and snippets.

@lcherone
Forked from oliverswitzer/nonModuleDirList.js
Last active May 3, 2019 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lcherone/d5cd7e378e8f0eaa624d435bb1bef00b to your computer and use it in GitHub Desktop.
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
// 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