Home > OS >  Trouble understanding path.relative
Trouble understanding path.relative

Time:04-11

You can see in the code below that the parent-parent folder of p1 is a sibling of p2.

> p1 = "/Users/Shared/dev/new-slice-script/src/test/dest/src/reducers/testSlice.js"
> p2 = "/Users/Shared/dev/new-slice-script/src/test/dest/combineReducers.js"
> path.relative(p2, p1)
'../src/reducers/testSlice.js'

So why isn't the final statement './src/reducers/testSlice.js' (one leading period) instead of '../src/reducers/testSlice.js' (two leading periods)?

Wouldn't the path it gives, '../src/reducers/testSlice.js', resolve to test/src/reducers/testSlice.js?

(I know there's not much content to this question but I think the code required to understand the question is all there. If you're going to downvote or vote to close please add constructive criticism.)

CodePudding user response:

path.relative is based on the cwd (current working directory) of each path, which is the final directory of the path.

In this case the final directory in the path is “combineReducers.js” since this is technically a valid directory name. This is why you are seeing the “../“ prefix the result instead of “./“, and also why you see testSlice.js in the output path (testSlice.js is also being treated as a directory)

/Users/Shared/dev/new-slice-script/src/test/dest/combineReducers.js/
#..
/Users/Shared/dev/new-slice-script/src/test/dest/
#../src
/Users/Shared/dev/new-slice-script/src/test/dest/src/
#../src/reducers
/Users/Shared/dev/new-slice-script/src/test/dest/src/reducers/
#../src/reducers/testSlice.js
/Users/Shared/dev/new-slice-script/src/test/dest/src/reducers/testSlice.js/

CodePudding user response:

So why isn't the final statement './src/reducers/testSlice.js' (one leading period) instead of '../src/reducers/testSlice.js' (two leading periods)?

Because the first argument to path.relative is supposed to be the directory that's to be interpreted as the "base" directory from which a relative path to the source is generated. For example, path.relative('/Users/mike', '/Users/greg') will result in ../greg, which is what you expect, right?

Now, you specified a file and not a directory, but node.js can't know that. Assuming combineReducers.js is a directory, the result makes total sense.

To avoid that, call path.dirname on the path first, so the base path will become /Users/Shared/dev/new-slice-script/src/test/dest:

> p1 = "/Users/Shared/dev/new-slice-script/src/test/dest/src/reducers/testSlice.js"
> p2 = "/Users/Shared/dev/new-slice-script/src/test/dest/combineReducers.js"
> path.relative(path.dirname(p2), p1)
'src/reducers/testSlice.js'
  • Related