简体   繁体   中英

node.js module exports

What's the reason that this works:

exports.foo = 'foo';

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

but this doesn't:

var data = { foo: 'foo' };
exports = data;

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

I'll Try to answer this as a javascript question Code Sample

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

The same for node

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 and module.exports refer to the same core object until you override as in javsacript prototype object. The moment you override the reference changes.

module.exports = {something: "works"} works because you are changing the property of module that node cares while caching it.

Even for the above

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

this proves that vice versa is also true :)

One more thing module is the reference to the current module so always prefer using module.exports than exports

You can fix the second code by replacing exports = data; with module.exports = data; .

The reason the former doesn't work is that it only assigns to exports another object in the module name space. While the latter replaces the value of exports property on the module object with your data object.

Well, in the second code you are basically overwriting the export object. So even if your code would worked, I guess all other exports would be destroyed (overwritten) by this. Thus maybe node has some protecting mechanism to avoid such a case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM