Looking at a random source file of the express framework for NodeJS, there are two lines of the code that I do not understand (these lines of code are typical of almost all NodeJS files).
/**
* Expose `Router` constructor.
*/
exports = module.exports = Router;
and
/**
* Expose HTTP methods.
*/
var methods = exports.methods = require('./methods');
I understand that the first piece of code allows the rest of the functions in the file to be exposed to the NodeJS app, but I don’t understand exactly how it works, or what the code in the line means.
What do
exportsandmodule.exportsactually mean?
I believe the 2nd piece of code allows the functions in the file to access methods, but again, how exactly does it do this.
Basically, what are these magic words: module and exports?
To be more specific:
moduleis the global scope variable inside a file.So if you call
require("foo")then :It acts in the same way that
windowacts in the browser.There is also another global object called
globalwhich you can write and read from in any file you want, but that involves mutating global scope and this is EVILexportsis a variable that lives onmodule.exports. It’s basically what you export when a file is required.There is a minor problem with
exportson it’s own. The _global scope context+ andmoduleare not the same. (In the browser the global scope context andwindoware the same).Read more about exports