Home > Software engineering >  nodejs import dynamic variable from another file
nodejs import dynamic variable from another file

Time:02-26

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?

CodePudding user response:

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');

CodePudding user response:

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);
    }
}

  • Related