Custom Module Export
/**Custom Module Export */
/* Lets see how to export your own module so that it could be read by other Js program */
/* actually a module can be exported in two ways:
1) using :
exports.custObj = 123;
2) using :
module.exports = 123;
says we have created a new file CustomModule.js and put the below line:
exorts.custObj = 123;
and we can get this exported value in other program say, UseExported.js:
var expVal = require("./CustomModule");
console.log(expVal);//will print { custObj: 123 }
but if we have exported the value by directly assigning to exports object like:
exports = 123;
and imported it in other js file
var expVal = require("./CustomModule");
console.log(expVal);//will print {} ,an empty object why??
Heres how, actually the CustomModule file have an internal module object which is like:
var module = {
exports : {}
};
and it provide short form of using :
var exports = module.exports;//pointing to {}
and when CustomModule code will return the internal code returns module.exports object
thus if someone ovveride like exports = 123, then what happen is like below
exports = 123;//user wants to export this value
then when custome module program actually return will call internally "return module.exports" which is still pointing to {}
thus if user uses this export in other program
it will simply print {} (becuase the short form var exports = module.exports points to the object and we ovveride it
not the object)
now lets do it by module.exports by assigning value to it:
module.exports = 123;//user want to export this constatnt value
,but when program return it will internally "return module.export;" ,which were pointing to {}
but you override the module.eports itself to 123, thus it will be the final value that will be exported i.e, 123
thus
var expVal = require("./CustomModule");
console.log(expVal);//will print 123
thus remeber when a custom module return ,it calls at the end "return module.exports;"
if you override module.exports , you are ovveriding the actual object.
if you do module.exports.custObj = 123;//it will be {custObj : 123}, becuase module.exports point to {}
and module.exports.custObj is like creating a property in object {}.
like wise if we do exports.custObj = 123; //which internally likes module.exports.custObj = 123
thus when module code returns it call "return module.exports;"//{custObj : 123}
and can be accessed:
console.log(expVal);//will print {custObj : 123}
console.log(expVal.custObj);//will print 123
Also note:
You have created a Custome module, but you have not done any assignment to exports or module.exports.
Even on this also, if someone require you module it will give {}, thus it proves that require function call
will look for the module.exports if not the default one {} will be taken.
*/
Comments
Post a Comment