'How to print file path with directory Indentation Nodejs

Printing file path with directory indentation. Input will be

[
  "/root/html/file/a.html",
  "/root/html/image/a.jpg",
  "/root/html/file/b.html",
  "/tmp/c.log"
]

Output needs to be like following,

- root
  - html 
     - file
       - a.html
       - b.html
     - image
       - a.jpg
- tmp
  - c.log

I couldn't find any solution. I guess it will be a recursive call with a tree structure. Any help would be appreciated.



Solution 1:[1]

You could map each file path of your input data into a simple tree-map structure and then recursively print this structure. Something like this (not tested and might still need to handle edge cases):

function processData(data) {
    const separator = "/";
    const tree = {};
    data.forEach(element => mapPathToTree(tree, element.split(separator).filter(part => part)));
    printTree(tree, 0);
}

function mapPathToTree(tree, pathParts) {
    if (pathParts && pathParts.length <= 1) {
        tree[pathParts[0]] = {};
        return;
    }
    const currPart = pathParts[0];
    let subTree = tree[currPart];
    if (!subTree) {
        subTree = {};
        tree[currPart] = subTree;
    }
    mapPathToTree(subTree, pathParts.slice(1));
}

function printTree(subTree, level) {
    for (const key in subTree) {
        console.log(" ".repeat(level).concat("- ").concat(key));
        printTree(subTree[key], level + 1);
    }
}

processData([
    "/root/html/file/a.html",
    "/root/html/image/a.jpg",
    "/root/html/file/b.html",
    "/tmp/c.log"
]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eol