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']
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
toto
.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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With