Introduction to Dree: Efficient Directory Tree Parsing in Node.js
The dree
library is a powerful tool in the Node.js ecosystem designed to parse and represent directory structures with ease. Whether you are developing file managers, directory explorers, or simply needing to manipulate file paths programmatically, dree
offers a comprehensive set of APIs to meet your needs.
Key APIs of Dree
1. parseTree()
The parseTree
function is the core utility, parsing a directory and returning its structure as a JSON object.
const { parseTree } = require('dree'); const tree = parseTree('/your/directory/path'); console.log(tree);
2. scanAsync()
The scanAsync
function performs an asynchronous scan of a directory.
const { scanAsync } = require('dree'); (async () => { const tree = await scanAsync('/your/directory/path'); console.log(tree); })();
3. parse()
The parse
function parses a single file or directory and provides different levels of details.
const { parse } = require('dree'); const file = parse('/your/file/path'); console.log(file);
4. scan()
The scan
function is a synchronous directory scanner.
const { scan } = require('dree'); const tree = scan('/your/directory/path'); console.log(tree);
5. parseWithOptions()
The parseWithOptions
function allows for parsing with additional custom options.
const { parseWithOptions } = require('dree'); const options = { symbolicLinks: true }; const file = parseWithOptions('/your/file/path', options); console.log(file);
Sample Application Using Dree
Let’s build a sample application that lists all files in a directory along with their sizes and last modified times.
const { parseTree } = require('dree'); const path = require('path'); const directoryPath = '/your/directory/path'; const tree = parseTree(directoryPath, { exclude: /node_modules/, stat: true }); function printTree(tree, indent = 0) { const indentation = ' '.repeat(indent * 2); console.log(`${indentation}${tree.name} - ${tree.size} bytes - Last modified: ${tree.mtime}`); if (tree.children) { tree.children.forEach(child => printTree(child, indent + 1)); } } printTree(tree);
Run this script to get a well-formatted list of all files and directories along with their sizes and last modification times.
Hash: b8df52705af995e05da19a13882d517dedfc88d10ba8b17bb581a6ca0a1f615d