Changing same instance of variable from other file nodejs
I'm not sure how to formulate an explanation, but I want to know how I can change a variable from the index.js file in another file. I thought by doing module.exports=(thing you want to export) then requiring the file will allow me to access the same instance of that variable, but it seems like it returns undefined. Bare in mind, I'm new to nodejs and I want to learn.
in index.js:
const multiVerse={stuff};
module.exports=multiVerse;
in other js file I want to use this in:
const main = require(./index.js)
//change data of object
main.multiVerse;
question: how can I access a variable from the index file in some other place in the project?
Solution 1:
const multiVerse = {foo: 'bar'};
module.exports = multiVerse;
// ...
const main = require('./index.js');
main.foo = 'baz';
or
const multiVerse = {foo: 'bar'};
module.exports = { multiVerse };
// ...
const main = require('./index.js');
main.multiVerse.foo = 'baz';
or
const multiVerse = {foo: 'bar'};
module.exports = { multiVerse };
// ...
const { multiVerse } = require('./index.js');
multiVerse.foo = 'baz';
Solution 2:
you can export like this -
in index.js
exports.variableA = 'some_value';
in other.js
var indexExports = require('./index');
...
...
indexExports.variableA = 'Any_value';