两个path之间的Nodejs差异

我试图弄清两条path的区别。 我已经提出了一个解决scheme,但即使它工作,我也不是很高兴。 有没有更好/更简单的方法来做到这一点?

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

节点提供了一个标准函数path.relative ,它完成了这个工作,还处理所有可能遇到的各种相对path边界情况:

从在线文档 :

path.relative(from, to)

解决from到的相对path。

例子:

 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' 

这可能工作。 虽然它依赖于它知道哪一个是另一个子集的事实,并且假设情况将是相同的。

 var diff = secondPath.substring(firstPath.length);