Antonio Pavicevac-Ortiz
Antonio Pavicevac-Ortiz

Reputation: 7729

Node.js path.join() ignoring parameter

According to the documentation:

The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.

Zero-length path segments are ignored. If the joined path string is a zero-length string then '.' will be returned, representing the current working directory.

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

path.join('foo', {}, 'bar');
// Throws 'TypeError: Path must be a string. Received {}'

A TypeError is thrown if any of the path segments is not a string.

Am I missing something? Why is:

 path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
    // Returns: '/foo/bar/baz/asdf'

Ignoring 'quux' and '..' ?

They're are not zero length?

Even played around in the REPL (see screenshot)

enter image description here

Upvotes: 1

Views: 1603

Answers (3)

Ronin
Ronin

Reputation: 81

Path.join isn't ignoring the last two parameters. Path.join takes the parameters you input and outputs a normalized path in string format.

So what's actually going on here is that it's constructing your string to form a path left to right, /foo/bar/baz/asdf/quux/, and the last parameter (..) is instructing path.join to 'go back a directory'. So your final result will be: /foo/bar/baz/asdf/

Upvotes: 6

HumbleOne
HumbleOne

Reputation: 170

  1. With regard to path.join('foo', {}, 'bar');, {} represents an empty object, not a string (empty or not). Therefore, it is an invalid parameter for path.join().
  2. With regard to path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');, .. refers to a parent directory. Through experimentation in a terminal, you will find that...

    /foo/bar/baz/asdf/quux/.. is equivalent to /foo/bar/baz/asdf

Upvotes: -1

Golo Roden
Golo Roden

Reputation: 150614

Part 1: what do you expect to happen when you provide an object instead of a string? To cut it short: It doesn’t make sense and hence doesn’t work.

Part 2: since .. means „up one directory“, this clears the last part of the path, hence it seems to not have any effect. Actually, it doesn’t get ignored - it’s just that the last two parameters clear each other.

Upvotes: 0

Related Questions