2

I'm trying to create a require which is unique for each require use, file 1, 2, 300 etc all have a require say of a file called test.js. this can then be disabled in one file but it's variables be untouched in the other files.

File1.js

const test = require("./test.js");
// NOTE enabled boolean in test is default = true
test.enabled = false; // or test.disable();
test.sayHello(); // will output nothing as enabled = false

File2.js

const test = require("./test.js");
test.sayHello(); // Should output hello but it as file1 set enabled to false it dosnt

What would test.js look like to achieve this functionality?

I am currently having to do this via an argument in the module.exports function, which is not ideal. eg disable would be test direct return of the function and then a 2nd optional argument for enable/disable. Which is meh...

Thanks

D

Darcey
  • 1,949
  • 1
  • 13
  • 22

1 Answers1

3

Even though you can clear require cache, I would consider that, for your particular case a bad practice.

Instead your require call should return a class and then you will use a new instance of that class on every file, and disable/enable that instance when needed.

test.js

class Test {

    disable() {
        this.disable = true;
    }

    sayHello() {
        if(this.disable)
            return false;

        console.log('hello')
    }

}

module.exports = Test;

index.js

const Test = require('./test.js');
const test = new Test();
test.disable();
test.sayHello(); // nothing is printed

const otherTest = new Test();
otherTest.sayHello(); // 'hello'
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98