stackiee
stackiee

Reputation: 309

Node.js: Sharing object data between multiple files

I am creating an Electron application and would like to create one Config type object that is shared throughout the application. My initial idea was to use a singleton, but that only worked when I was creating new instances of an object within the same file where the class was created.

What I am trying to achieve is having one Config object whose data is shared between multiple require() statements in different files. I hope the example below clears things up. In other words, once file1.js starts modifying variables within the config object, I want file2.js to see those changes. The two files should then be able to almost 'share' the data in the object.

The only idea I can think of is to use global variables and then just make all the class functions static. So instead of this.variable = '...'; I would use global.variable = '...';. That way even if multiple objects of the Config class were created, they would still share the variable values. Would this be the better route to take?

Local Files:

-- ../lib/config.js --

class Config {
    constructor(){
        if(!Config.instance){
            console.log('creating instance');
            this.variable = '...';
            Config.instance = this;
        }

        console.log('returning instance');
        return Config.instance;
    }

    getValue() { return this.variable }
   
    setValue(val) { this.variable = val }
}

const configHandler = new Config();
module.exports = configHandler;
--file1.js--

const config = require('../lib/config');
--file2.js--

const config = require('../lib/config');

Current console output

creating instance
returning instance
creating instance
returning instance

Expected console output

creating instance
returning instance
returning instance

Upvotes: 2

Views: 1356

Answers (1)

stackiee
stackiee

Reputation: 309

I was able to achieve what I wanted by using global variables.

class Config {
    constructor(){
        this.variable = '...';
    }

    getValue() { return this.variable }
   
    setValue(val) { this.variable = val }
}

if (!global.configHandler) {
    global.configHandler = new Config();
    module.exports = configHandler;
} else {
    module.exports = global.configHandler;
}

Basically, if the config object already exists in the global scope I export the object. If not, I create the new config object, set it to a global variable, and then finally I export the variable.

Upvotes: 1

Related Questions