R. Tienzo
R. Tienzo

Reputation: 13

How to update a module.exports properly?

I have this file that stores some of my environment variables. Let's call it generalEnv.js

module.exports = {
  CONSTANT_1: process.env.CONSTANT_1,
  CONSTANT_2: process.env.CONSTANT_2
};

When the app initializes, I don't put the value of process.env.CONSTANT_1 in the env variables yet because I have to look into some places first if it exists(mongodb for instance). If it does not exists on mongodb, I will add a value into process.env.CONSTANT_1 and I was expecting that the value will reflect on generalEnv now.

When I tried accessing the CONSTANT_1 in another file. Let's call it getConstantOne.js

const { CONSTANT_1 } = require('./generalEnv');

module.exports = () => {
  // I was expecting that CONSTANT_1 will have a value here now
  if(!CONSTANT_1) {
    // do something
  }

  return CONSTANT_1
}

it does not reflect.. how do I update the closure of generalEnv.js for process.env.CONSTANT_1 to reflect on CONSTANT_1?

Upvotes: 0

Views: 506

Answers (1)

Viktor W
Viktor W

Reputation: 1149

When assigning to a variable (or a value in an object/element in an array), the assignment will replace the value, not modify it. Therefore, any "copies" of that value will not be affected, and remain the same. Consider this example:

let a = 0;
let b = a;
a = 1;

What happens to b? Answer: Its value is 0.

To work around this we need some way of modifying the value instead of replacing it. Unfortunately, "primitive types" (strings/numbers/booleans etc.) cannot be modified in javascript. There are types that can be modified however, such as objects. You could solve this by wrapping your variables in an object called "env".

let env: { 
  CONSTANT_1: process.env.CONSTANT_1,
  CONSTANT_2: process.env.CONSTANT_2
}
modules.exports = { env }

and then to modify:

env.CONSTANT_1 = "new value"

and to access:

if (!env.CONSTANT_1) { ... }

Upvotes: 1

Related Questions