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).