Skip to main content

Overview

The getFileTree function recursively scans a directory and returns a formatted array of file and directory paths. It automatically excludes common build and dependency directories.

Function Signature

getFileTree(dir: string, prefix?: string): string[]

Parameters

dir
string
required
The directory path to scan. Can be relative or absolute. Relative paths are resolved from the current working directory.
prefix
string
default:"''"
Internal parameter used for indentation during recursive calls. Generally not provided by users. Defaults to an empty string.

Return Value

tree
string[]
An array of strings representing the file tree structure. Directories are suffixed with / and subdirectories/files are indented with two spaces per level.

Implementation Details

The function performs the following steps:
  1. Reads the directory contents using fs.readdirSync()
  2. Filters out directories listed in the IGNORED_DIRS array
  3. For each item:
    • If it’s a directory: adds it with a / suffix and recursively scans it with increased indentation
    • If it’s a file: adds it to the results with current indentation
  4. Returns the complete tree as an array of formatted strings

Ignored Directories

The following directories are automatically excluded from the file tree:
const IGNORED_DIRS = ['.git', 'node_modules', 'dist', 'build', '.next'];
These directories are commonly used for version control, dependencies, and build artifacts. Excluding them significantly improves performance and readability when scanning project directories.

Usage Example

import { getFileTree } from './tools/getFileTree';

// Get file tree for current directory
const tree = getFileTree('.');
console.log(tree.join('\n'));

// Get file tree for specific directory
const srcTree = getFileTree('./src');
srcTree.forEach(line => console.log(line));

// Example output:
// src/
//   index.ts
//   utils/
//     helper.ts
//     validator.ts
//   components/
//     Button.tsx

Output Format

The function returns an array where:
  • Each directory is suffixed with /
  • Each level of nesting adds two spaces of indentation
  • Files and directories are listed in the order they appear in the file system
[
  'src/',
  '  index.ts',
  '  components/',
  '    Header.tsx',
  '    Footer.tsx',
  '  utils/',
  '    format.ts'
]

Error Handling

This function will throw an error if:
  • The directory does not exist
  • The directory cannot be read due to permissions
  • The path points to a file instead of a directory
This is a synchronous recursive operation and will block the event loop until the entire directory tree is scanned. For very large directory structures, this may take noticeable time.

Practical Applications

import { getFileTree } from './tools/getFileTree';
import { writeFile } from './tools/writeFile';

// Generate project structure documentation
const tree = getFileTree('./src');
const docs = `# Project Structure\n\n\`\`\`\n${tree.join('\n')}\n\`\`\``;
writeFile('./STRUCTURE.md', docs);

// Find all TypeScript files
const tree = getFileTree('.');
const tsFiles = tree.filter(line => line.trim().endsWith('.ts'));
console.log('TypeScript files:', tsFiles);

Source Code

import fs from 'fs';
import path from 'path';

const IGNORED_DIRS = ['.git', 'node_modules', 'dist', 'build', '.next'];

export const getFileTree = (dir: string, prefix = ''): string[] => {
  let results: string[] = [];
  const list = fs.readdirSync(dir);

  list.forEach(file => {
    if (IGNORED_DIRS.includes(file)) return;
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      results.push(prefix + file + '/');
      results = results.concat(getFileTree(filePath, prefix + '  '));
    } else {
      results.push(prefix + file);
    }
  });

  return results;
};

Build docs developers (and LLMs) love