20

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?

MustSeeMelons
  • 737
  • 1
  • 10
  • 24

3 Answers3

43

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"
};
robertklep
  • 198,204
  • 35
  • 394
  • 381
8

If you want to get via caravan.month then:

module.exports = {
    month: "july"
};
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38
2

If you want to get the object, use

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

and then get it like this:

var caravan = require("./caravan")

You may also check:

console.log(caravan.caravan.month);
Ravi Teja
  • 649
  • 7
  • 17