node.js 未捕获的类型错误:URL 不是使用 WHATWG URL 对象支持电子的构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44738065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:18:51  来源:igfitidea点击:

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

node.jsurlelectronfs

提问by Ana Houa

I am trying to read a file using WHATWG URL object support here

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

and I am getting this error: Uncaught TypeError: URL is not a constructor

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

here is my code:

这是我的代码:

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

回答by Kowsalya

I faced the same issue, then I looked into the url module and found a solution

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

For Node V6use,

对于 Node V6使用,

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

or

或者

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

If you look into the module, it exports 5 methods one of which is Url, so if you need to access Url, you can use either of the two methods

如果您查看该模块,它会导出 5 个方法,其中一个是 Url,因此如果您需要访问 Url,则可以使用这两种方法之一

回答by jrc

Are you using Node 6 instead of Node 8?

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

Node 6

节点 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

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

Node 8

节点 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

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

回答by Tal Z

Node v10.0.0 and newer (currently Node v14.x)

Node v10.0.0 和更新版本(当前是 Node v14.x)

URL Class

网址类

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

v10.0.0 | 该类现在可用于全局对象。

As mentioned here: Node.js Documentation - Class: URL

如此处所述:Node.js 文档 - 类:URL

So this should work without require('url'):

所以这应该没有require('url')

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

回答by user4447655

The docs you took this info out are for the nodeof version 8.4.0.

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

If it does not work for you, that means that your nodeis of version 6.11.2. Then, just change the letter case of URL-

如果它对您不起作用,则意味着您node的版本是6.11.2. 然后,只需更改字母大小写URL-

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

because urlmodule exports Url, not URL.

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