Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
nodejs import dynamic variable from another file

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report

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');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!