Reputation: 11249
I have been reading about this topic for several hours and just haven't found anything to help make this stick.
a module is just an object in node with a few properties, one is an exports property that references an object.
the 'exports' variable is
var exports = module.exports
It is a var pointing to the object that module.exports is referencing.
What I am struggling with is visualize what the module is. I know it's an object, but is there only one?
I know this isn't the exact way node implements a module but I am visualizing it looking something like this:
var module = {}
module.exports = {}
// now module has a property module.exports
var exports = module.exports
Now, from everything I have been reading, if you were to assign something to module.export = 'xyz'
It would hold the value 'xyz'. Does it lose the original object? On top of that, if I assigned something else to module.exports in the same file, would it be replaced with the new value?
EX:
// file = app.js
module.export = 'hello'
module.export = 'bye'
// file = newApp.js
require(./app);
what is the value of the module? Am I overriding the same module object or are there multiple?
Upvotes: 6
Views: 2016
Reputation: 145162
Before we continue, it's important that you understand how modules are actually loaded by node.
The key thing to take away from node's module loading system is that before it actually runs the code you require
(which happens in Module#_compile
), it creates a new, empty exports
object as a property of the Module
. (In other words, your visualization is correct.)
Node then wraps the text in the require
d file with an anonymous function:
(function (exports, require, module, __filename, __dirname) {
// here goes what's in your js file
});
...and essentially eval
s that string. The result of eval
ing that string is a function (the anonymous wrapper one), and node immediately invokes the function, passing in the parameters like this:
evaledFn(module.exports, require, module, filename, dirname);
require
, filename
, and dirname
are a reference to the require
function (which actually isn't a global), and strings containing the loaded module's path information. (This is what the docs mean when they say "__filename
isn't actually a global but rather local to each module.")
So we can see that inside a module, indeed exports === module.exports
. But why do modules get both a module
and a exports
?
Backward compatibility. In the very early days of node, there was no module
variable inside of modules. You simply assigned to exports
. However, this meant you could never export a constructor function as the module itself.
A familiar example of a module exporting a constructor function as the module:
var express = require('express');
var app = express();
This works because Express exports a function by reassigning module.exports
, overwriting the empty object that node gives you by default:
module.exports = function() { ... }
However, note that you can't just write:
exports = function { ... }
This is because JavaScript's parameter passing semantics are weird. Technically, JavaScript might be considered "pure pass-by-value," but in reality parameters are passed "reference-by-value".
This means that you when you pass an object to a function, it receives a reference to that object as a value. You can access the original object through that reference, but you cannot change the caller's perception of the reference. In other words, there's no such thing as an "out" param like you might see in C/C++/C#.
As a concrete example:
var obj = { x: 1 };
function A(o) {
o.x = 2;
}
function B(o) {
o = { x: 2 };
}
Calling A(obj);
will result in obj.x == 2
, because we access the original object passed in as o
. However, B(obj);
will do nothing; obj.x == 1
. Assigning a completely new object to B
's local o
only changes what o
points to. It does nothing to the caller's object obj
, which remains unaffected.
Now it should be obvious why it was thus necessary to add the module
object to node modules' local scope. In order to allow a module to completely replace the exports
object, it must be available as the property an object passed in to the module anonymous function. And obviously no one wanted to break existing code, so exports
was left as a reference to module.exports
.
So when you're just assigning properties to your exports object, it doesn't matter whether you use exports
or module.exports
; they are one and the same, a reference pointing to the exact same object.
It's only when you want to export a function as the top-level export where you must use module.exports
, because as we've seen, simply assigning a function to exports
would have no effect outside of the module scope.
As a final note, when you are exporting a function as the module, it's a good practice to assign to both exports
and module.exports
. That way, both variables remain consistent and work the same as they do in a standard module.
exports = module.exports = function() { ... }
Be sure to do this near the top of your module file, so that no one accidentally assigns to an exports
that ends up getting overwritten.
Also, if that looks strange to you (three =
s?), I'm taking advantage of the fact that an expression containing the assignment operator returns the assigned value, which makes it possible to assign a single value to multiple variables in one shot.
Upvotes: 9
Reputation: 13585
Modules in Node.js are just files. Each file is a module and each module is a file. If you have more than one file, you can have more than one module (one in each file).
As per module.exports
: the Node.js API documentation will shed some light on the topic:
The
module.exports
object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this assign the desired export object tomodule.exports
. Note that assigning the desired object toexports
will simply rebind the localexports
variable, which is probably not what you want to do.
and
The
exports
variable that is available within a module starts as a reference tomodule.exports
. As with any variable, if you assign a new value to it, it is no longer bound to the previous value. ... As a guideline, if the relationship between exports and module.exports seems like magic to you, ignore exports and only use module.exports.
So, what does this all mean? In your particular example, module.exports
would be equal to it's last assigned value ('bye'
).
Upvotes: 2
Reputation: 636
You're overriding the module — exports is a single object gets pulled in with require
. Typically, when doing this kind of modular JavaScript using require
, your export will be a constructor rather than a primitive like a string in your example. That way, you can create new instances of functionality that's defined in the module. Example:
// module.js
var MyConstructor = function(prop) {
this.prop = prop;
});
module.exports = MyConstructor;
// app.js
var MyConstructor = require('module');
var instance = new MyConstructor('test');
console.log(instance.prop) // 'test'
Upvotes: 2