Skip to content

Instantly share code, notes, and snippets.

@Shoghy
Created February 26, 2024 15:40
Show Gist options
  • Save Shoghy/944c72bdcd821aca9ddcfdb0714621ca to your computer and use it in GitHub Desktop.
Save Shoghy/944c72bdcd821aca9ddcfdb0714621ca to your computer and use it in GitHub Desktop.
A function to get all files on a folder and its subfolders recursively without using function recursion
import fs from "fs";
/**
* @param {Array<T>} arr
* @param {number} index
* @returns {Array<T>}
* @template T
*/
function RemoveIndexOfArray(arr, index){
const copyOfArray = [... arr];
copyOfArray.splice(index, 1);
return copyOfArray;
}
/**
* @typedef FolderInfo
* @prop {string} name
* @prop {string[]} filesToReview
*/
/**
* Get all files in the specified directory and its subdirectories
*
* recursively without using function recursion
*
* and return all the files paths in an array of strings
* @param {string} folder
*/
function GetAllFiles(folder){
/** @type {string[]} */
const files = [];
/**@type {FolderInfo[]} */
let folderInfo = [{name: folder, filesToReview: fs.readdirSync(folder)}];
while(folderInfo.length > 0){
const current = folderInfo[folderInfo.length - 1];
const path = current.name;
let del = true;
while(current.filesToReview.length > 0){
const filePath = `${path}/${current.filesToReview[0]}`;
current.filesToReview = RemoveIndexOfArray(current.filesToReview, 0);
if(fs.lstatSync(filePath).isDirectory()){
del = false;
folderInfo.push({
name: filePath,
filesToReview: fs.readdirSync(filePath)
});
break;
}else{
files.push(filePath);
}
}
if(del){
folderInfo = RemoveIndexOfArray(folderInfo, folderInfo.length - 1);
}
}
return files;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment