Home > OS >  How do I stop variables from overwriting in nodejs when requiring them on a main file?
How do I stop variables from overwriting in nodejs when requiring them on a main file?

Time:11-18

I have multiple scripts that are almost the same but with different parameters on a 'params' object set on top level. When I require() the scripts on the same file to run them at the same time, the 'params' object gets overwriten and only the last required 'params' is used. How do I stop this?

File 1:

params = {
        name: "John",
        salary: "50"
    }

File 2:

params = {
        name: "Victoria",
        salary: "10"
    }

File 3:

params = {
        name: "Veka",
        salary: "80"
    }

Main file:

require(file1.js)();
require(file2.js)();
require(file3.js)();
// do things

I know I could change the name for every file, but I think Im missing something. Thank you in advance.

CodePudding user response:

What is the desired behavior? You seem to have one global variable and it naturally can't hold several distinct values at once. If you need to have access to data provided by all three files and you need it to be a global variable (as opposed to, say, making your files into value-returning functions) then you can instead make it an array or object that the individual files insert into.

Array:

Main file before require calls:

params = []

File 1 (same for other files):

params.push({
    name: "John",
    salary: 50
});

Object:

Main file:

params = {}

File 1:

params['file1'] = {
    name: "John",
    salary: 50
};

Alternative

Use of globals is discouraged unless absolutely necessary because they lead to confusing bugs and are hard to debug. Instead, you can do:

File 1

function getData() {
  return {
    name: 'John',
    salary: 50
  };
}
module.exports = getData;

Main file:

const file1Data = require('./file1.js')();

CodePudding user response:

You need to understand closure and variable scope in Javascript.

Here an interresting articles.

So, you need to encapsulate those variable in their own function.

const yourFunctionFile1 = () => {
   const params = {
        name: "Veka",
        salary: "80"
    }
   // do whatever you want
}
module.exports = yourFunctionFile1

CodePudding user response:

You can export the params object in each file and then require them in your main file as variables:

File 1:

module.exports.params = {
  name: "John",
  salary: "50"
}

File 2:

module.exports.params = {
  name: "Victoria",
  salary: "10"
}

Main file:

let params1 = require('./file1').params
let params2 = require('./file2').params
  • Related