Mohammad Yusuf Ghazi Mohammad Yusuf Ghazi - 6 months ago 30
Javascript Question

nodejs module exports confusion

I have a confusion with module.exports. As far as I understood

module.exports
is an object that is exposed to other modules,

exports=module.exports={}


But in the index.js of morgan package in node.js I found this.

module.exports = morgan
module.exports.compile = compile
module.exports.format = format
module.exports.token = token


morgan
,
compile
,
format
and
token
are all functions.

Can you explain whats happening here? How is a function(morgan) assigned to module.exports ? After the first line is executed, is module.exports a function instead of an JSON object?

Answer

A Node module basically works like this:

var module = {
    exports: {}
};
(function (exports, require, module, __filename, __dirname) {

    // your module code here

})(module.exports, require, module, __filename, __dirname);

var exported = module.exports;

By default, exports, and module.exports both point to the same object. You can add properties to the object as normal. However, what if you want to return a function or some other object instead of just the default standard object?

In that case, you can set module.exports to something else, and that will be the new exported object.

module.exports = function() {};

And of course, that function can have properties too, so your code is kind-of like this:

module.exports = function(){};
module.exports.compile = function() {};
module.exports.format = function() {};
module.exports.token = function() {};

Which would be equivalent to:

var morgan = function() {};
var compile = function() {};
var format = function() {};
var token = function() {};

morgan.compile = compile;
morgan.format = format;
morgan.token = token;
module.exports = morgan;

How is a function(morgan) assigned to module.exports ? After the first line is executed, is module.exports a function instead of an JSON object?

Yes, module.exports will be a function, in place of the default object (however there is no JSON here, JSON is not a JavaScript object, but an encoding format).