Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
Matt Derrick Avatar asked Jun 24 '15 10:06

Matt Derrick


People also ask

What is path relative?

A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.

What is path resolve?

The path. resolve() method is used to resolve a sequence of path-segments to an absolute path. It works by processing the sequence of paths from right to left, prepending each of the paths until the absolute path is created. The resulting path is normalized and trailing slashes are removed as required.

What is path in nodejs?

The Path module provides a way of working with directories and file paths.


1 Answers

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.

like image 150
Matt Browne Avatar answered Sep 23 '22 10:09

Matt Browne