nodejs如何获取多个文件路径的共同根路径?

发布于 2022-09-12 03:21:02 字数 363 浏览 8 评论 0

有没快捷的方式可以获取多个文件路径的共同根路径,如下:

let file1 = '/a/b/c.txt';
let file2 = '/a/b/d.txt';
let file3 = '/a/e';
let file4 = '/f/e';

console.log(getCommonPath(file1, file2, file3)); // '/a/';
console.log(getCommonPath(file1, file2)); // '/a/b/';
console.log(getCommonPath(file1)); // '/a/b/';
console.log(getCommonPath(file1, file4)); // '/';

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

勿忘初心 2022-09-19 03:21:02
getCommonPath = function getCommonPath (path1 = '', path2 = '', ...rest) {
  path1 = path1.replace(/[^\/]+$/, '')
  if (!path2) return path1
  path2 = path2.replace(/[^\/]+$/, '')
  
  let base = ''
  for (let i = 0; i < path1.length && i < path2.length; i++) {
    if (path1[i] === path2[i]) {
      base += path2[i]
    } else {
      break
    }
  }
  if (rest.length) {
    return getCommonPath(base, ...rest)
  }
  return base
};

image.png

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文