Dean Gibson Dean Gibson - 3 months ago 14
Javascript Question

What's the difference between these two module.exports?

So the first one being something like:

myFile.js

var name = "Peter";

module.exports.sayHello = function () {
console.log('Hello ' + name);
}


And the second one

myFile.js

module.exports = function () {

var name = 'Mary';

function sayHello () {
console.log('Hello ' + name);
}

return {
sayHello : sayHello
};

}();


Essentially it's the same thing right? If not, what's the difference and what's the pros and cons of each method?

Answer

Yes they are basically the same. You just don't need the verbosity of the second example.

In the first example you are adding a named property to the already existing module.exports object injected by node.js, in the second example you are overriding the original object - there is no difference for the consuming end.