Sometimes, we want to share variables between files in Node.js.
In this article, we’ll look at how to share variables between files in Node.js.
How to share variables between files in Node.js?
To share variables between files in Node.js, we export the variables and then import them where we want to use them.
For instance, we write
module.js
const name = "foobar";
exports.name = name;
to export the name variable with
exports.name = name;
Then we import module.js and use name in main.js with
const myModule = require("./module");
const name = myModule.name;
Conclusion
To share variables between files in Node.js, we export the variables and then import them where we want to use them.