Creative Choi
Creative Choi

Reputation: 123

What is a difference between var app = require(..) and var app = module.exports = require(..)?

I have an question about a common usage but difficult for nodejs newbie.

What is a difference between

var app = require('./index');

and

var app = module.exports = require('./index');

?

Anything different or is there something I don't know? Thank you for reading this. :)

Upvotes: 0

Views: 1732

Answers (2)

Bassam Rubaye
Bassam Rubaye

Reputation: 302

require('./index') will return (reference) whatever the value of module.exports in index.js

Your code in index.js will be wrapped by a function(exports, module, etc.){}

So, the difference between your two statements is : in the second statement whatever you assign to app will also be returned to the require

var app = module.exports = require('./index'); //assume index returns{ name:'joe' } 
app.age='20;  // now you will return {name:'joe', age:20} 

now if you require this file you will receive {name:'joe', age:20}

Upvotes: 2

Saad
Saad

Reputation: 53879

var app = module.exports = require('./index');

is the same thing as

module.exports = require('./index');
var app = module.exports;

Upvotes: 0

Related Questions