difference between module.require () and require() node.js

I apologize for my English, but in the documentation for node modules.js everything is written in such a way that I was not enough with the translator:

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.

Author: Stranger in the Q, 2016-06-11

3 answers

module.require and require are the same thing. The only difference is that module.require is a method, and require is a parameter :)


In practice, the presence of the module.require method means that if you have a reference to some module (which in itself is not easy, because module is also a local parameter), then you can call require as if it is executed from this very other module.

The only module that is available "out of the box" is require.main, the main module (i.e. that module, which was launched). This allows you to do tricks like require.main.require('./config'), loading the config not relative to the current module - but relative to the main one. Other modules, except for the config, so it is better not to load, because each module should work regardless of how and from where it was launched.


PS The function whose parameters are module and require can be found in the documentation. This is a wrapper function over the modules, inside which each module is implicitly placed before start executing.

 4
Author: Pavel Mayorov, 2017-01-23 06:26:07

It says here that the module.require method provides the ability to load the module if the method is called from the main module. in this case, the method returns what is assigned to the module.exports variable inside the module.

Let's say you have a module: myModule.js

module.exports = {
    moduleFunction: function(arg) {
        console.log(arg);
    }
}

And the main script index.js

var myModule = require('./myModule');
myModule.moduleFunction('hello');

This is how you load your module and call the moduleFunction{[6 method]}

I want to note that this is not only true for node.js but also for the regular web, for example with browserify

 1
Author: Stranger in the Q, 2016-06-11 06:03:53

It says that module. require allows you to load the module as if it was loaded from the parent module

 0
Author: pitersky, 2016-06-11 09:15:29