Using Global Variables in Node.js
In Node.js, you may have encountered the concept of setting variables to the global scope, which can be achieved by omitting the variable declaration keyword. However, it's important to note that this approach does not make the variable available to required files.
If you attempt to do this, the underscore library won't be accessible in your required files, despite the following code:
<code class="js">_ = require('underscore');</code>
Alternatively, Express.js allows you to set variables using app.set, making them available elsewhere. However, this approach is specific to Express.js.
To set a variable in the global scope, you need to use the global object, as shown below:
<code class="js">global._ = require('underscore');</code>
This will make the underscore library accessible in all your required files. Remember that global variables can lead to namespace pollution, so use them with caution and only when necessary.
The above is the detailed content of How do I make variables accessible in all files in Node.js?. For more information, please follow other related articles on the PHP Chinese website!