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 can put our shared variables in a module.
For instance, we write
module.js
const name = "foobar";
exports.name = name;
to export the name
variable in module.js by assigning it to exports.name
.
And then in main.js, we write
main.js
const myModule = require('./module');
const name = myModule.name;
to call require
to include the module.js module and assign the exported contents to myModule
.
And then we get the exports.name
value with myModule.name
,
Conclusion
To share variables between files in Node.js, we can put our shared variables in a module.