url.fileURLToPath(url[, options])


  • url <URL> | <string> 要转换为路径的文件 URL 字符串或 URL 对象。
  • options <Object>
    • windows <boolean> | <undefined> true 如果 path 应该作为 Windows 文件路径返回,false 用于 POSIX,undefined 用于系统默认。 默认值: undefined
  • 返回:<string> 完全解析的特定平台的 Node.js 文件路径。

此函数确保对百分号编码字符的正确解码,同时确保生成跨平台有效的绝对路径字符串。

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

安全注意事项:

此函数解码百分号编码的字符,包括编码的点段(%2e 作为 .%2e%2e 作为 ..),然后规范化生成的路径。这意味着编码的目录遍历序列(例如 %2e%2e)会被解码并作为实际的路径遍历进行处理,即使编码的斜杠(%2F%5C)也会被正确拒绝。

🌐 This function decodes percent-encoded characters, including encoded dot-segments (%2e as . and %2e%2e as ..), and then normalizes the resulting path. This means that encoded directory traversal sequences (such as %2e%2e) are decoded and processed as actual path traversal, even though encoded slashes (%2F, %5C) are correctly rejected.

应用不得仅依赖 fileURLToPath() 来防止目录遍历攻击。 必须始终对返回的路径值进行明确的路径验证和安全检查,以确保其在使用进行文件系统操作之前仍在预期的范围内。

import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);

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)const { fileURLToPath } = require('node:url');
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)