Reputation: 15
I have app.js here:
let x = 5;
const print = require('./print')
print()
I have print.js here
module.exports = function(){
console.log(x)
}
Is there a good way I can use the variables in app.js in the print.js function? I'm working with much more variables in my actual application so I would like to avoid using parameters.
Upvotes: 0
Views: 438
Reputation: 708046
You can't or shouldn't. That's not how the modular architecture in node.js works. Unlikely the messy world of the browser where many bodies of code just declare a zillion things in the global scope that everything can then use, node.js is modular. Each file is typically its own module. It must export things that it wishes to share and other modules must import it's exports in order to use them.
If you want to share data with another module, you call some function and pass it that data.
While there are globals in node.js (you can assign things like global.x = 5
and then reference those anywhere), using globals are strongly, strongly discouraged for anything except built-in node.js functionality defined by the platform (not defined by an app).
There are dozens of reasons why globals are problematic and it gets worse the larger a project is, the more people there are working on it or the more 3rd party code libraries you use. If you really want to know more about that, you can just search "why are globals bad in Javascript" and find all sorts of discussion on the topic.
The modular architecture of node.js is one of the reasons that we have NPM and tens of thousands of easily reusable modules of code that work in node.js. These pieces of code all use the same modular architecture making them able to uniformly be used in any app with far less risk of symbol conflicts or modules conflicting with existing code. And, the modular architecture clearly defines dependencies on other pieces of code so a module can be self-contained and load any of the modules it depends on, even different versions of a module than other code in the project is using. None of that works when sharing code via globals.
I will repeat. In node.js, if you want to share a function or data between modules, you export that in one module and import it in another module.
Upvotes: 1
Reputation: 1224
Assign those variables to the global
object.
global.x = 5;
const print = require('./print')
print()
module.exports = function(){
console.log(global.x)
}
Upvotes: 0