url.pathToFileURL(path)
该函数确保 path 被绝对解析,并且在转换为文件网址时正确编码网址控制字符。
import { pathToFileURL } from 'node:url';
new URL('/foo#1', 'file:');           // 错误: file:///foo#1
pathToFileURL('/foo#1');              // 正确: file:///foo%231 (POSIX)
new URL('/some/path%.c', 'file:');    // 错误: file:///some/path%.c
pathToFileURL('/some/path%.c');       // 正确: file:///some/path%25.c (POSIX)const { pathToFileURL } = require('node:url');
new URL(__filename);                  // 错误: 抛出错误 (POSIX)
new URL(__filename);                  // 错误: C:\... (Windows)
pathToFileURL(__filename);            // 正确: file:///... (POSIX)
pathToFileURL(__filename);            // 正确: file:///C:/... (Windows)
new URL('/foo#1', 'file:');           // 错误: file:///foo#1
pathToFileURL('/foo#1');              // 正确: file:///foo%231 (POSIX)
new URL('/some/path%.c', 'file:');    // 错误: file:///some/path%.c
pathToFileURL('/some/path%.c');       // 正确: file:///some/path%25.c (POSIX)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)