module.exports vs exports in Node.js

前端 未结 23 1638
自闭症患者
自闭症患者 2020-11-22 06:11

I\'ve found the following contract in a Node.js module:

module.exports = exports = nano = function database_module(cfg) {...}

I wonder what

23条回答
  •  醉梦人生
    2020-11-22 06:50

    1. Both module.exports and exports point to the same function database_module(cfg) {...}.

      1| var a, b;
      2| a = b = function() { console.log("Old"); };
      3|     b = function() { console.log("New"); };
      4|
      5| a(); // "Old"
      6| b(); // "New"
      

      You can change b on line 3 to a, the output is reverse. The conclusion is:

      a and b are independent.

    2. So module.exports = exports = nano = function database_module(cfg) {...} is equivalent to:

      var f = function database_module(cfg) {...};
      module.exports = f;
      exports = f;
      

      Assumed the above is module.js, which is required by foo.js. The benefits of module.exports = exports = nano = function database_module(cfg) {...} is clear now:

      • In foo.js, since module.exports is require('./module.js'):

        var output = require('./modules.js')();
        
      • In moduls.js: You can use exports instead of module.exports.

    So, you will be happy if both exports and module.exports pointing to the same thing.

提交回复
热议问题