kfx
kfx

Reputation: 8537

Dynamically set variables exported from a JavaScript module

I'm looking for something like Python globals() or locals() in the context of the new JavaScript modules.

Here is the situation: there are two modules, config.mjs and main.mjs. The first one defines configuration for the program, the second uses that configuration. The goal is to allow to override the default configuration defined in config.mjs by passing a JSON configuration file as an argument. However, I don't know how to indirectly reference the variables the config.mjs module exports?

config.mjs:

import fs from 'fs';

export let LOG_LEVEL = 1;

export function init()
{
    const config_file = fs.readFileSync("config.json");
    const config_struct = JSON.parse(config_file);
    for (const key in config_struct) {
        console.log(`  config_struct[${key}] = ${config_struct[key]}` );
        // how to automatically set the LOG_LEVEL variable from here?
    }
}

config.json:

{ "LOG_LEVEL" : 2 }

main.mjs:

import * as config from "./config";

config.init()
console.log(config.LOG_LEVEL);

The program currently prints 1, but I would like it to print 2 — the value from the config file.

Upvotes: 0

Views: 992

Answers (2)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

If there are many keys possible in the config.json file then you can make use of spread operator:

config.mjs:

import fs from 'fs';

const configFile = fs.readFileSync("config.json");
const configStruct = JSON.parse(configFile); // assuming it exists, some check would be useful here

const defaultConfig = {
    LOG_LEVEL: 1,
    LOG_DIR: '/var/log/app.log',
    ...configStruct
};


export defaultConfig;

config.json:

{
    "LOG_LEVEL": 2
}

The spread operator in the first file will override only values that exist in configStruct (which is the content of config.json).

Does that work for you?

Upvotes: 2

Uthistran Selvaraj
Uthistran Selvaraj

Reputation: 1371

The below changes should work I hope. not sure about the LOG_LEVEL variable declaration.

config.mjs:

import fs from 'fs';

export let LOG_LEVEL = 1;

export function init()
{
    const config_file = fs.readFileSync("config.json");
    const config_struct = JSON.parse(config_file);
    LOG_LEVEL = config_struct["LOG_LEVEL"];
}

Upvotes: 0

Related Questions