A powerful and flexible Node.js directory tree generator with multiple output modes and extensive customization options.
- 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
npm install -g dirtree-node-clinpm install dirtree-node-cli# 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.txtconst 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();| 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 |
| Option | Short | Description |
|---|---|---|
--exclude <pattern> |
-I |
Exclude files matching regex pattern(s) |
Note on
-Ipatterns: 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 likenode_moduleswhich work everywhere. |--show-errors| | Show error messages for inaccessible files |
| Option | Short | Description |
|---|---|---|
--output <file> |
-o |
Write output to file |
--stream |
Use streaming mode (memory efficient) | |
--async |
Use async mode | |
--progress |
Show progress information |
# 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.txtSynchronously generate directory tree structure.
Parameters:
path(string): Directory pathoptions(Object): Configuration options
Returns:
// Returns a string representing the directory tree
string;Asynchronously generate directory tree structure, returns a Promise.
Parameters:
path(string): Directory pathoptions(Object): Configuration options, including progress callback
Returns:
// Returns a Promise that resolves to a string representing the directory tree
Promise<string>Stream processing directory tree, suitable for large directories.
Parameters:
path(string): Directory pathoptions(Object): Configuration optionsoutputStream(stream.Writable): Output stream (defaults to process.stdout)
{
// 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}`);
}
}{
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
}# Quickly understand project structure
dirtree -L 2 -I "node_modules|.git|dist"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');# Browse entries with sizes, in reverse alphabetical order
dirtree -s -r | head -20
# Check directory structure
dirtree -d -F# Analyze user directory structure
dirtree /home/user -L 3 -d
# Check disk usage
dirtree /var/log -s# Run CLI
npm run dev
# Code linting
npm run lint
# Code formatting
npm run format
# Pre-publish checks
npm run prepublishOnlyThe project uses the following tools to ensure code quality:
- ESLint: Code linting and style consistency
- Prettier: Code formatting
- TypeScript: Type definitions and intellisense
- Sizes are computed with a single internal scan β no external binaries
(the legacy
fast-folder-size/Sysinternalsdu.exedependency 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
- Smart caching of file system stat calls
- Avoids duplicate stat operations
- Uses cache only when needed (sizes, dirs-first, dirs-only modes)
- Memory efficient for large directories
- Progressive output without waiting for complete processing
- Support for custom output streams
- Non-blocking operations
- Suitable for concurrent scenarios
- Progress tracking support
Contributions are welcome! Please follow these steps:
- Fork this repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
# 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 devThis project is licensed under the MIT License. See the LICENSE file for details.
- Fixed:
--stream -o <file>never finished (missingwriteStream.end()), which dropped the success message and could hang the process on older Node versions - Fixed:
-L 0was silently ignored (0treated as falsy) and rendered the whole tree; negative or non-numeric-Lvalues are now rejected with clear errors - Fixed: README programmatic examples used
const { tree } = require(...)which resolved toundefined; 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-sizedependency; directory sizes are computed in-process with one extra scan (nodu.exedownload, no spawn per directory, no more[size error]on locked-down Windows installs) - Changed: library-API exclude regexes with
g/yflags are normalized so matching is stateless and repeatable - Changed:
dirsOnlyno longer silently drops inaccessible directories when--show-errorsis enabled - Changed: minimum Node.js version is now 16 (matches the
commanderrequirement) - Added: test suite (30 tests) and GitHub Actions CI across Node 18/20/22/24
- 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