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

192
Views
Walking up a file's path backwords

Starting with a string that has the full path of a file I threw together this function to walk up the directories of the file's path backwards. It works, but my gut tells me I'm overcooking the plumbing and I decided that this was a good opportunity for a learning experience. How would I refactor this to be more succinct?

const path = require('path')

function walk(file) {
    let dir = path.dirname(file)
    let arr = dir.split('/').filter(e => e).reverse()
    let paths = []
    for(let i = arr.length; i >= 0; i--) {
        let sub = arr.slice(i)
        paths.push(sub.reverse().join('/'))
    }
    paths = paths.filter(e => e).reverse()
    paths.forEach(path => {
        console.log('/' + path)
    })
}

walk('/D0/D1/D2/D3/foo.bar')
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Another simpler recursive version:

const path = require('path');

function walk(start) {
  const dir = path.dirname(start)
  console.log(dir);
  if (dir !== '/') {
    walk(dir);
  }
}

walk('/D0/D1/D2/D3/foo.bar');

It will output:

"/D0/D1/D2/D3"
"/D0/D1/D2"
"/D0/D1"
"/D0"
"/"
about 4 years ago · Juan Pablo Isaza Report

0

You could use a recursive function.

I let you here an example

const path = require('path')

function walk(file) {
    let dir = path.dirname(file)
    walkRecursively(dir.split('/'))
}

function walkRecursively(dirs) {
  if(dirs.length < 2) {
    return;
  }
  console.log(path.join(dirs))
  const nextDirs = dirs.slice(0, -1)
  walkRecursively(nextDirs)
}

walk('/D0/D1/D2/D3/foo.bar')
about 4 years ago · Juan Pablo Isaza Report

0

you can do something like this

function walk(file) {
    const path = file.split('/').filter(e => e).slice(0, -1)
    const result = path.reduce((res, p, i) => {
      return [
        ...res,
        `${res[i - 1] || ''}/${p}`
      ]
    }, []).reverse()
    console.log(result)
}

walk('/D0/D1/D2/D3/foo.bar')

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!