Asynchronusly read the files in a directory returning a Promise.
dir
A relative or absolute path of the directory to read files.
options
An optional object parameter with the following properties:
reverse: a boolean value that reverses the order of the list of files before traversing them (defaults to false)
filenameFormat: one of readfiles.FULL_PATH, readfiles.RELATIVE, or readfiles.FILENAME, whether the callback's returns the full-path, relative-path or only the filenames of the traversed files. (default is readfiles.RELATIVE)
rejectOnError: a boolean value whether to stop and trigger the "doneCallback" when an error occurs (defaults to true)
filter: a string, or an array of strings of path expression that match the files being read (defaults to '**')
? matches one character
* matches zero or more characters
** matches zero or more 'directories' in a path
readContents: a boolean value whether to read the file contents when traversing the files [1] (defaults to true)
encoding: a string with the encoding used when reading a file (defaults to 'utf8')
depth: an integer value which limits the number sub-directories levels to traverse for the given path where -1 is infinte, and 0 is none (defaults to -1)
hidden: a boolean value whether to include hidden files prefixed with a . (defaults to false)
callback(err, filename, content, stat)
The optional callback function is triggered everytime a file is found. If there's an error while reading the file the err parameter will contain the error that occured, When readContents is true, the contents parameter will be populated with the contents of the file encoded using the encoding option. For convenience the stat result object is passed to the callback for you to use.
[1] The contents parameter will be null when the readContents option is false.
Asynchronous Callback
When working with asynchronous operations, you can simply return a function (next) { ... } which will enabled you to completed your asynchronous operation until you call next().
readfiles('/path/to/dir/', function (err, filename, content, stat) { if (err) throw err; return function (next) { setTimeout(function () { console.log('File ' + filename); next(); }, 3000); };});
Promise(files)
When calling readfiles, an ES6 Promise is returned with an array of all the files that were found. You can then call then or catch to see if readfiles encountered an error.