14

I am trying to get the difference between two path. I've come with a solution, but I am not really happy about it, even if it works. Is there a better / easier way to do this?

var firstPath =  '/my/first/path'
  , secondPath = '/my/first/path/but/longer'

// what I want to get is: '/but/longer'

// my code:
var firstPathDeconstruct = firstPath.split(path.sep)
  , secondPathDeconstruct = secondPath.split(path.sep)
  , diff = []

secondPathDeconstruct.forEach(function(chunk) {
  if (firstPathDeconstruct.indexOf(chunk) < 0) {
    diff.push(chunk)
  }
})

console.log(diff)
// output ['but', 'longer']

1 Answer 1

33

Node provides a standard function, path.relative, which does exactly this and also handles all of the various relative path edge cases that you might encounter:

From the online docs:

path.relative(from, to)

Solve the relative path from from to to.

Examples:

path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
// returns
'..\\..\\impl\\bbb'

path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
// returns
'../../impl/bbb'
1
  • I took a look at it before and for some reason thought it was not appropriate. But it is. Thanks Commented Jan 18, 2013 at 0:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.