GeezerVison is showing github.com — path.relative(dir, dir) returns empty string · Issue #4826 · nodejs/node
path.relative(dir, dir) returns empty string #4826Labels pathIssues and PRs related to the path subsystem. Descriptionpath.relative returns empty string when its from and to arguments are identical.
> path.relative(dir, dir)
''
Since '' is not a valid path, this can blow up:
function ls (dir) {
dir = path.relative(process.cwd(), dir);
console.log(dir);
// ...
console.log(fs.readdirSync(dir));
}
This function ls works most of the time (nonexistent files and permissions aside), but not if dir points to the working directory:
> ls('.')
Error: ENOENT: no such file or directory, scandir ''
at Error (native)
at Object.fs.readdirSync (fs.js:856:18)
at ls (repl:6:16)
I find the fact that path.relative returns a valid path, except in one corner case when the two arguments are identical, rather inconvenient.
However, this is probably intentional since there is a test for this introduced in #2106. But I haven't found any reasoning for this, and the reasoning of #2106 itself is not (directly) applicable here: it's one thing to defensively treat empty strings as '.', and the other to return an empty string instead of a valid path.
Expected bahavior:
> path.relative(dir, dir)
'.' Activitysilverwind commented on Jan 24, 2016 I see what you mean, but '.' means 'current directory' to me, something which does not seem correct for me for arbitrary paths which are equal. It would only be correct when dir equals $PWD. eush77 commented on Jan 24, 2016
I see what you mean, but '.' means 'current directory' to me, something which does not seem correct for me for arbitrary paths which are equal. It would only be correct when dir equals $PWD.
That's not actually correct. Every directory has '.' and '..', and they can appear anywhere in the path:
$ cd /tmp
$ cd ../var/./opt/../../.
$ pwd
/ zeusdeux commented on Jan 24, 2016 Shouldn't path.relative(dir, dir) just return dir? silverwind commented on Jan 24, 2016
Shouldn't path.relative(dir, dir) just return dir?
No, that would imply there's another sub-directory like /dir/dir when dir = '/dir'.
That's not actually correct. Every directory has '.' and '..', and they can appear anywhere in the path:
Right, I see returning '.' has some uses, like process.chdir(path.relative(process.cwd(), 'dir')). Still, I'm uncomfortable with breaking documented behaviour. evanlucas commented on Jan 29, 2016
MetadataMetadatapathIssues and PRs related to the path subsystem. DevelopmentNo branches or pull requestsIssue actions
|