Created
March 1, 2019 13:54
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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