Slava Fomin II
Slava Fomin II

Reputation: 28661

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?

Upvotes: 9

Views: 2599

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

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)
'../..'

Upvotes: 25

skypjack
skypjack

Reputation: 50568

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.

Upvotes: 0

Related Questions