Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs difference between two paths

Tags:

node.js

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']
like image 930
romainberger Avatar asked Jan 17 '13 23:01

romainberger


1 Answers

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'
like image 199
Phil Booth Avatar answered Oct 26 '22 17:10

Phil Booth