最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node path.relative returns incorrect path - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Jun 24, 2015 at 10:19 Matt DerrickMatt Derrick 5,7242 gold badges38 silver badges54 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

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.

发布评论

评论列表(0)

  1. 暂无评论