module.exports vs exports in Node.js

前端 未结 23 1285
自闭症患者
自闭症患者 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 07:10

    I went through some tests and I think this may shed some light on the subject...

    app.js:

    var ...
      , routes = require('./routes')
      ...;
    ...
    console.log('@routes', routes);
    ...
    

    versions of /routes/index.js:

    exports = function fn(){}; // outputs "@routes {}"
    
    exports.fn = function fn(){};  // outputs "@routes { fn: [Function: fn] }"
    
    module.exports = function fn(){};  // outputs "@routes function fn(){}"
    
    module.exports.fn = function fn(){};  // outputs "@routes { fn: [Function: fn] }"
    

    I even added new files:

    ./routes/index.js:

    module.exports = require('./not-index.js');
    module.exports = require('./user.js');
    

    ./routes/not-index.js:

    exports = function fn(){};
    

    ./routes/user.js:

    exports = function user(){};
    

    We get the output "@routes {}"


    ./routes/index.js:

    module.exports.fn = require('./not-index.js');
    module.exports.user = require('./user.js');
    

    ./routes/not-index.js:

    exports = function fn(){};
    

    ./routes/user.js:

    exports = function user(){};
    

    We get the output "@routes { fn: {}, user: {} }"


    ./routes/index.js:

    module.exports.fn = require('./not-index.js');
    module.exports.user = require('./user.js');
    

    ./routes/not-index.js:

    exports.fn = function fn(){};
    

    ./routes/user.js:

    exports.user = function user(){};
    

    We get the output "@routes { user: [Function: user] }" If we change user.js to { ThisLoadedLast: [Function: ThisLoadedLast] }, we get the output "@routes { ThisLoadedLast: [Function: ThisLoadedLast] }".


    But if we modify ./routes/index.js...

    ./routes/index.js:

    module.exports.fn = require('./not-index.js');
    module.exports.ThisLoadedLast = require('./user.js');
    

    ./routes/not-index.js:

    exports.fn = function fn(){};
    

    ./routes/user.js:

    exports.ThisLoadedLast = function ThisLoadedLast(){};
    

    ... we get "@routes { fn: { fn: [Function: fn] }, ThisLoadedLast: { ThisLoadedLast: [Function: ThisLoadedLast] } }"

    So I would suggest always use module.exports in your module definitions.

    I don't completely understand what's going on internally with Node, but please comment if you can make more sense of this as I'm sure it helps.

    -- Happy coding

提交回复
热议问题