Reputation: 792
I can define a module in node.js:
mymodule.js
exports.bar = "Hello";
exports.foo = function(){
console.log(exports.bar);
}
I can require the module:
app.js
var baz = require("./mymodule.js");
baz.foo(); //Logs "Hello" in the console
If I call the foo
function as above, it logs "Hello"
in the console. However, the variable that foo
is logging is exports.bar
, not baz.bar
. Does Node.js automatically know to switch them or the exports
object still exists?
Upvotes: 0
Views: 55
Reputation: 10148
exports
is a special object which is included in every JS
file in the Node.js
application by default.
So anything you export in a file (mymodule.js
in your case) is a property on this object and when you require
this module export
object is assigned to the requiring object (baz
in your case).
When you do
var baz = require("./mymodule.js");
Your baz
variable now looks like something
baz = {
bar : "Hello",
foo : () => {
console.log(baz.bar)
}
}
And when you call baz.foo()
you see "Hello"
printed
Upvotes: 2
Reputation: 722
When you use exports in the module, This will add property to the object and will use it as just like local object(variable).
Upvotes: 0