如何在nodejs文件中指定:URL,windows下的绝对路径

PA.*_*PA. 3 windows url node.js

我使用node.jsURL类来解析不同的用户URL,通常的协议没有问题,file:Linux下的URL也没有问题。

file:但是当用户尝试指定绝对路径时,我发现在Windows下有一个问题file://C:\temp\test.jpg

> u = new URL('file://C:\\temp\\test.jpg');
URL {
  href: 'file:///C:/temp/test.jpg',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/C:/temp/test.jpg',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
Run Code Online (Sandbox Code Playgroud)

你可以看到u.pathnameis '/C:/temp/test.jpg',注意前导/,使路径名无用。

在nodejs中的URL中指定Windows文件的绝对路径的正确方法是什么?

Ole*_*leg 7

https://nodejs.org/api/url.html#urlfileurltopathurl

new URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');         // Correct:   C:\path\ (Windows)
Run Code Online (Sandbox Code Playgroud)