node.js - Nodejs 两条路径的区别

标签 node.js

我试图找出两条路径之间的区别。我有一个解决方案,但我对此并不满意,即使它有效。有没有更好/更简单的方法来做到这一点?

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

关于node.js - Nodejs 两条路径的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14390337/

相关文章:

javascript - Loopback hasOne 和 hasMany 的模型相同

node.js - Passport : Facebook Login asking for user_friends permission by default

node.js - 云发送通知功能不起作用

node.js - node.js 中的 socket.io 在 3G 移动网络上不工作

javascript - 从 Gulp-Zip 任务 foreach 循环中排除文件夹

node.js - npm 从本地位置而不是从网络安装软件包?

ios - 使用 RAW RSA 在 iOS 上加密和在 Node.js 上解密时遇到问题

node.js - Docker:开发和生产环境的最佳实践

javascript - 如何一起使用 ExpressJS、VueJS、Jade?

node.js - 允许用户仅在 firebase 上修改自己的数据