Uncaught TypeError: URL is not a constructor using WHATWG URL object support for electron

Uncaught TypeError: URL is not a constructor using WHATWG URL object support for electron

我正在尝试使用 WHATWG URL 对象支持读取文件 here

我收到此错误:未捕获的类型错误:URL 不是构造函数

这是我的代码:

var fs = require("fs");                                     
const { URL } = require('url');
var dbPath = 'file://192.168.5.2/db/db.sqlite';
const fileUrl = new URL(dbPath);

我遇到了同样的问题,然后我查看了 url 模块并找到了解决方案

对于 Node V6 使用,

const URL = require('url').Url;

const { Url } = require('url'); 

如果你查看该模块,它导出了 5 个方法,其中一个是 Url,所以如果你需要访问 Url,你可以使用这两种方法中的任何一种

您使用的是 Node 6 而不是 Node 8 吗?

节点 6

const url = require('url');
const myUrl = url.parse('http://example.com');
const myUrlString = url.format(myUrl);

https://nodejs.org/dist/latest-v6.x/docs/api/url.html#url_url

节点 8

const { URL } = require('url');
const myUrl = new URL('http://example.com');
const myUrlString = myUrl.toString();

https://nodejs.org/dist/latest-v8.x/docs/api/url.html#url_url

您取出此信息的文档适用于版本 8.4.0node

如果它对您不起作用,则意味着您的 node6.11.2 版本。然后,只需更改 URL -

的字母大小写
const { Url } = require('url');
const myUrl = new Url('http://example.com'); 

因为 url 模块导出 Url,而不是 URL

Node v10.0.0 及更高版本(当前为 Node v16.x)

URL Class

v10.0.0 | The class is now available on the global object.

如此处所述:Node.js Documentation - Class: URL

所以这应该在没有 require('url') 的情况下工作:

const myUrl = new URL('http://example.com');