簡體   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