将绝对path转换为相对path

在Node中工作我需要将我的请求path转换为相对path,以便将其放入一些具有不同文件夹结构的模板中。

基本上,如果我从path“/ foo / bar”开始,我需要我的相对path是“..”如果是“/ foo / bar / baz”,我需要它是“../ ..”

我写了一对function来做到这一点:

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

不知道这是最好的方法,或者如果可能用String.replace中的正则expression式来做到这一点?

编辑

我应该指出这是因为我可以将所有东西渲染为静态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) ../ ../../