Skip to content

path.relative(dir, dir) returns empty string #4826

Closed
@eush77

Description

@eush77

path.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)
'.'

Metadata

Metadata

Assignees

No one assigned

    Labels

    pathIssues and PRs related to the path subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions