Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js object exports

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?

like image 852
MustSeeMelons Avatar asked Jul 09 '16 16:07

MustSeeMelons


People also ask

Can we export object in node JS?

exports in Node. js is used to export any literal, function or object as a module. It is used to include JavaScript file into node. js applications.

How do I export a class object in node JS?

As we just saw, exporting a class can be accomplished by attaching the class as a property of the module. exports object. First, we created a class using a constructor function. Then we exported the class using module.

How do I export an array of objects in Node JS?

You'd want to define a function which returns the randomized portion of the array: module. exports = { getRArray: function() { var arrays = []; arrays[0] = 'array 0'; arrays[1] = 'array 1'; arrays[2] = 'array 2'; arrays[3] = 'array 3'; arrays[4] = 'array 4'; return arrays[Math.


2 Answers

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"
};
like image 137
robertklep Avatar answered Sep 27 '22 18:09

robertklep


If you want to get via caravan.month then:

module.exports = {
    month: "july"
};
like image 31
Arun Ghosh Avatar answered Sep 27 '22 17:09

Arun Ghosh