[javascript] module.exports vs exports in Node.js

  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.

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to commonjs

Field 'browser' doesn't contain a valid alias configuration Node.js - use of module.exports as a constructor Relation between CommonJS, AMD and RequireJS? Difference between "module.exports" and "exports" in the CommonJs Module System module.exports vs exports in Node.js