0

by using module.exports = var; and const var = require("./file.js"); we can access a variable from another file but the imported variable is static and cannot change even if the original variable changes in the original file, how can I export an array that can be updated at any time and accessible in real time in another file?

  • 1
    It sounds like you might need a [singleton](https://stackoverflow.com/questions/13179109/singleton-pattern-in-nodejs-is-it-needed)? – evolutionxbox Feb 25 '22 at 16:56
  • `but the imported variable is static and cannot change even if the original variable changes in the original file` I'm not sure this is true. Try creating a situation where you change some property of `var` in the original file, and see if that property of `var` is also changed in the file you exported to. I think you'll find that `var` is fully mutable like any other javascript object. – TKoL Feb 25 '22 at 16:59
  • `even if the original variable changes in the original file` -- I actually suspect you mean that you're reassigning the variable in the original file. Yes, that's right, and that's how javascript works *in general*, not just with imports and exports. If one environment passes a variable to another environment, and then the first environment redefines that variable, the second environment won't know about the first environment's newly assigned value. – TKoL Feb 25 '22 at 17:06
  • You should not use var as a variable name, it is a reserved word for assigning variables the old fashioned way. `const` `let` `var`. – Cal Irvine Feb 25 '22 at 17:39

2 Answers2

0

put your variable inside of a function that returns the variable then export the function

export function getVariable(){
  let myVar = 0;
  return myVar
}
module.exports = getVariable;

const getVar = require('../file.js');
0

If you are storing the variable somewhere in the code by which you can differentiate between the files that you're interested in reading.

You might use the following approach by which you change the file name dynamically with the variable.

const readFile = async() => {
    try {
        const num = 1;
        // your variable which will be used to change the destination file. 
        let world = await fs.promises.readFile(path.join(__dirname, `data/fileName${num}.json`), "utf8");
        world = JSON.parse(world);
        console.log(world);
        // data you're intrested in! 
    } catch (err) {
      console.log(err);
    }
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Tanay
  • 33
  • 6