-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
479910f
commit 2b9f5a3
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import { promises as fs } from 'fs'; | ||
import { join } from 'path'; | ||
|
||
/** | ||
* @typedef {object} DirTreeNode | ||
* | ||
* @property {string} name The name of the node. | ||
* @property {Array<DirTreeNode>} [children] The array of child nodes if the node is a directory. This is a recursive structure. | ||
*/ | ||
|
||
/** | ||
* Asynchronously retrieves the directory tree structure. | ||
* | ||
* @async | ||
* @param {string} dirPath The path of the directory. | ||
* @returns {Promise<Array<DirTreeNode>>} A promise that resolves to an array of `DirTreeNode`. | ||
* | ||
* @example | ||
* // Get the directory tree structure | ||
* const dirTree = await getDirTree('/path/to/dir'); | ||
* console.log(dirTree); | ||
*/ | ||
export async function getDirTree(dirPath) { | ||
// `readdir` automatically throws an error when `dirPath` is not a directory. | ||
const dirents = await fs.readdir(dirPath, { withFileTypes: true }); | ||
|
||
return await Promise.all( | ||
dirents.map(async dirent => ({ | ||
name: dirent.name, | ||
...(dirent.isDirectory() | ||
? { children: await getDirTree(join(dirPath, dirent.name)) } | ||
: {}), | ||
})), | ||
); | ||
} | ||
|
||
/** | ||
* Checks if a `DirTreeNode` is a directory. | ||
* | ||
* @param {DirTreeNode} dirTreeNode The `DirTreeNode` object. | ||
* @returns {boolean} `true` if the node is a directory. otherwise, `false`. | ||
* | ||
* @example | ||
* // Check if a node is a directory | ||
* const isDir = isDirectory({ name: 'folder', children: [...] }); | ||
* console.log(isDir); // true | ||
*/ | ||
export function isDirectory(dirTreeNode) { | ||
return Boolean(dirTreeNode.children); | ||
} |