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)); // '/';
阅读 3k
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

推荐问题