Home > OS >  Node.js url module vs Javascript URL
Node.js url module vs Javascript URL

Time:11-11

I was searching for the URL module when I found the URL on both JavaScript and Node.js.
I have a few questions:

  1. Is the JavaScript URL different from the Node.js URL?
  2. What is the difference between the URL module in Node.js and the features of JavaScript?
  3. Inside the documentation was written, the 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
  • what is the reason?

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: '\\',
  ...
  ...
  • What is the reason for the difference between REPL and script file?

Thanks for your attention. I’m looking forward to your reply.

CodePudding user response:

  1. The URL object in Node.js is designed to be compatible with the one that you get in browsers.
  2. Any visible differences should be mentioned in the docs for the URL class. There do not appear to be any.
  3. That is correct - you do not need to 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.

  • Related