繁体   English   中英

使用路径字符串从另一个文件中查找文件的相对路径

[英]Find relative path of file from another file with path string

我试图找出一种方法来比较两个绝对(ish.)文件位置并以尽可能最短的方式从一个到另一个返回相对路径。

/*
Example 1:
..\root\folder\subFolder\myCurrent.file
..\root\folder\subFolder\img\myTarget.image

Expected result:
.\img\myTarget.image

Example 2:
..\root\folder\subFolder\myCurrent.file
..\root\folder\otherSubFolder\img\myTarget.image

Expected result:
..\otherSubFolder\img\myTarget.image

Example 3:
..\root\folder\subFolder\myCurrent.file
..\root\folder\subFolder\myTarget.image

Expected result:
myTarget.image
*/

我试图拆分到 arrays 的路径并比较长度和值,但结果完全是一团糟,我什至还没有做到......

const currentFilePath = activepath.split('\\')
const currentDir = currentFilePath[currentFilePath.indexOf(currentFilePath[currentFilePath.length - 2])];
const targetFilePath = file.path.split('\\');
const targetDir = targetFilePath[targetFilePath.indexOf(targetFilePath[targetFilePath.length - 2])];
const currentFileDepth = currentFilePath.length;
// and so on...

我想要一个体面,干净的方式来解决这个问题......

您可以拆分两条路径,然后使用.filter()从两个 arrays 获取唯一组件。 然后通过再次使用.filter()并最后使用.join('\\')来获取与第二条路径的部分相关的独特组件来创建您的结果:

 const comparePaths = (a, b) => { const a_parts = a.split('\\'); const b_parts = b.split('\\'); const arr = [...a_parts, ...b_parts]; const diffs = arr.filter(item => arr.indexOf(item) === arr.lastIndexOf(item)); let path_parts = diffs.filter(part => b_parts.includes(part)); const res = ".".repeat(path_parts.length && path_parts.length-1 || 0) +'\\'+ path_parts.join('\\'); return res; } console.log(comparePaths("..\\root\\folder\\subFolder\\myCurrent.file", "..\\root\\folder\\subFolder\\img\\myTarget.image")); console.log(comparePaths("..\\root\\folder\\subFolder\\myCurrent.file", "..\\root\\folder\\otherSubFolder\\img\\myTarget.image")); console.log(comparePaths("..\\foo\\bar\\foobar.js", "..\\foo\\bar\\foobar.js"));

对于 node.js,有一个内置的

let path = require('path').win32;

r = path.relative(
    "..\\root\\folder\\subFolder\\myCurrent.file",
    "..\\root\\folder\\subFolder\\img\\myTarget.image");

console.log(r) // ..\img\myTarget.image

对于浏览器,谷歌搜索一个端口,或者只是获取源代码,它是小而透明的。

path.relative期望第一个参数是目录,如果是文件名,则必须先获取目录:

let path = require('path').win32;

r = path.relative(
    path.dirname("..\\root\\folder\\subFolder\\myCurrent.file"),
    "..\\root\\folder\\subFolder\\img\\myTarget.image");

console.log(r) // img\myTarget.image

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM