node.js模块导出

时间:2012-05-08 09:15:53

标签: javascript node.js commonjs

这是什么原因:

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'}

3 个答案:

答案 0 :(得分:5)

我会尝试将此问题作为一个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"}

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

module.exports = {something: "works"}  之所以有效,是因为您正在更改节点在缓存时所关心的模块的属性。

即使是上述

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

这证明反之亦然:)

另外一件事module是对当前模块的引用,所以总是更喜欢使用module.exports而不是exports

答案 1 :(得分:3)

您可以将exports = data;替换为module.exports = data;来修复第二个代码。

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

答案 2 :(得分:1)

好吧,在第二个代码中,你基本上覆盖了导出对象。因此,即使您的代码有效,我猜其他所有出口都会被销毁(覆盖)。因此,节点可能有一些保护机制来避免这种情况