I was searching for the URL
module when I found the URL
on both JavaScript and Node.js.
I have a few questions:
URL
different from the Node.js URL?URL
module in Node.js and the
features of JavaScript?URL
is known as a global object. So
you no longer need to require a url
module?Browser-compatible URL class, implemented by following the WHATWG URL Standard. Examples of parsed URLs may be found in the Standard itself. The URL class is also available on the global object.
Inside the global object platform, I also saw the http
, path
, os
, etc. modules.
I wanted to use the os
and path
modules without requiring (because they are inside global objects) but my file execution failed:
> node test.js
console.log(path); // ReferenceError: path is not defined
I also wrote the following code but the undefined value was printed in the output:
console.log(global.path); // undefined
But when I use these in REPL, it returns the following output:
<ref *1> {
resolve: [Function: resolve],
normalize: [Function: normalize],
isAbsolute: [Function: isAbsolute],
join: [Function: join],
relative: [Function: relative],
toNamespacedPath: [Function: toNamespacedPath],
dirname: [Function: dirname],
basename: [Function: basename],
extname: [Function: extname],
format: [Function: bound _format],
parse: [Function: parse],
sep: '\\',
...
...
Thanks for your attention. I’m looking forward to your reply.
require('url')
if you just want the URL class or URLSearchParams.You mention some modules being in the global object:
http, path, os, etc.
However, the documentation does not state that anywhere. On the contrary, these are modules that you need to require()
yourself. URL
is documented as being part of the global object, and it's true - it's a class that's available anywhere, much like String, Number, Buffer and some others. This is done for compatibility with the Web platform.
The REPL is special - it includes a usability feature that loads core modules if it sees a reference to them. More details here: https://nodejs.org/api/repl.html#accessing-core-nodejs-modules
This means that some code can actually behave differently in the REPL and when run directly via node
.