簡體   English   中英

將絕對路徑轉換為相對路徑

[英]Converting an absolute path to a relative path

在Node中工作我需要將我的請求路徑轉換為相對路徑,這樣我就可以將它放入一些具有不同文件夾結構的模板中。

基本上如果我從路徑“/ foo / bar”開始,我需要我的相對路徑是“..”如果它是“/ foo / bar / baz”我需要它是“../ ..”

我寫了一對函數來做到這一點:

function splitPath(path) {
    return path.split('/').map(dots).slice(2).join('/');
}

function dots() {
    return '..';
}

不確定這是否是最好的方法,或者是否可以以某種方式在String.replace中使用正則表達式?

編輯

我應該指出這是因為我可以將所有內容呈現為靜態HTML,壓縮整個項目,並將其發送給無法訪問Web服務器的人。 看我的第一條評論。

如果我理解你的問題是正確的,你可以使用path.relative(from, to)

文檔

例:

var path = require('path');
console.log(path.relative('/foo/bar/baz', '/foo'));

Node.js具有用於此目的的本機方法: path.relative(from,to)

這可能需要一些調整,但它應該工作:

function getPathRelation(position, basePath, input) {
    var basePathR = basePath.split("/");
    var inputR = input.split("/");
    var output = "";
    for(c=0; c < inputR.length; c++) {
       if(c < position) continue;
       if(basePathR.length <= c) output = "../" + output;
       if(inputR[c] == basePathR[c]) output += inputR[c] + "/";
    }

    return output;
}

var basePath ="/foo"
var position = 2;
var input = "/foo";
console.log(getPathRelation(position,basePath,input));
var input = "/foo/bar";
console.log(getPathRelation(position,basePath,input));
var input = "/foo/bar/baz";
console.log(getPathRelation(position,basePath,input));

結果:

(an empty string)    
../    
../../

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM