url.pathToFileURL(path[, options])


版本历史
版本变更
v22.1.0, v20.13.0

options 参数现在可用于确定如何返回 path 值。

v10.12.0

新增于: v10.12.0

  • path <string> 要转换为文件网址的路径。

    \path <string> The path to convert to a File URL.

  • options <Object>

    • windows <boolean> | <undefined> 如果 path 应该被视为 Windows 文件路径,则为 true;对于 posix,则为 false;对于系统默认值,则为 undefined。默认值:undefined

      \windows <boolean> | <undefined> true if the path should be treated as a windows filepath, false for posix, and undefined for the system default. Default: undefined.

  • 返回:<URL> 文件网址对象。

    \Returns: <URL> The file URL object.

该函数确保 path 被绝对解析,并且在转换为文件网址时正确编码网址控制字符。

\This function ensures that path is resolved absolutely, and that the URL control characters are correctly encoded when converting into a File URL.

import { pathToFileURL } from 'node:url';
new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1
pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)
new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)const { pathToFileURL } = require('node:url');
new URL(__filename); // Incorrect: throws (POSIX)
new URL(__filename); // Incorrect: C:\... (Windows)
pathToFileURL(__filename); // Correct: file:///... (POSIX)
pathToFileURL(__filename); // Correct: file:///C:/... (Windows)
new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1
pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)
new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)

AltStyle によって変換されたページ (->オリジナル) /