path.normalize(path)


path.normalize() 方法规范化给定的 path,解析 '..''.' 片段。

¥The path.normalize() method normalizes the given path, resolving '..' and '.' segments.

当找到多个连续的路径片段分隔符(例如 POSIX 上的 / 和 Windows 上的 \/)时,则它们将被平台特定路径片段分隔符(POSIX 上的 / 和 Windows 上的 \)的单个实例替换。保留尾随的分隔符。

¥When multiple, sequential path segment separation characters are found (e.g. / on POSIX and either \ or / on Windows), they are replaced by a single instance of the platform-specific path segment separator (/ on POSIX and \ on Windows). Trailing separators are preserved.

如果 path 是零长度字符串,则返回 '.',表示当前工作目录。

¥If the path is a zero-length string, '.' is returned, representing the current working directory.

在 POSIX 上,此函数应用的规范化类型并不严格遵守 POSIX 规范。例如,此函数将用单个斜杠替换两个前导正斜杠,就好像它是常规绝对路径一样,而一些 POSIX 系统为恰好以两个正斜杠开头的路径分配特殊含义。类似地,此函数执行的其他替换(例如删除 .. 段)可能会改变底层系统解析路径的方式。

¥On POSIX, the types of normalization applied by this function do not strictly adhere to the POSIX specification. For example, this function will replace two leading forward slashes with a single slash as if it was a regular absolute path, whereas a few POSIX systems assign special meaning to paths beginning with exactly two forward slashes. Similarly, other substitutions performed by this function, such as removing .. segments, may change how the underlying system resolves the path.

例如,在 POSIX 上:

¥For example, on POSIX:

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

在 Windows 上:

¥On Windows:

path.normalize('C:\\temp\\\\foo\\bar\\..\\');
// Returns: 'C:\\temp\\foo\\' 

由于 Windows 识别多个路径分隔符,两个分隔符都将被 Windows 首选分隔符 (\) 的实例替换:

¥Since Windows recognizes multiple path separators, both separators will be replaced by instances of the Windows preferred separator (\):

path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');
// Returns: 'C:\\temp\\foo\\bar' 

如果 path 不是字符串,则抛出 TypeError

¥A TypeError is thrown if path is not a string.