John Glabb
John Glabb

Reputation: 1621

How to access global variable from main Node.js module?

I have simple app.js that contains simple variable, e.g.:

app.js

const HW = "Hello, world!";
var config = require('./config');

How do I access that HW variable from config.js? config.js

console.log(HW);

does exports in app.js really set it visible in config.js?

Upvotes: 0

Views: 968

Answers (1)

Lukas Bach
Lukas Bach

Reputation: 3919

In order to see a variable declared in another js file, you have to export it in that file and import/require it in the file which needs a reference to that variable. So if you have a const variable in app.js named HW, you have to export it:

app.js

const HW = "Hello, world!";
module.exports.HW = HW;

And then import it in your other file:

config.js

var HW = require("app.js").HW;
console.log(HW);

Upvotes: 1

Related Questions