我试图找到两条路径之间的差异.我已经找到了一个解决方案,但我并不高兴,即使它有效.有没有更好/更简单的方法来做到这一点?
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']
Run Code Online (Sandbox Code Playgroud)
Phi*_*oth 20
Node提供了一个标准函数,path.relative它正是这样做的,并且还处理了您可能遇到的所有各种相对路径边缘情况:
来自在线文档:
path.relative(from, to)解决从相对路径
from来to.例子:
Run Code Online (Sandbox Code Playgroud)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'
| 归档时间: |
|
| 查看次数: |
3656 次 |
| 最近记录: |