我试图找出两条路径之间的区别。我有一个解决方案,但我对此并不满意,即使它有效。有没有更好/更简单的方法来做到这一点?
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 提供了一个标准函数 path.relative
,它正是这样做的,并且还处理您可能遇到的所有各种相对路径边缘情况:
来自 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'
关于node.js - Nodejs 两条路径的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14390337/