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?
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.
The path. basename() method returns the filename part of a file path.
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.
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)
'../..'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With