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)); // '/';

回答

最长公共前缀

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

以上是 nodejs如何获取多个文件路径的共同根路径? 的全部内容, 来源链接: utcz.com/a/26708.html

回到顶部