source code

function Module(id, parent) {
    this.id = id;
    this.exports = {};
    this.parent = parent;
    if (parent && parent.children) {
        parent.children.push(this);
    }

    this.filename = null;
    this.loaded = false;
    this.children = [];
}

Default

index.js

console.log(module)
Module {
  id: '.',
  exports: {},
  parent: null,
  filename: '/home/joes/Demo/tests/index.js',
  loaded: false,
  children: [],
  paths: 
   [ '/home/joes/Demo/tests/node_modules',
     '/home/joes/Demo/node_modules',
     '/home/joes/node_modules',
     '/home/node_modules',
     '/node_modules' ] }

Add module

file1.js

module.exports = function fn() {};

index.js

var file1 = require('./file1.js')
console.log(module)
Module {
  id: '.',
  exports: {},
  parent: null,
  filename: '/home/joes/Demo/tests/index.js',
  loaded: false,
  children: 
   [ Module {
       id: '/home/joes/Demo/tests/file1.js',
       exports: [Function],
       parent: [Circular],
       filename: '/home/joes/Demo/tests/file1.js',
       loaded: true,
       children: [],
       paths: [Object] } ],
  paths: 
   [ '/home/joes/Demo/tests/node_modules',
     '/home/joes/Demo/node_modules',
     '/home/joes/node_modules',
     '/home/node_modules',
     '/node_modules' ] }
     

我们时常会在模块源码中看到

exports = module.exports = {};

此时二者指向同一个对象。如果export.a = 1;此时

exports = module.exports = {a: 1}

如果使用exports = function() {};并没有导出module,exports 指向了新的对象,module.exports还是指向原始的对象。又因为module.exports对象是要传给require函数的,所以之后的改变并不会实际导出到外面。

Links

http://www.hacksparrow.com/node-js-exports-vs-module-exports.html
http://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js


cnio
222 声望3 粉丝

个人网站:[链接]