node.js模块导出

这是什么原因:

exports.foo = 'foo'; var bar = require('./foo'); console.log(bar); // {foo: 'foo'} 

但是这不是:

 var data = { foo: 'foo' }; exports = data; var bar = require('./foo'); console.log(bar); // {} // expected {foo: 'foo'} 

我会尽力回答这是一个JavaScript问题的代码示例

 function a() {} a.prototype.foo = {test:"bar"} var d = new a(); var c = new a(); console.log(d.prototype ==== c.prototype) // Both c and d share the same prototype object d.foo.hai = "hello" console.log(d.prototype ==== c.prototype) // Still the they refer to the same d.foo = {im: "sorry"} console.log(d.prototype ==== c.prototype) // now they don't 

同样的节点

 console.log(module.exports === exports);// true; They refer to the same object exports.a = {tamil: "selvan"} console.log(module.exports === exports);// true even now exports = {sorry: "im leaving"}; // overrides modules.exports console.log(module.exports === exports); //false now they don't console.log(module.exports); // {a: {tamil: "selvan"}} console.log(exports); // {sorry: "im leaving"} 

导出和module.exports引用相同的核心对象,直到你重写在javsacript原型对象。 您覆盖参考更改的那一刻。

module.exports = {something: "works"}作品,因为你正在改变模块的属性,该节点在caching时关心。

即使是以上

module.exports === exports //is false they are no more the same

这certificate反之亦然:)

还有一件事是module是对当前模块的引用,所以总是比使用module.exports更喜欢exports

您可以通过replaceexports = data;来修复第二个代码exports = data;module.exports = data;

前者不起作用的原因是它只在模块名称空间中分配exports另一个对象。 而后者用data对象replacemodule对象上的exports属性的值。

那么,在第二个代码中,你基本上覆盖了导出对象。 所以,即使你的代码可以工作,我猜所有其他的出口将被销毁(重写)。 因此,节点可能有一些保护机制来避免这种情况