Wednesday, 7 June 2017

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?



via alexcs

No comments:

Post a Comment