Skip to content

Instantly share code, notes, and snippets.

@c0d0g3n
Last active February 15, 2019 09:45
Show Gist options
  • Save c0d0g3n/4f4e3c9be448dc825201e8f598fe7557 to your computer and use it in GitHub Desktop.
Save c0d0g3n/4f4e3c9be448dc825201e8f598fe7557 to your computer and use it in GitHub Desktop.
Recursively find files in a directory using Bluebird promises
const Promise = require('bluebird')
const fs = require('fs')
Promise.promisifyAll(fs)
const path = require('path')
// Usage:
// const findFiles = require('path/to/findFiles.js')
// findFiles('dir/to/search/in')
// Arg 'files' is used to propagate data of recursive calls to the initial call
// If you really want to, you can use arg 'files' to manually add some files to the result
// Note: Order of results is not guaranteed due to parallel nature of function
findFiles = (dir, files = []) => {
return fs.readdirAsync(dir)
.then((items) => { // items = files || dirs
// items figures as list of tasks, settled promise means task is completed
return Promise.map(items, (item) => {
item = path.resolve(dir, item)
return fs.statAsync(item)
.then((stat) => {
if (stat.isFile()) {
// item is file
files.push(item)
} else if (stat.isDirectory()) {
// item is dir
// note: we only care about this being a promise, not it's resolved value
return findFiles(item, files)
}
})
})
})
.then(() => {
// every task is completed, provide results
return files
})
}
module.exports = findFiles
@toreric
Copy link

toreric commented Feb 15, 2019

This is a good algorithm for limited trees (thank You!), but is pretty slow for extended file trees. Comments?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment