Skip to content

About

A powerful and flexible directory tree generator for Node.js with multiple output modes.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

2 Commits

Folders and files

Repository files navigation

dirtree-node-cli

npm version License: MIT

A powerful and flexible Node.js directory tree generator with multiple output modes and extensive customization options.

🌟 Features

  • Multiple Execution Modes: Synchronous, asynchronous, and streaming processing
  • Performance Optimized: Smart caching and streaming for large directories
  • Rich Customization Options: Filtering, sorting, and display options
  • Error Handling: Graceful handling of permission and access errors
  • Progress Tracking: Real-time feedback during long operations
  • Cross-Platform: Support for Windows, macOS, and Linux
  • TypeScript Support: Complete type definitions
  • CLI Tool: Comprehensive command-line interface

πŸ“¦ Installation

Global Installation

npm install -g dirtree-node-cli

Local Installation

npm install dirtree-node-cli

πŸš€ Quick Start

Command Line Usage

# Basic usage
dirtree

# Show tree structure of current directory
dirtree .

# Show hidden files
dirtree -a

# Show directories only
dirtree -d

# Show file sizes
dirtree -s

# Limit depth
dirtree -L 2

# Exclude specific files
dirtree -I "node_modules|.git"

# Output to file
dirtree -o output.txt

Programmatic Usage

const tree = require('dirtree-node-cli');

// Synchronously generate directory tree
const result = tree('.', {
  maxDepth: 2,
  sizes: true,
  dirsFirst: true,
});

console.log(result);
const tree = require('dirtree-node-cli');

// Asynchronously generate directory tree
tree
  .async('.', {
    sizes: true,
    onProgress: (progress) => {
      console.log(`Processing: ${progress.filesProcessed} files, ${progress.dirsProcessed} dirs`);
    },
  })
  .then((result) => {
    console.log(result);
  });
const tree = require('dirtree-node-cli');
const fs = require('fs');

// Stream processing for large directories
const outputStream = fs.createWriteStream('tree-output.txt');
tree.stream(
  '.',
  {
    sizes: true,
  },
  outputStream
);
// tree.stream() traverses synchronously; the caller owns the stream
// lifecycle, so end it once the call returns to flush and close the file.
outputStream.end();

πŸ”§ CLI Command Reference

Basic Options

Option Short Description
--all -a Show all files, including hidden files
--dirs-only -d Show directories only
--dirs-first List directories before files
--sizes -s Show file and directory sizes
--max-depth <n> -L Maximum depth of tree traversal
--reverse -r Sort in reverse order
--trailing-slash -F Append '/' to directory names
--ascii Use ASCII line characters instead of Unicode

Filtering and Exclusion

Option Short Description
--exclude <pattern> -I Exclude files matching regex pattern(s)

Note on -I patterns: patterns are regular expressions matched against the full path of each entry (e.g. /home/user/project/node_modules), not just the file name. On Windows the path separator is \, so patterns containing / will not match β€” prefer plain substrings like node_modules which work everywhere. | --show-errors | | Show error messages for inaccessible files |

Output Options

Option Short Description
--output <file> -o Write output to file
--stream Use streaming mode (memory efficient)
--async Use async mode
--progress Show progress information

Example Commands

# Show complete directory structure including hidden files
dirtree -a -s

# Show directory structure only, with max 3 levels depth
dirtree -d -L 3

# Exclude node_modules and .git directories
dirtree -I "node_modules|\.git"

# Use ASCII characters and show file sizes
dirtree --ascii --sizes

# Async processing for large directories with progress
dirtree --async --progress

# Save results to file
dirtree -o directory-structure.txt

πŸ“š API Documentation

Main Methods

tree(path, options)

Synchronously generate directory tree structure.

Parameters:

  • path (string): Directory path
  • options (Object): Configuration options

Returns:

// Returns a string representing the directory tree
string;

tree.async(path, options)

Asynchronously generate directory tree structure, returns a Promise.

Parameters:

  • path (string): Directory path
  • options (Object): Configuration options, including progress callback

Returns:

// Returns a Promise that resolves to a string representing the directory tree
Promise<string>

tree.stream(path, options, outputStream)

Stream processing directory tree, suitable for large directories.

Parameters:

  • path (string): Directory path
  • options (Object): Configuration options
  • outputStream (stream.Writable): Output stream (defaults to process.stdout)

Configuration Options

{
  // Display options
  allFiles: false,         // Show all files, including hidden files
  dirsOnly: false,         // Show directories only
  sizes: false,            // Show file and directory sizes
  dirsFirst: false,        // List directories before files
  trailingSlash: false,    // Append '/' to directory names
  showErrors: false,       // Show error messages

  // Filtering and sorting
  exclude: [],             // Array of regex patterns to exclude
  maxDepth: Infinity,      // Maximum depth
  reverse: false,          // Sort in reverse order

  // Display settings
  lineAscii: false,        // Use ASCII line characters

  // Callback functions
  onProgress: (progress) => { // Progress callback
    console.log(`Files: ${progress.filesProcessed}, Dirs: ${progress.dirsProcessed}`);
  }
}

Progress Callback Interface

{
  filesProcessed: number,  // Total number of files processed
  dirsProcessed: number,   // Total number of directories processed
  totalSize: number,       // Total size of processed files (in bytes)
  currentPath: string,     // Currently processing path
  done: boolean           // Whether all processing is complete
}

πŸ’‘ Use Cases

Code Repository Analysis

# Quickly understand project structure
dirtree -L 2 -I "node_modules|.git|dist"

Documentation Generation

const tree = require('dirtree-node-cli');
const fs = require('fs');

// Generate project structure documentation
const result = tree('.', {
  maxDepth: 3,
  exclude: [/node_modules/, /\.git/, /coverage/],
  sizes: true,
});

fs.writeFileSync('structure.md', '## Project Structure\n\n```\n' + result + '\n```\n');

File Management

# Browse entries with sizes, in reverse alphabetical order
dirtree -s -r | head -20

# Check directory structure
dirtree -d -F

System Administration

# Analyze user directory structure
dirtree /home/user -L 3 -d

# Check disk usage
dirtree /var/log -s

πŸ”§ Development

Scripts

# Run CLI
npm run dev

# Code linting
npm run lint

# Code formatting
npm run format

# Pre-publish checks
npm run prepublishOnly

Code Quality

The project uses the following tools to ensure code quality:

  • ESLint: Code linting and style consistency
  • Prettier: Code formatting
  • TypeScript: Type definitions and intellisense

πŸ“Š Performance Features

Directory Sizes

  • Sizes are computed with a single internal scan β€” no external binaries (the legacy fast-folder-size/Sysinternals du.exe dependency is gone)
  • Directory sizes reflect on-disk contents (like du), including hidden and excluded files, independent of display filters
  • Directory sizes require a full subtree scan regardless of -L, so that boundary directories show accurate totals

StatCache Optimization

  • Smart caching of file system stat calls
  • Avoids duplicate stat operations
  • Uses cache only when needed (sizes, dirs-first, dirs-only modes)

Stream Processing

  • Memory efficient for large directories
  • Progressive output without waiting for complete processing
  • Support for custom output streams

Async Processing

  • Non-blocking operations
  • Suitable for concurrent scenarios
  • Progress tracking support

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork this repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Development Setup

# Clone repository
git clone https://github.com/snowsword20/dirtree-node-cli.git
cd dirtree-node-cli

# Install dependencies
npm install

# Run development version
npm run dev

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for details.

πŸ”— Related Links

πŸ“ˆ Version History

1.1.0

  • Fixed: --stream -o <file> never finished (missing writeStream.end()), which dropped the success message and could hang the process on older Node versions
  • Fixed: -L 0 was silently ignored (0 treated as falsy) and rendered the whole tree; negative or non-numeric -L values are now rejected with clear errors
  • Fixed: README programmatic examples used const { tree } = require(...) which resolved to undefined; both import styles now work (compat export added)
  • Fixed: symlinked target directories are now traversed (root symlinks are followed; child symlinks still are not, to avoid cycles)
  • Fixed: statistics are now exclusive β€” directories are no longer counted as files, and the root directory is excluded (matches tree(1) summaries)
  • Changed: removed the fast-folder-size dependency; directory sizes are computed in-process with one extra scan (no du.exe download, no spawn per directory, no more [size error] on locked-down Windows installs)
  • Changed: library-API exclude regexes with g/y flags are normalized so matching is stateless and repeatable
  • Changed: dirsOnly no longer silently drops inaccessible directories when --show-errors is enabled
  • Changed: minimum Node.js version is now 16 (matches the commander requirement)
  • Added: test suite (30 tests) and GitHub Actions CI across Node 18/20/22/24

1.0.0

  • Initial release
  • Complete CLI and programmatic interface
  • Support for sync, async, and streaming modes
  • Rich customization options
  • TypeScript support
  • Performance optimization and error handling

Author: cloudyer [email protected] License: MIT Node.js Requirement: >= 16.0.0

About

A powerful and flexible directory tree generator for Node.js with multiple output modes.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages