alexcs
alexcs

Reputation: 540

Node.js - Globals config file with inter-dependent variables

I have a globals.js file that needs to be accessible across multiple files in my app.

These globals are inter-dependent, and I would like to set up my data file so that the parameters are relative to one another. I am trying the following:

const config = {
  "canvas": {
    "width": 600,
  },
  "shape": {
    "width": function() {
      return config.canvas.width*0.9;
    };
  },
};

module.exports = config;

The idea is that if I change the canvas.width property, all changes will cascade down.

A big problem with this approach is that now I need to remember which global variables are functions. So for example in another file I would need to access it like this:

const config = require('./globals.js');
let width = config.shape.width();

Ideally I would like to access all globals as normal properties. To be clear, none of this needs to be dynamic (ie, recalculated at runtime) - once the app is running all these globals can be set in stone.

What's the best way to achieve this? Should I somehow "pre-compute" or "pre-build" the object?

Upvotes: 0

Views: 43

Answers (1)

tmcw
tmcw

Reputation: 11882

You're likely looking for JavaScript's get syntax, which lets you access computed values as if they were properties. From your example, it's not obvious that this is absolutely necessary, since you could remember that you need to call a function. But if you really want to avoid explicit function calls, use a getter.

Upvotes: 1

Related Questions