Created
February 26, 2024 15:40
-
-
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
This file contains 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
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