romainberger
romainberger

Reputation: 4558

Nodejs difference between two paths

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']

Upvotes: 15

Views: 7537

Answers (1)

Phil Booth
Phil Booth

Reputation: 4913

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'

Upvotes: 34

Related Questions