Directory Tree Printer CLI
A Node CLI that prints a directory as an indented tree with box-drawing connectors, skipping node_modules and dotfiles and reporting total files and directories.
Project
node-dir-tree-cli
Entry point: tree.mjs
Install
node --versionRun
node tree.mjs srcTest
node --test tree.test.mjsExpected output
Prints a tree of the given directory followed by a count of directories and files.Dependencies
- node >=20
What it does
Prints a readable directory tree using box-drawing connectors, which is handy for documenting a project layout without a screenshot.
import { readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
const IGNORED = new Set(['node_modules', '.git']);
function walk(dir, prefix, stats) {
const entries = readdirSync(dir)
.filter((name) => !IGNORED.has(name) && !name.startsWith('.'))
.sort();
entries.forEach((name, index) => {
const full = join(dir, name);
const last = index === entries.length - 1;
const isDir = statSync(full).isDirectory();
console.log(prefix + (last ? '└── ' : '├── ') + name + (isDir ? '/' : ''));
if (isDir) { stats.dirs++; walk(full, prefix + (last ? ' ' : '│ '), stats); }
else stats.files++;
});
}
const root = process.argv[2] ?? '.';
const stats = { dirs: 0, files: 0 };
console.log(root + '/');
walk(root, '', stats);
console.log('\n' + stats.dirs + ' directories, ' + stats.files + ' files');
Ignored names such as node_modules and dotfiles are skipped by default so the output stays about structure rather than dependencies.
Run and verify
node tree.mjs src
Run against any directory; the first argument defaults to the current directory when omitted.
Expected Output
For a small src folder the program should print the tree with connectors and a trailing count. The output is:
src/
├── index.js
├── lib/
│ └── util.js
└── cli.js
1 directories, 3 files
Directories are marked with a trailing slash, the last entry of each level uses a corner connector, and the summary counts files and directories separately.
Limitations
Symbolic links are treated as their target and can create cycles on unusual layouts; add a visited set if you run it over a graph with links.