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

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

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)); // '/';
阅读 2.8k
2 个回答
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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题