DEV Community

Discussion on: Loading a directory as a tree structure in Node

Collapse
 
_aasman_ profile image
Himanshu Jha

Hello Sir, thanks for this wonderful article. Can you please throw some light on how we can add a filter to exclude files of certain extension from our tree?

Collapse
 
peaonunes profile image
Rafael Nunes

Hello! Sorry for the delay.
I believe you could use another Node API to solve that. The path API allows you to find the extension of a file given its path.

import path from 'path';

function buildTree(rootPath: string) {
  const BLOCKED_EXTENSIONS = ['.txt']
  const root = new TreeNode(rootPath);

  const stack = [root];

  while (stack.length) {
    const currentNode = stack.pop();

    if (currentNode) {
      const children = fs.readdirSync(currentNode.path);

      for (let child of children) {
        const childPath = `${currentNode.path}/${child}`;
        const childNode = new TreeNode(childPath);

        const isDirectory = fs.statSync(childNode.path).isDirectory();
        const extension = path.extname(childNode.path);
        const isFileBockled = BLOCKED_EXTENSIONS.includes(extension);

        if (!isFileBockled) {
          currentNode.children.push(childNode);
        }

        if (isDirectory && !isFileBockled) {
          stack.push(childNode);
        }
      }
    }
  }

  return root;
}
Enter fullscreen mode Exit fullscreen mode

We could do something like the snippet above, you can have a const with the blocked extensions or you could have a const with the only ones you allow. Having that combined with path.extname we can filter out any file based on their extension.