Traverse a path and print directory tree
AdobeSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to recursively traverse a directory structure and format the output into a human-readable, indented tree structure while handling potential I/O errors.
Problem Statement
Given a root directory path, implement a function printDirectoryTree(rootPath) that traverses the filesystem and prints a hierarchical tree structure to the console. The output should visually represent the nesting levels using indentation and prefixes.
Requirements
- For each directory, list its contents sorted alphabetically.
- Use a tree-like visual format. For example:
root/ ├── config.json ├── src/ │ ├── index.js │ └── utils.js └── README.md - If a directory cannot be accessed (e.g., permission denied), skip it and continue processing.
- Your solution should use synchronous filesystem methods (e.g.,
fs.readdirSync,fs.statSync) for simplicity.
Function Signature
function printDirectoryTree(rootPath, prefix = '') {
// Implementation here
}
Constraints
- Handle deep directory structures without overflowing the stack (though you may assume reasonable depth).
- Ignore hidden files (files starting with a dot
.). - The input
rootPathis guaranteed to be a string representing a valid starting directory.
Edge Cases
- Empty directories.
- Symlinks (you can choose to treat them as files or skip them).
- Directories with restricted permissions.
Hints
Hint 1
Use 'fs.readdirSync' with the 'withFileTypes' option set to 'true' to easily distinguish between files and directories.
Hint 2
Maintain a 'prefix' string parameter that grows as you recurse deeper into subdirectories to handle the visual indentation.
Hint 3
Sort the results of 'readdirSync' alphabetically before iterating through them to ensure the output is deterministic.
Follow-up questions
- How would you modify your implementation to output the result as a nested JSON object instead of a printed tree?
- If the directory tree is extremely large, how would you change your approach to avoid blocking the main event loop in Node.js?
- How would you handle circular symlink references to prevent an infinite recursion loop?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.