Tuesday 8 May 2018

exports vs module.exports in node js

Hey guys,

Today i understood the concept of exports and module.exports in node js.

so basically in Node js both are pointing to same object reference (empty object at first)

module.exports           exports 
             
               |                       /
               |                    /
                        { }

so its like module.exports= exports ;

Now exports is a object reference and you can start adding properties to the Object. like

//calc.js

exports.add = function() {
//bla bla
}
exports.number = 2;

when you import in other modules -> node Js returns only the module.exports in which exports is also pointed to the same. once you do this
 calc = require('calc');
 calc.add();

What if you want to return a function() instead a object property ?

once you assign exports with function and then you will loose module.exports reference but at the end node js returns module.exports

Hence you need to assign the function to
//calc
module.exports = function(){
    return x;
}


var calc = require(calc)();

so do like module.exports = exports = function() { } ==> make references to main object

No comments:

Post a Comment