Created
August 13, 2024 16:19
-
-
Save montasim/c871e65223c3945af050104571948eab to your computer and use it in GitHub Desktop.
Recursively generates a tree structure of the directory.
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'; | |
import path from 'path'; | |
/** | |
* Recursively generates a tree structure of the directory. | |
* | |
* @param {string} dir - The directory to scan. | |
* @param {string} [prefix=''] - The prefix used for formatting the tree structure. | |
* @param {string} [output=''] - The accumulated output string containing the directory structure. | |
* @returns {string} - The complete directory structure as a string. | |
*/ | |
function generateTree(dir, prefix = '', output = '') { | |
const files = fs.readdirSync(dir); | |
files.forEach((file, index) => { | |
const fullPath = path.join(dir, file); | |
const isLast = index === files.length - 1; | |
const isDirectory = fs.statSync(fullPath).isDirectory(); | |
// Ignore specified directories | |
if (['.git', 'node_modules', 'log'].includes(file)) { | |
return; | |
} | |
output += `${prefix}${isLast ? '└── ' : '├── '}${file}\n`; | |
if (isDirectory) { | |
output = generateTree(fullPath, `${prefix}${isLast ? ' ' : '│ '}`, output); | |
} | |
}); | |
return output; | |
} | |
/** | |
* Saves the generated tree structure to a file. | |
* | |
* @param {string} filename - The name of the file to save the tree structure to. | |
* @param {string} content - The content to write to the file. | |
*/ | |
function saveTreeToFile(filename, content) { | |
fs.writeFileSync(filename, content, 'utf8'); | |
} | |
// The output filename where the directory structure will be saved | |
const outputFilename = 'structure.md'; | |
// Initialize the tree structure with a Markdown header | |
let treeStructure = '# Project Structure\n\n'; | |
// Generate the directory structure starting from the current working directory | |
treeStructure += generateTree(process.cwd()); | |
// Save the generated structure to a file | |
saveTreeToFile(outputFilename, treeStructure); | |
console.log(`Project structure has been saved to ${outputFilename}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment