require() vs module.require() in nodejs? - node.js

What is the difference between require() vs module.require() in nodejs ?
require()
module.require()
The documentation don't provide any content about the difference between them. Can anyone explain ?

They both require other modules (call other module's and returns their module.exports objects)
module.require('./module1.js');
require('./module1.js');
but they are NOT the same
require === module.require // -> false
module.require can only be used as method
require is a method but also has their own properties (cache main)
providing additional data
module.require.cache // -> undefined
require.cache // -> {the cached module}

The official documentation is not only a little unclear on how they differ, but also lacks any example usage that would help determine the usefulness of using module.require vs require. So I resorted to experimentation, and what I discovered is that, essentially, require() takes a path relative to the module doing the importing, where as module.require takes a module id (this is outlined in the docs, but it is a little unclear what 'id' refers to).
So what id actually refers to is an attribute 'id' of the module object (module.id). If you console.log(module.id) from within a module, you will get the full path to that file. But the only way to load a module using module.require() is if you have access to the module.id variable, which is not exported in module.exports. So technically you could load the current module inside itself as so:
Example Usage 1:
test.js
module.exports = {};
module.exports.foo = function() {
console.log('bar');
};
let thisModule = module.require(module.id);
thisModule.foo();
app.js
const test = require('./test');
output
$ bar
How this use case is useful is beyond me, but loading a module inside itself to run its own exported functions is possible for some reason. Another possible use case is something like this:
Example Usage 2:
test.js
const loader = require('./loader'); // Some library that handles module loading
// dynamically. loader.register passes the module
// info to the dynamic loader to be called
// later by the client perhaps.
loader.register(module);
module.exports = {};
module.exports.foo = function() {
console.log('bar');
};
app.js
const loader = require('./loader');
const test = loader.require('./test'); // loader module will have to do some parsing
// to match './test' with the fully qualified
// path name. Just to be clear, loader.require
// is some function defined by the library
test.foo();
Theoretically outputs bar. So I guess the second use case could be useful if you want to control the loading of the modules for some reason. But you would have to build your modules specifically to this usage. I imagine there could be other uses, I plan to investigate further and if I discover anything new, then I will expand this answer. I hope this helps.

https://nodejs.org/api/modules.html#modules_module_require_id
The module.require() method provides a way to load a module as if require() was called from the original module.
In order to do this, it is necessary to 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.
What this is saying is that you can require() as if you are in another module, given that you somehow have access to the other module's module variable.
For example, I can do a module.require('./c'), even if c.js doesn't exist as a sibling in my current directory. It will work as long as module's directory has c.js in it.
Example:
.
├── a
│   ├── c.js
│   └── index.js
└── b.js
// b.js
console.log(require('./a').require('./c'));
// a/index.js
module.exports = module;
// a/c.js
module.exports = 'c';
node b.js // stdout 'c'

Documentation for module.require is clear:
The module.require method provides a way to load a module as if require() was called from the original module.
In order to do this, it is necessary to 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.

Related

How do I use require inside a module with the parents context?

app.js
require('./modules/mod');
modules/mod/mod.js
modules.exports = () => {
require('./modules/secondmodule');
}
Essentially I want the above code to be able to require modules, but using the same context that itself was called from, e.g. another module in the same folder, without having to use relative paths.
I thought module.require() did this, but it seems to give me the same error that require() was after I moved my code into the separate module (mod.js).
edit:
I have since discovered I can use require.parent.module and it seems to be working. Please let me know if this is not advised.
require uses paths that are relative to current module. It's possible to do this by providing require from parent module:
modules.exports = parentRequire => {
parentRequire('./modules/secondmodule');
}
Which is used like:
require('./modules/mod')(require);
It's correct to use relative modules instead because child module shouldn't be aware of the context in which it's evaluated:
require('../secondmodule');
In case mod has to be decoupled from secondmodule, dependencies can be provided to it with some common pattern, e.g. dependency injection or service locator.
Secondary optional answer:
module.exports = () => {
module.parent.require('./modules/secondmodule');
}

Require a file within itself in node.js

How do you require a file within itself in node.js? E.g. api.js:
var api = require(./api.js);
What is the best practice for doing this?
You can totally do it. Try this, for instance (in a file named a.js):
exports.foo = 'foo';
var a = require('./a');
console.log(a);
exports.bar = 'bar';
console.log(a);
At the point where require executes, it will return the module a as it exists at the point where require runs so the field foo will be defined but not bar.
There's no point to doing this though. You use require to bring into your current scope an object which would otherwise not be available (namely, a module). But you don't need to do this to access the module you are currently in: it is already fully available.
The code above works because Node has rules to handle cyclic dependencies. And here you have a module which is cyclicly dependent on itself. Rather than go into an infinite loop of requires, Node has require return the module as built up to that point: a partial module. And the modules in a cyclic dependency have to be designed to handle the fact that they may get partial modules.
Cyclic dependencies are to be avoided as much as possible. Most of the time this means refactoring the modules to avoid the mutual dependency by moving functionality into one or more new modules.
So, again, the best practice is to not do this in the first place.

node mean.io syntax what the purpose of expose app?

In the server.js file of mean.io
I can see
//expose app
exports = module.exports = app;
Can anyone explain me the meaning, what is it for ?
File in Question: https://github.com/linnovate/mean/blob/master/server.js
I would write something up, but I found an article that covers it nicely:
[ . . . ] In /src/node.js you can see that your
code is wrapped in a closure and passed both exports and module. Of
course, further inspection will show you that exports contains a
pointer to module.exports and suddenly everything makes sense.
Overwriting exports overwrites the pointer to module.exports which
disconnects exports from the Node.js environment!
What’s the point?
Exports is a helper function that points to module.exports. This is
meant to make your life easier. That is all. Use it to expose
functions of your module, but if your module needs to replace what is
exposed, you must use module.exports.
Open up that article and take a look at the examples that are provided for more information.
In short, it's a way of making the app variable be referenced directly when it's required from another module instead of being nestled into an object, e.g.
// hello.js
module.exports = 'hello';
// foo.js
exports.foo = 'bar';
// testing it out
console.log(require('hello.js')); // outputs 'hello'
console.log(require('foo.js')); // outputs { foo: 'bar' }

Not modifying a loaded node module

In my Node app, have a config file like this:
module.exports = {
BUILD_DIR: '/some.path',
OTHER_CONFIG: 42,
// ...
};
I also have some tests doing things like
var appConfig = require('./path/to/appConfig');
appConfig.BUILD_DIR = 'tmp/some/path';
// and stuff done with appConfig
To my big surprise doing this apparently modifies the state of the module. My next test that requires it will have BUILD_DIR set to 'tmp/some/path'. I did not realize modules had this kind of state across requires. How do I get rid of this effect in my test? Also, how can I prevent people from modifying the state of this module? If someone includes it, they should always get what it defines, and not possibly something some other code wrote to it.
The reason why is explained here:
Modules are cached after the first time they are loaded. This means
(among other things) that every call to require('foo') will get
exactly the same object returned, if it would resolve to the same
file.
(emphasis mine)
So the object that you're exporting is cached and shared among the code that uses it.
If that's not what you want, you could export a function instead:
module.exports = function() {
return {
BUILD_DIR: '/some.path',
OTHER_CONFIG: 42,
// ...
};
};
And require it like so:
var appConfig = require('./path/to/appConfig')();
Assuming your module is called 'Config', and you originally:
var Config=require('Config');
you could:
delete require.cache[require.resolve('Config')];
which will remove the module from require's cache, causing it to be loaded afresh when you next 'require' it.
Gist: https://gist.github.com/raisch/6786930

When should I use require() and when to use define()?

I have being playing around with requirejs for the last few days. I am trying to understand the differences between define and require.
Define seems to allow for module separation and allow for dependency ordering to be adhere. But it downloads all the files it needs to begin with. Whilst require only loads what you need when you need it.
Can these two be used together and for what purposes should each of them be used?
With define you register a module in require.js that you can then depend on in other module definitions or require statements.
With require you "just" load/use a module or javascript file that can be loaded by require.js.
For examples have a look at the documentation
My rule of thumb:
Define: If you want to declare a module other parts of your application will depend on.
Require: If you just want to load and use stuff.
From the require.js source code (line 1902):
/**
* The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's
* name.
*/
The define() function accepts two optional parameters (a string that represent a module ID and an array of required modules) and one required parameter (a factory method).
The return of the factory method MUST return the implementation for your module (in the same way that the Module Pattern does).
The require() function doesn't have to return the implementation of a new module.
Using define() you are asking something like "run the function that I am passing as a parameter and assign whatever returns to the ID that I am passing but, before, check that these dependencies are loaded".
Using require() you are saying something like "the function that I pass has the following dependencies, check that these dependencies are loaded before running it".
The require() function is where you use your defined modules, in order to be sure that the modules are defined, but you are not defining new modules there.
General rules:
You use define when you want to define a module that will be reused
You use require to simply load a dependency
//sample1.js file : module definition
define(function() {
var sample1 = {};
//do your stuff
return sample1;
});
//sample2.js file : module definition and also has a dependency on jQuery and sample1.js
define(['jquery', 'sample1'], function($,sample1) {
var sample2 = {
getSample1:sample1.getSomeData();
};
var selectSomeElement = $('#someElementId');
//do your stuff....
return sample2;
});
//calling in any file (mainly in entry file)
require(['sample2'], function(sample2) {
// sample1 will be loaded also
});
Hope this helps you.
"define" method for facilitating module definition
and
"require" method for handling dependency loading
define is used to define named or unnamed modules based on the proposal using the following signature:
define(
module_id /*optional*/,
[dependencies] /*optional*/,
definition function /*function for instantiating the module or object*/
);
require on the other hand is typically used to load code in a top-level JavaScript file or within a module should you wish to dynamically fetch dependencies
Refer to https://addyosmani.com/writing-modular-js/ for more information.
require() and define() both used to load dependencies.There is a major difference between these two method.
Its very Simple Guys
Require() : Method is used to run immediate functionalities.
define() : Method is used to define modules for use in multiple locations(reuse).

Resources