var myModule=require("./myModule");

Using require like this assigns the value of module.exports from the module myModule. Our myModule looks like this:

//myModule.js
var func1=function(a){
  return a*a;
}
exports.func1=func1;

Wait a minute! We are using exports to export the functions from the module, not module.exports. Are they the same? Turns out that exports is a reference to module.exports that is shorter to type. exports is not global but local to each module.

It is like declaring the following at the top of each of your modules:

var exports=module.exports;

All of this works fine if we are assigning all the exports from your module as properties (like in the myModule definition above). What happens if we did something like this:

//myModule.js
var func1=function(a){
return a*a;
}
exports=func1;

Nothing gets exported - module.exports will be empty. Why? Remember exports is just a variable and when we assign something else to it, it is no longer referring to module.exports.

If you need to export a function or a complete object from your module, assign it to module.exports instead of exports.

//myModule.js
var func1=function(a){
return a*a;
}
module.exports=func1;
Posted
AuthorMurali Narasimhan
CategoriesTechnology