Node.js Global Variables
In Node.js, variables can be set to the global scope by omitting the var keyword when defining them. However, it's important to note that this method has certain limitations.
You mentioned encountering an issue where assigning _ to the global scope using the following syntax did not make it available in required files:
_ = require('underscore');
This is because, by default, Node.js modules are isolated from the global scope. To make a variable available globally, it must be explicitly assigned to the global object. Here's how you can do it correctly:
global._ = require('underscore');
By assigning _ to the global object, you ensure that it becomes available in the global scope and can be accessed by all modules.
It's worth noting that Express.js's app.set method provides a different way to set global variables. It allows you to set application-specific settings and make them available within the Express.js application. However, these settings are not accessible outside of the Express.js context.
In summary, to set a variable to the global scope in Node.js, use the global object as shown above. Omitting the var keyword when defining variables does not set them to the global scope by default.
The above is the detailed content of How to set global variables in Node.js?. For more information, please follow other related articles on the PHP Chinese website!