I'd like to split my Node app into several separate files to make it more modular and easier to maintain.
But since there is no way to 'include' a file directly into the currently parsed file like in other languages like PHP, my 'modules' or 'separate files' do not automatically get access to the variables defined in the script that 'requires' them.
How can I do this?
I was thinking about doing something like this in my separate files:
module.exports = function(stuff) {
//I now have access to 'stuff'.
}
But it's slightly cumbersome.
I'm sure someone has already tackled this before me so... what do you suggest?
The easiest way to share variables across modules is to assign the variables to the global namespace object. Variables declared how they would be globally declared in a browser are still module-specific in Node, so there is a global
object.
Using the global scope is considered bad practice, but can be much simpler than other approaches:
foo.js
global.num = 3;
global.str = 'a string';
require('./bar');
bar.js
console.log(num); // 3
console.log(str); // a string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With