Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract one absolute path from another in Node.js

I have two paths in Node.js, e.g.:

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?

like image 601
Slava Fomin II Avatar asked Jan 17 '16 08:01

Slava Fomin II


People also ask

How do you find the absolute path of a relative path in node?

Use the path. resolve() method to get an absolute path of a file from a relative path in Node. js, e.g. path. resolve('./some-file.

What is path Basename?

The path. basename() method returns the filename part of a file path.

How do you create a relative path in NodeJS?

relative() Method. The path. relative() method is used to find the relative path from a given path to another path based on the current working directory. If both the given paths are the same, it would resolve to a zero-length string.


1 Answers

Not sure what you mean by "according to all necessary URL rules", but it seems you should be able to just use 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)
'../..'
like image 125
Joachim Isaksson Avatar answered Oct 05 '22 07:10

Joachim Isaksson