简体   繁体   English

从Node.js中的另一个绝对路径中减去一个绝对路径

[英]Subtract one absolute path from another in Node.js

I have two paths in Node.js, eg: 我在Node.js中有两条路径,例如:

var pathOne = '/var/www/example.com/scripts';
var pathTwo = '/var/www/example.com/scripts/foo/foo.js';

How do I subtract one path from another in order to obtain a relative path? 如何从另一路径减去一条路径以获得相对路径?

subtractPath(pathTwo, pathOne); // => 'foo/foo.js'

Is there a module that does this according to all necessary URL rules or do I better use some simple string manipulations? 是否有一个模块根据所有必要的URL规则执行此操作,还是最好使用一些简单的字符串操作?

Not sure what you mean by "according to all necessary URL rules", but it seems you should be able to just use path.relative ; 不确定“按照所有必要的URL规则”是什么意思,但是似乎您应该只可以使用path.relative ;

> var pathOne = '/var/www/example.com/scripts';
> var pathTwo = '/var/www/example.com/scripts/foo/foo.js';

> path.relative(pathOne, pathTwo)
'foo/foo.js'

> path.relative(pathTwo, pathOne)
'../..'

You can do that easily with a regex: 您可以使用正则表达式轻松做到这一点:

var pathOne = /^\/your\/path\//
var pathTwo = '/your/path/appendix'.replace(pathOne, '');

This way you can force it to be at the start of the second path (using ^ ) and it won't be erased if it isn't an exact match. 这样,您可以强制它位于第二条路径的开头(使用^ ),并且如果它不完全匹配,则不会被删除。

Your example would be: 您的示例将是:

var pathOne = /^\/var\/www\/example.com\/scripts\//;
var pathTwo = '/var/www/example.com/scripts/foo/foo.js'.replace(pathOne, '');

It should return: foo/foo.js . 它应该返回: foo/foo.js

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

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