Why require.main.require.resolve is undefined?

2019-07-24 10:02发布

问题:

The question

Whitin the scope of a node.js module there is a module object meant to be a reference to the current module, a require function meant to require modules and a require.resolve function meant to look up the location of a module but rather than load the module just return the resolved filename.

If there is a module.require as there is a require, why there isn't a module.require.resolve as there is a require.resolve?

Or potentially the same thing: Why module.require !== require?

console.log('is require.main the same as module?');
console.log( require.main === module );

console.log('does module have a require property being a function?');
console.log( 'function' === typeof module.require );

console.log('is module.require the same as require.main.require?')
console.log( module.require === require.main.require );

console.log('is module.require the same as require?')
console.log( module.require === require );

console.log('why not?')

Notes

  1. On the code example, assume a file called something.js executed through node something.js.
  2. Please do not answer because the current implementation is that, the question is if there is really a reason to justify the current design/implementation/behaviour.
  3. For those wondering about a use case, I want to resolve an identifier as if require.resolve was called from the main module, so I expected require.main.require.resolve not being undefined.

Related on SO

What is the purpose of module.require?

Related documentation

The node.js documentation about globals states here:

require()

To require modules. See the Modules section. require isn't actually a global but rather local to each module.

require.resolve()

Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.

and here:

module A reference to the current module. In particular module.exports is used for defining what a module exports and makes available through require().

module isn't actually a global but rather local to each module.

It also states about modules here that:

module.require(id)

The module.require method provides a way to load a module as if require() was called from the original module.

Note that in order to do this, you must get a reference to the module object. Since require() returns the module.exports, and the module is typically only available within a specific module's code, it must be explicitly exported in order to be used.