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

前端 未结 4 873
自闭症患者
自闭症患者 2021-01-01 10:08

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:

相关标签:
4条回答
  • 2021-01-01 10:26

    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

    0 讨论(0)
  • 2021-01-01 10:35

    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.

    0 讨论(0)
  • 2021-01-01 10:45

    Node v10.0.0 and newer (currently Node v14.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');
    
    0 讨论(0)
  • 2021-01-01 10:47

    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

    0 讨论(0)
提交回复
热议问题