Skip to content

Latest commit

History

History
128 lines (97 loc) 路 5.15 KB

File metadata and controls

128 lines (97 loc) 路 5.15 KB

馃搨 File paths

Path delimiters

While / is used as a file path delimiter on Unix (/file/to/path), \ is used on Windows instead (\file\to\path).

The path delimiter can be retrieved with path.sep.

Windows actually allows using or mixing in / delimiters in file paths sometimes, but not always so this should not be relied on.

Absolute paths

Absolute paths always start with / on Unix, but on Windows they can take many shapes:

  • \: the current drive.
  • C:\: a specific drive (here C:). This can also be used with relative paths like C:file\to\path.
  • \\HOST\: UNC path, for remote hosts.
  • \\?\: allows to overcome file path length limit of 260 characters. Those can be produced in Node.js with path.toNamespacedPath().
  • \\.\: device path.

Node.js behavior

In arguments

When file paths are used as arguments to Node.js core methods:

  • only Unix paths are allowed on Unix.
  • both Unix and Windows paths are allowed on Windows (including mixed).

This includes arguments to require(path), import(path), import from "path", fs.*(path) methods, path.*() methods or process.chdir(path).

In return values

When file paths are returned by Node.js core methods:

  • Unix paths are returned on Unix.
  • Windows paths are returned on Windows.

This includes the return values of path.*() methods, process.cwd(), os.homedir(), os.tmpdir(), os.devNull() or the value of __dirname, process.argv and process.execPath.

Exceptions:

In a terminal or file

Outside of Node.js, i.e. when the path is input from (or output to) the terminal or a file, its syntax is OS-specific.

Conclusion

  • if a path must be output outside of Node.js (e.g. terminal or file), path.normalize() should be used to make it OS-specific.
  • if a path comes from outside of Node.js or from a core method, it will be OS-specific. However all Node.js core methods will properly handle it.
  • in all other cases using Unix paths will just work.

import.meta.url

ES modules require using import.meta.url, import.meta.filename and import.meta.dirname instead of __filename and __dirname.

import.meta.url is a file:///... URL. For backward compatibility, you should:

Summary

Use path.normalize() when writing a file path to a terminal or file. Otherwise use Unix paths (slashes).

Use url.fileURLToPath() with import.meta.url.


Next (馃搨 Filenames)
Previous (馃搨 Directory locations)
Top