url.fileURLToPath(url[, options])
版本历史
| 版本 | 变更 |
|---|---|
| v22.1.0, v20.13.0 |
|
| v10.12.0 | 新增于: v10.12.0 |
-
url<URL> | <string> 要转换为路径的文件网址字符串或网址对象。\
url<URL> | <string> The file URL string or URL object to convert to a path. -
options<Object>-
windows<boolean> | <undefined> 如果path应作为 Windows 文件路径返回,则为true;对于 posix,则返回false;对于系统默认值,则返回undefined。默认值:undefined。\
windows<boolean> | <undefined>trueif thepathshould be return as a windows filepath,falsefor posix, andundefinedfor the system default. Default:undefined.
-
-
返回:<string> 完全解析的特定于平台的 Node.js 文件路径。
\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.
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)