Uncaught TypeError: URL is not a constructor using WHATWG URL object support for electron
Solution 1
I faced the same issue, then I looked into the url module and found a solution
For Node V6 use,
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
Solution 2
Are you using Node 6 instead of Node 8?
Node 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
Node 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
Solution 3
Node v10.0.0 and newer (currently Node v16.x)
URL Class
v10.0.0 | The class is now available on the global object.
As mentioned here: Node.js Documentation - Class: URL
So this should work without require('url')
:
const myUrl = new URL('http://example.com');
Solution 4
The docs you took this info out are for the node
of version 8.4.0
.
If it does not work for you, that means that your node
is of version 6.11.2
. Then, just change the letter case of URL
-
const { Url } = require('url');
const myUrl = new Url('http://example.com');
because url
module exports Url
, not URL
.
![Ana Houa](https://lh3.googleusercontent.com/--9WKMoWe-Ik/AAAAAAAAAAI/AAAAAAAAACo/ZePjSDO6u-o/photo.jpg?sz=256)
Ana Houa
Updated on July 16, 2022Comments
-
Ana Houa almost 2 years
I am trying to read a file using WHATWG URL object support here
and I am getting this error: Uncaught TypeError: URL is not a constructor
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);
-
andrhamm almost 7 yearsI had to use
const URL = require('url').URL
-
Ricky Nelson over 6 yearsSigh, it looks like the documentation is wrong here, it does not show the
.URL
nodejs.org/api/url.html in the various examples. -
SliverNinja - MSFT over 6 yearsif you are managing multiple node environments -
semver
can be helpful to determine which method to use based upon the node version -
Biswajit Mohanty about 6 yearsI think const URL = require('url').Url; will give you null values const URL = require('url').Url; var loginURL = new URL("exampe.com/xyz.html"); console.log(loginURL); node version 8.4.0
-
Kowsalya about 6 years@BiswajitMohanty, the above answer was posted for node version 6, for version 8, the method (const { URL } = require('url'); ) mentioned in the question should work fine.
-
Kowsalya about 6 years@socketwiz, the documentation is not wrong, requiring a module with {} (const { URL } = require('url');) or using dot notation (const URL = require('url').URL) both must yield same response.