Search code examples
javascriptnode.jspathfilepath

Node path.relative returns incorrect path


I'm pretty sure I must be wrong but in Node, path.relative seems to output the wrong directory, or at least one I wasn't expecting:

> path.relative('a/file.js', 'a/file.css')
> '../file.css'

However I would expect the result to be something like:

> './file.css'

In essence I am trying to compute the difference in the two paths in order for one file to require the other and ../file.css is obviously wrong for my require as both the files are in the a directory. The output suggests that file.css is in the parent directory.

What am I missing?


Solution

  • As far as I can tell, path.relative() expects a folder rather than a file as its first argument. This works:

    path.relative('a', 'a/file.css')
    > 'file.css'
    

    Here's the source code for path.relative: https://github.com/joyent/node/blob/master/lib/path.js#L504-L530 https://github.com/joyent/node/blob/master/lib/path.js#L265-L304

    (Note: in case the line numbers change in the future, here's a link to the source as it is at the time I'm writing this: https://github.com/nodejs/node-v0.x-archive/blob/94beb2985b4cb25e592a9ccc226f6c824a81e510/lib/path.js)

    As you can see there, the paths are split by the slashes in them and it simply compares the number of parts, so it doesn't work if you pass a file instead of a folder as the from argument.