I dont understand certain scenarios of module.exports concept of nodejs.
math.js
var add = function(a, b){
return a + b;
}
multiply = function(a, b){
return a * b;
}
Scenario 1:
app.js
require("./math")
//can I use add?
//can I use multiply?
Scenario 2:
app.js
var math = require("./math")
//can I use math.add?
//can I use math.multiply?
I have put down my questions inside each scenarios. Thanks for help.
To add functions and objects to the root of your module, you can add them to the special exports object.
Variables local to the module will be private, as though the module was wrapped in a function. In this example the variable PI is private to circle.js.
Both of your scenarios wont work(as you would have noticed if you had just tried it).
Everything you want to use needs to be assigned to the exports property on the (module-)local module object.
See the example on nodejs.org/api/modules.html
EDIT: Imagine require doing the following
(function (module, exports) {
var im_local = 123;
im_global = 321;
// Your module code here
})(module, module.exports);
return module.exports;
Note that im_global is actually invalid by newer javascript standards but will not throw an error when not in strict mode because of
backwards compatibilty / quirks mode behavior of the V8 javascript engine.