Skip to content

Instantly share code, notes, and snippets.

@neatshell
Created November 2, 2019 14:48
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 neatshell/8af9681dae9565d4afd13486678e3acb to your computer and use it in GitHub Desktop.
Save neatshell/8af9681dae9565d4afd13486678e3acb to your computer and use it in GitHub Desktop.
import path from 'path';
import fs from 'fs';
const testAgainstRegex = (patterns, string) => {
if (typeof patterns === 'string') {
return new RegExp(patterns).test(string);
} else if (patterns instanceof Array) {
return new RegExp(patterns.join('|')).test(string);
} else {
return patterns;
}
};
const ifUndefined = (value, fallback) => {
if (typeof value === 'undefined') {
return fallback;
} else {
return value;
}
};
/**
*
* @param root: the folder from which start to walk
* @param options: an object to customize the behavior of the walking
* By default, if no options provided it will collect every folders and files
* starting from the root to the leaves.
*
* Here the detailed list of options:
*
* - exclude: a string or an array of string to specify folders or files to NOT include in the resulting list
* - include: a string or an array of string to specify folders or files to ONLY include in the resulting list
* - foldersOnly: a boolean to collect only folders
* - filesOnly: a boolean to collect only files
* - recurse: a boolean to indicate whether to recurse till the leaves or stop at the first level
* @param list: an Array to which push the collected files
* @returns {Array}
*/
const walkSync = (root, options = {}, list = []) => {
options.exclude = ifUndefined(options.exclude, false);
options.include = ifUndefined(options.include, true);
options.foldersOnly = ifUndefined(options.foldersOnly, false);
options.filesOnly = ifUndefined(options.filesOnly, false);
options.recurse = ifUndefined(options.recurse, true);
const files = fs.readdirSync(root);
files.forEach((file) => {
if (fs.statSync(path.join(root, file)).isDirectory()) {
if (options.foldersOnly && testAgainstRegex(options.include, file) && !testAgainstRegex(options.exclude, file)) {
options.callback ?
list.push(options.callback(path.join(root, file))) : list.push(path.join(root, file));
}
if (options.recurse) {
list = walkSync(path.join(root, file), options, list);
}
}
else {
if (options.filesOnly && testAgainstRegex(options.include, file) && !testAgainstRegex(options.exclude, file)) {
options.callback ?
list.push(options.callback(path.join(root, file))) : list.push(path.join(root, file));
}
}
});
return list;
};
export default walkSync;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment