Skip to content

Instantly share code, notes, and snippets.

@titovanton
Last active February 19, 2019 07:22
Show Gist options
  • Save titovanton/e46474a3fc40883271d94c97833c1889 to your computer and use it in GitHub Desktop.
Save titovanton/e46474a3fc40883271d94c97833c1889 to your computer and use it in GitHub Desktop.
/**
* Recursive listing of all files inside path
* and all files inside of all folders and so on...
* But using stack algorithm instead recursion, which uses less RAM.
* About fs.Stats:
* https://nodejs.org/api/fs.html#fs_class_fs_stats
* @param path - path to root folder
* @param fn - callback function
* @return nothing.
* Expected parameters of the callback functin:
* @param name - the name of file or directory
* @param absPath - the absolute path to
* @param dirPath - the absolute path to parent dir
* @param statsObj - result of fs.statSync
*/
export const recursiveFolder = (path, fn) => {
// current dir path
let dirPath = path;
// stack of dir path
let dirStack = [];
while (dirPath) {
// like $ ls -a
const list = lib.fs.readdirSync(dirPath);
list.forEach((name, i, lst) => {
const absPath = lib.path.join(dirPath, name);
// posix attributes
const statsObj = lib.fs.statSync(absPath);
if (statsObj.isDirectory()) {
dirStack.push(absPath);
}
fn(name, absPath, dirPath, statsObj);
});
dirPath = dirStack.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment