npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

dirtree-node-cli

v1.0.1

Published

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

Readme

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
);

🔧 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) | | --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

# Find large files
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

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.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: >= 12.0.0