Skip to content

Instantly share code, notes, and snippets.

@mvillarrealb
Created March 1, 2019 13:54
Show Gist options
  • Save mvillarrealb/1cd7ee49b5624ec328802387ffbbc478 to your computer and use it in GitHub Desktop.
Save mvillarrealb/1cd7ee49b5624ec328802387ffbbc478 to your computer and use it in GitHub Desktop.
Scan recursively a directory to find all files, in the example we filter markdown(.md) files
const fs = require('fs');
const path = require('path');
/**
*
* @param {String} Directory to scan
* @param {Array} allFiles partial list of files(used for recursivity)
*/
const recursiveScan = function (directory, allFiles) {
const files = fs.readdirSync(directory);
allFiles = allFiles || [];
files.forEach(function (file) {
const stat = fs.statSync(path.join(directory, file));
if (stat.isDirectory()) {
/**
* if it is a directory invoke the recursiveScan function passing the allFiles
array to keep a reference of it
*/
allFiles = recursiveScan(path.join(directory, file), allFiles);
} else {
allFiles.push(path.join(directory, file));
}
});
return allFiles;
};
(async function () {
/**
* Markdown filter
*/
const markDownFiles = recursiveScan('test').filter(file => file.indexOf(".md") >= 0);
console.log(markDownFiles);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment