Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  124] [ 1]  / answers: 1 / hits: 43015  / 13 Years ago, tue, may 24, 2011, 12:00:00

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 exports and module.exports actually 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?


More From » node.js

 Answers
18

To be more specific:



module is the global scope variable inside a file.



So if you call require(foo) then :



// foo.js
console.log(this === module); // true


It acts in the same way that window acts in the browser.



There is also another global object called global which you can write and read from in any file you want, but that involves mutating global scope and this is EVIL



exports is a variable that lives on module.exports. It's basically what you export when a file is required.



// foo.js
module.exports = 42;

// main.js
console.log(require(foo) === 42); // true


There is a minor problem with exports on it's own. The _global scope context+ and module are not the same. (In the browser the global scope context and window are the same).



// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with

// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the correct exports

// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works


Read more about exports


[#92067] Monday, May 23, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazlynnessencec

Total Points: 434
Total Questions: 113
Total Answers: 94

Location: Norway
Member since Mon, May 23, 2022
2 Years ago
;