特定于平台的注意事项
¥Platform-specific considerations
在 Windows 上,带有主机名的 file:
<URL> 转换为 UNC 路径,而带有驱动器号的 file:
<URL> 转换为本地绝对路径。file:
<URL> 没有主机名也没有盘符会报错:
¥On Windows, file:
<URL> with a host name convert to UNC paths, while file:
<URL> with drive letters convert to local absolute paths. file:
<URL>
with no host name and no drive letter will result in an error:
import { readFileSync } from 'node:fs';
// On Windows :
// - WHATWG file URLs with hostname convert to UNC path
// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
readFileSync(new URL('file://hostname/p/a/t/h/file'));
// - WHATWG file URLs with drive letters convert to absolute path
// file:///C:/tmp/hello => C:\tmp\hello
readFileSync(new URL('file:///C:/tmp/hello'));
// - WHATWG file URLs without hostname must have a drive letters
readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
readFileSync(new URL('file:///c/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
file:
<URL> 带驱动器号的必须在驱动器号后面使用 :
作为分隔符。使用其他分隔符会导致错误。
¥file:
<URL> with drive letters must use :
as a separator just after
the drive letter. Using another separator will result in an error.
在所有其他平台上,不支持具有主机名的 file:
<URL> 并将导致错误:
¥On all other platforms, file:
<URL> with a host name are unsupported and
will result in an error:
import { readFileSync } from 'node:fs';
// On other platforms:
// - WHATWG file URLs with hostname are unsupported
// file://hostname/p/a/t/h/file => throw!
readFileSync(new URL('file://hostname/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute
// - WHATWG file URLs convert to absolute path
// file:///tmp/hello => /tmp/hello
readFileSync(new URL('file:///tmp/hello'));
具有编码斜杠字符的 file:
<URL> 在所有平台上都将导致错误:
¥A file:
<URL> having encoded slash characters will result in an error on all
platforms:
import { readFileSync } from 'node:fs';
// On Windows
readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */
// On POSIX
readFileSync(new URL('file:///p/a/t/h/%2F'));
readFileSync(new URL('file:///p/a/t/h/%2f'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
/ characters */
在 Windows 上,具有编码反斜杠的 file:
<URL> 将导致错误:
¥On Windows, file:
<URL> having encoded backslash will result in an error:
import { readFileSync } from 'node:fs';
// On Windows
readFileSync(new URL('file:///C:/path/%5C'));
readFileSync(new URL('file:///C:/path/%5c'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */