I have this in file data.js:
module.exports = {
data: {
value: 42
}
};
I am importing that in file test.js:
function load(fileName) {
const {data} = require(fileName);
data.value += 5;
return data;
}
for (let i = 0; i < 5; i++)
console.log(load("data.js"));
When I execute node test.js, the printout is:
{ value: 47 }
{ value: 52 }
{ value: 57 }
{ value: 62 }
{ value: 67 }
I expected { value: 42 } to be printed in every iteration, but I understand that probably data references the object returned from require(fileName), so changing data.value impacts the contents of that object.
But what I don't understand is, why the require statement isn't executed "from scratch", i.e., on the original input file.
Of course, I can work around this by changing data.js into a properly formatted JSON file, and then load that file using something like:
const data = JSON.parse(fs.readFileAsync(data.json));
But I would like to get a deeper understanding of why using a require statement is inappropriate in this case.
Thanks!