Skip to content

Instantly share code, notes, and snippets.

@montasim
Last active May 7, 2025 06:59
Show Gist options
  • Save montasim/c871e65223c3945af050104571948eab to your computer and use it in GitHub Desktop.
Save montasim/c871e65223c3945af050104571948eab to your computer and use it in GitHub Desktop.
Recursively generates a tree structure of the directory.
import fs from 'fs';
import path from 'path';
// Configuration
const IGNORE_LIST = ['.git', 'node_modules', 'log']; // Add more if needed
const OUTPUT_FILE = 'structure.md';
/**
* 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 = '') {
let files;
try {
files = fs.readdirSync(dir);
} catch (err) {
console.error(`Error reading directory ${dir}:`, err.message);
return output;
}
const filteredFiles = files.filter(file => !IGNORE_LIST.includes(file));
const totalFiles = filteredFiles.length;
filteredFiles.forEach((file, index) => {
const fullPath = path.join(dir, file);
const isLast = index === totalFiles - 1;
const isDirectory = fs.statSync(fullPath).isDirectory();
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');
console.log(`Project structure has been saved to ${filename}`);
}
// Get target directory from command-line arguments or use current working directory
const args = process.argv.slice(2);
const targetDir = args[0] ? path.resolve(args[0]) : process.cwd();
console.log(`Generating project structure for: ${targetDir}`);
let treeStructure = '# Project Structure\n\n';
treeStructure += '```\n';
treeStructure += generateTree(targetDir);
treeStructure += '\n```\n';
saveTreeToFile(OUTPUT_FILE, treeStructure);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment