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



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

但是当用户试图指定像file://C:temptest.jpg这样的绝对路径时,我发现了file:在窗口下的问题

> 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: ''
}

您可以看到u.pathname'/C:/temp/test.jpg',注意前面的/,使路径名无用。

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

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

new URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');         // Correct:   C:path (Windows)