Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
56
rated 0 times [  59] [ 3]  / answers: 1 / hits: 25325  / 8 Years ago, sat, july 9, 2016, 12:00:00

Got a pretty simple question to which I cant find an answer regarding exporting a object form a module in Node js, more specifically accessing the objects properties.



Here is my object I export:



exports.caravan = {
month: july
};


And here is my main module:



var caravan = require(./caravan)

console.log(caravan.month);
console.log(caravan.caravan.month);


Why cant I access the properties directly with caravan.month but have to write caravan.caravan.month?


More From » node.js

 Answers
2

Consider that with require, you gain access to the module.exports object of a module (which is aliased to exports, but there are some subtleties to using exports that make using module.exports a better choice).



Taking your code:



exports.caravan = { month: july };


Which is similar to this:



module.exports.caravan = { month: july };


Which is similar to this:



module.exports = {
caravan : { month: july }
};


If we similarly translate the require, by substituting it with the contents of module.exports, your code becomes this:



var caravan = {
caravan : { month: july }
};


Which explains why you need to use caravan.caravan.month.



If you want to remove the extra level of indirection, you can use this in your module:



module.exports = {
month: july
};

[#61446] Thursday, July 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarettajb

Total Points: 678
Total Questions: 94
Total Answers: 90

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;