url.fileURLToPath(url)


  • url <URL> | <string> 要转换为路径的文件网址字符串或网址对象。
  • 返回: <string> 完全解析的特定于平台的 Node.js 文件路径。

此函数可确保正确解码百分比编码字符,并确保跨平台有效的绝对路径字符串。

new URL('file:///C:/path/').pathname;    // 错误: /C:/path/
fileURLToPath('file:///C:/path/');       // 正确: C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname;  // 错误: /foo.txt
fileURLToPath('file://nas/foo.txt');     // 正确: \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname;    // 错误: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');       // 正确: /你好.txt (POSIX)

new URL('file:///hello world').pathname; // 错误: /hello%20world
fileURLToPath('file:///hello world');    // 正确: /hello world (POSIX)
  • url <URL> | <string> The file URL string or URL object to convert to a path.
  • Returns: <string> The fully-resolved platform-specific Node.js file path.

This function ensures the correct decodings of percent-encoded characters as well as ensuring a cross-platform valid absolute path string.

new URL('file:///C:/path/').pathname;    // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');       // Correct:   C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname;  // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt');     // Correct:   \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname;    // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');       // Correct:   /你好.txt (POSIX)

new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world');    // Correct:   /hello world (POSIX)