Windows 与 POSIX


path 模块会因操作系统的差异而不同。 比如在 Windows 上,path 模块会认为使用的是 Windows 风格的路径。

例如,对文件路径 C:\temp\myfile.html 使用 path.basename(),在 POSIX 上与在 Windows 上会产生不同的结果:

在 POSIX 上:

path.basename('C:\\temp\\myfile.html');
// 返回: 'C:\\temp\\myfile.html'

在 Windows 上:

path.basename('C:\\temp\\myfile.html');
// 返回: 'myfile.html'

要想在任何操作系统上处理 Windows 文件路径时获得一致的结果,可以使用 path.win32

在 POSIX 和 Windows 上:

path.win32.basename('C:\\temp\\myfile.html');
// 返回: 'myfile.html'

如果想在任何操作系统上处理 POSIX 文件路径时获得一致的结果,则使用 path.posix

在 POSIX 和 Windows 上:

path.posix.basename('/tmp/myfile.html');
// 返回: 'myfile.html'

The default operation of the path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the path module will assume that Windows-style paths are being used.

So using path.basename() might yield different results on POSIX and Windows:

On POSIX:

path.basename('C:\\temp\\myfile.html');
// Returns: 'C:\\temp\\myfile.html'

On Windows:

path.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html'

To achieve consistent results when working with Windows file paths on any operating system, use path.win32:

On POSIX and Windows:

path.win32.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html'

To achieve consistent results when working with POSIX file paths on any operating system, use path.posix:

On POSIX and Windows:

path.posix.basename('/tmp/myfile.html');
// Returns: 'myfile.html'

On Windows Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example, path.resolve('c:\\') can potentially return a different result than path.resolve('c:'). For more information, see this MSDN page.