简体   繁体   English

将绝对路径转换为相对路径

[英]Converting an absolute path to a relative path

Working in Node I need to convert my request path into a relative path so I can drop it into some templates that have a different folder structure. 在Node中工作我需要将我的请求路径转换为相对路径,这样我就可以将它放入一些具有不同文件夹结构的模板中。

Basically if I start with the path "/foo/bar" I need my relative path to be ".." If it's "/foo/bar/baz" I need it to be "../.." 基本上如果我从路径“/ foo / bar”开始,我需要我的相对路径是“..”如果它是“/ foo / bar / baz”我需要它是“../ ..”

I wrote a pair of functions to do this: 我写了一对函数来做到这一点:

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

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

Not sure if this is the best approach or if it's possible to do it with a regular expression in String.replace somehow? 不确定这是否是最好的方法,或者是否可以以某种方式在String.replace中使用正则表达式?

edit 编辑

I should point out this is so I can render everything as static HTML, zip up the whole project, and send it to someone who doesn't have access to a web server. 我应该指出这是因为我可以将所有内容呈现为静态HTML,压缩整个项目,并将其发送给无法访问Web服务器的人。 See my first comment. 看我的第一条评论。

If I understand you question correct you can use path.relative(from, to) 如果我理解你的问题是正确的,你可以使用path.relative(from, to)

Documentation 文档

Example: 例:

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

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

This might need some tuning but it should work: 这可能需要一些调整,但它应该工作:

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

Result: 结果:

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

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

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