module.exports vs exports in Node.js

前端 未结 23 1235
自闭症患者
自闭症患者 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:55

    This shows how require() works in its simplest form, excerpted from Eloquent JavaScript

    Problem It is not possible for a module to directly export a value other than the exports object, such as a function. For example, a module might want to export only the constructor of the object type it defines. Right now, it cannot do that because require always uses the exports object it creates as the exported value.

    Solution Provide modules with another variable, module, which is an object that has a property exports. This property initially points at the empty object created by require but can be overwritten with another value in order to export something else.

    function require(name) {
      if (name in require.cache)
        return require.cache[name];
      var code = new Function("exports, module", readFile(name));
      var exports = {}, module = {exports: exports};
      code(exports, module);
      require.cache[name] = module.exports;
      return module.exports;
    }
    require.cache = Object.create(null);
    

提交回复
热议问题