Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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"
]);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!