Bogdan M. Bogdan M. - 5 months ago 10
Node.js Question

How to access global variables from required() file in Node?

Let's say I have 2 files:

main.js
, and
module.js
:

//main.js
const myModule = require('./module');
let A = 'a';
myModule.log();


//module.js
module.exports = {
log() {
console.log(A);
}

}


When calling
myModule.log
,
A
is not defined. Is there any way I can make global vars from
main.js
available in
module.js
? Thanks.

Answer

Use force, use global

const myModule = require('./module');
let A = 'a';
global.A = A
myModule.log();